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 */
float a, b, c; /* operands */
printf(“Enter expression of the form a op b:\n”);
scanf(“%f %lc %f”, &a, &op, &b);
c = a + b;
c = a – b;
c = a * b;
c = a / b;
printf(“c =%f\n”, c);
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.