A switch case is used to select one among multiple options.
Can we use arithmetic operators in switch case:
Yes, We Can use we. To provide symbols in a case statement a single quote is used.
To perform arithmetic operations, we create a case for each operator, for the matching operator, it will call the appropriate case statements and execute the statements.
In our program, we will use a switch case statement and do while loop statement
You can check both details here
algorithm for arithmetic operations using switch case in c
Lets see steps to write this C program
- Declare variables
- start loop
- get num1 ,operator, num2 value from user
- start switch case and pass operator in switch case
- write the case for arithmetic operators and their associated statements
- define default in switch case
- Take input from the user to check loop continuity
- if the user enters yes then repeat steps 2-7 else end the loop.
C program for arithmetic operations using switch case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include<stdio.h> int main() { int num1,num2; char c,ch; do{ printf("\nEnter Num1 Operator [+,-,*,/] Num2 \n"); scanf("%d %c %d",&num1,&c,&num2); switch(c){ case '+': printf("\n%d+%d=%d",num1,num2,num1+num2); break; case '-': printf("\n%d-%d=%d",num1,num2,num1-num2); break; case '*': printf("\n%d*%d=%d",num1,num2,num1*num2); break; case '/': printf("\n%d/%d=%f",num1,num2,(float)num1/num2); break; default: printf("\nEnter valid operation : +, -, *, /"); } printf("\nEnter y to continue other character to end\n"); getchar(); scanf("%c",&ch); }while(ch=='y'); } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | Enter Num1 Operator [+,-,*,/] Num2 2 + 2 2+2=4 Enter y to continue other character to end y Enter Num1 Operator [+,-,*,/] Num2 3 * 2 3*2=6 Enter y to continue other character to end y Enter Num1 Operator [+,-,*,/] Num2 5 - 1 5-1=4 Enter y to continue other character to end y Enter Num1 Operator [+,-,*,/] Num2 5 / 6 5/6=0.833333 Enter y to continue other character to end y Enter Num1 Operator [+,-,*,/] Num2 1 + 2 1+2=3 Enter y to continue other character to end n |