Let us use variables a and b of type float to represent two operands, variable c of type float to represent the result and variable op of type char to represent the operator. In the program given below, an expression of the form a op b is first accepted from the keyboard and a switch statement is used to evaluate the result.
The operator op is used as test expression in the switch statement and four cases correspond to the given operators. In each case, the desired value is evaluated in variable c. This value is printed using a printf statement after the switch statement.
/* Simple calculator: evaluates expression of form a op b */
#include <stdio.h>
void main()
{
float a, b, c; /* operands */
char op;
clrscr();
printf(“Enter expression of the form a op b:\n”);
scanf(“%f %lc %f”, &a, &op, &b);
switch (op)
{
case ‘+’:
c = a + b;
break;
case ‘-‘:
c = a – b;
break;
case ‘*’:
case ‘x’:
case ‘X’:
c = a * b;
break;
case ‘/’:
c = a / b;
break;
}
printf(“c =%f\n”, c);
getch();
}
Observe that the case values are character constants: ‘+’ , ‘- ‘, ‘ * ‘, ‘x ‘, ‘x’ and ‘/ ‘. Also, an operator is accepted from the keyboard using the %lc format in the scanf statement.