by Dinesh Thakur Category: Control Structures

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;


      printf("Enter expression of the form a op b:\n");

      scanf("%f %lc %f", &a, &op, &b);

      switch (op)


             case '+':

                    c = a + b;


             case '-':

                    c = a - b;


             case '*':

             case 'x':

             case 'X':

                    c = a * b;


             case '/':

                    c = a / b;



             printf("c =%f\n", c);



    C Program for Simple Calculator

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.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles