C Program for simple calculator to perform addition subtraction multiplication and division based on the symbol using switch statement
Program
#include<stdio.h>
#include<stdlib.h>
void main()
{
float a, b, result;
char opcode;
printf("Enter two numbers\n");
scanf("%f %f", &a, &b);
printf("Enter\n'+' to add\n'-' to subtract\n'*' to multiply\n'/' to divide\n");
scanf(" %c", &opcode);
switch(opcode)
{
case '+':
result = a + b;
printf("Sum of %f & %f is : %f\n", a, b, result);
break;
case '-':
result = a - b;
printf("Subtraction of %f & %f is : %f\n", a, b, result);
break;
case '*':
result = a * b;
printf("Multiplication of %f & %f is : %f\n", a, b, result);
break;
case '/':
if(b == 0)
{
printf("Divide By Zero Error\n");
exit(0);
}
else
{
result = a / b;
printf("Division of %f & %f is : %f\n", a, b, result);
}
break;
default:
printf("Invalid Operator\n");
}
}
Output 1
Enter two numbers
71
20
Enter
'+' to add
'-' to subtract
'*' to multiply
'/' to divide
+
Sum of 71.000000 & 20.000000 is : 91.000000
Output 2
Enter two numbers
9
3
Enter
'+' to add
'-' to subtract
'*' to multiply
'/' to divide
-
Subtraction of 9.000000 & 3.000000 is : 6.000000
Output 3
Enter two numbers
6
5
Enter
'+' to add
'-' to subtract
'*' to multiply
'/' to divide
*
Multiplication of 6.000000 & 5.000000 is : 30.000000
Output 4
Enter two numbers
6
3
Enter
'+' to add
'-' to subtract
'*' to multiply
'/' to divide
/
Division of 6.000000 & 3.000000 is : 2.000000
Output 5
Enter two numbers
9
0
Enter
'+' to add
'-' to subtract
'*' to multiply
'/' to divide
/
Divide By Zero Error