# Program to simulate calculator using switch in C

The input is the expression of the form (a op b) where a and b are the operands and op is an operator. For example 10+20. Based on the operator, the operation is performed and the result is displayed. The complete algorithm along with the flowchart is shown below:

Read: a, op, b

switch(op)

case "+" : res = a+b

case "-" : res = a-b

case "*" : res= a*b

case "/" : if (b==0)

Write : "Divide by 0"

Exit

else

res = a/b

[End of if]

default : Write: ' Invalid operator'

Exit

[End of switch]

Write: res

Exit.

The equivalent C program to perform various operations such as addition, subtraction, multiplication and division is shown below:

#include<process.h>

main( )

{

int a, b, res;

char op; /* can be +, - , *,, or / */

printf("Enter the expression");

scanf("%d%c%d",&a, &op, &b);

switch(op)

{

case '+' :

res = a+b;

break;

case '-':

res= a-b;

break;

case '*':

res=a*b;

break;

case '/' :

if(b!=0)

res=a/b;

else

{

printf("Div by 0\n");

exit(0);

}

default:

printf("Invalid operator \n");

}

/* end of switch statement */

printf("%d %c %d = %d\n",a,op,b,res); /* Display the result */

}

**Algorithm: CALCULATOR**

**Step 1:**[Read expression of from (a+b)]Read: a, op, b

**Step 2:**[perform the required operation]switch(op)

case "+" : res = a+b

case "-" : res = a-b

case "*" : res= a*b

case "/" : if (b==0)

Write : "Divide by 0"

Exit

else

res = a/b

[End of if]

default : Write: ' Invalid operator'

Exit

[End of switch]

**Step 3:**[Output the result]Write: res

**Step 4:**[Finished]Exit.

The equivalent C program to perform various operations such as addition, subtraction, multiplication and division is shown below:

### Program

#include<stdio.h>#include<process.h>

main( )

{

int a, b, res;

char op; /* can be +, - , *,, or / */

printf("Enter the expression");

scanf("%d%c%d",&a, &op, &b);

switch(op)

{

case '+' :

res = a+b;

break;

case '-':

res= a-b;

break;

case '*':

res=a*b;

break;

case '/' :

if(b!=0)

res=a/b;

else

{

printf("Div by 0\n");

exit(0);

}

default:

printf("Invalid operator \n");

}

/* end of switch statement */

printf("%d %c %d = %d\n",a,op,b,res); /* Display the result */

}

Program to simulate calculator using switch in C
Reviewed by Jacob Lefore
on
December 11, 2014
Rating:

## No comments