BPOPS103/203
Principles of Programming using C Lab
1. Simulation of a Simple Calculator.
Algorithm:
Step 1: START
Step 2 : Read two numbers
say num1 and num2
Step 3: Read arithmetic operator(+,-,*,/)
say it as op
Step 4: Check if op is matching with '+'
Compute result=num1+num2
display result
Check if op is matching with '-'
Compute result=num1-num2
display result
Check if op is matching with '*'
Compute result=num1*num2
display result
Check if op is matching with '/'
Check if num2 is 0
Display the given operation cannot be performed
else
Dept. of AI & DS, SMVITM, Bantakal Page 1
BPOPS103/203
Principles of Programming using C Lab
Compute result=num1/num2
display result
else
display Error Message
Step 5: STOP
Dept. of AI & DS, SMVITM, Bantakal Page 2
BPOPS103/203
Principles of Programming using C Lab
Flowchart:
Dept. of AI & DS, SMVITM, Bantakal Simple Calculator
Page 3
BPOPS103/203
Principles of Programming using C Lab
Program:
#include<stdio.h>
#include<stdlib.h>
void main()
{
float num1, num2, result;
char op;
printf(“Enter the operator (+,-,*./) \n”);
scanf(“%c”, &op);
printf(“Please enter two numbers:\n”);
scanf(“%f %f”, &num1, &num2);
if(op = = ’+’ )
Dept. of AI & DS, SMVITM, Bantakal Page 4
BPOPS103/203
Principles of Programming using C Lab
{
result = num1 + num2;
printf(“Result is %0.2f \n”, result);
else if(op = = ’-’ )
{
result = num1 - num2;
printf(“Result is %0.2f \n”, result);
}
else if(op = = ’*’ )
{
result = num1* num2;
printf(“Result is %0.2f \n”, result);
}
Dept. of AI & DS, SMVITM, Bantakal Page 5
BPOPS103/203
Principles of Programming using C Lab
else if(op = = ‘/ ’ )
{
if(num2 = = 0)
{
printf(“Please enter non zero no. For num2: \n”);
exit(0);
}
else
{
result = num1 / num2; printf(“Result is %0.2f\n”,result);
}}
else
{
printf (“Entered operator is invalid \n”);
Dept. of AI & DS, SMVITM, Bantakal Page 6
BPOPS103/203
Principles of Programming using C Lab
}}
Command to execute the Program:
$ cc lab1.c
$ ./a.out
OUTPUT:
Case 1: Enter the operator (+,-,*,/)
+
Please enter two numbers: 4 2
Result is 6.00
Case 2: Enter the operator (+,-,*,/)
-
Please enter two numbers: 4 2
Result is 2.00
Case 3: Enter the operator (+,-,*,/)
*
Please enter two numbers: 4 2
Result is 8.00
Case 4: Enter the operator (+,-,*,/)
/
Please enter two numbers: 4 2
Result is 2.00
Dept. of AI & DS, SMVITM, Bantakal Page 7
BPOPS103/203
Principles of Programming using C Lab
Case 5: Enter the operator (+,-,*,/)
?
Please enter two numbers: 4 2
Entered operator is invalid
Case 6: Enter the operator (+,-,*,/)
/
Please enter two numbers: 4 0
Please enter non zero no. For num2
Dept. of AI & DS, SMVITM, Bantakal Page 8