You are here:   HomeC Programming (Theory)Control Structures in CWrite a C program to show working of continue.
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;

      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();

}

    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.



Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes 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.



What's New and Popular





Popular Article