Switch case statements are used to execute only specific case statements based on the switch expression. The switch statement allows us to execute one code block among many alternatives. You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.
if...else statement provides support to control program flow. if statement make decisions based on conditions. It selects an action, if some condition is met. However, there exits situations where you want to make a decision from available choices. For example - select a laptop from available models, select a menu from available menu list etc.
switch...case statement gives ability to make decisions from fixed available choices. Rather making decision based on conditions. Using switch we can write a more clean and optimal code, that take decisions from available choices.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
How does the switch statement work?
The expression is evaluated once and compared with the values of each case label.
If we do not use break, all statements after the matching label are executed.
Rules for working with switch case
Flowchart of switch...case statement
Example program of switch case: Simple Calculator
// Program to create a simple calculator
#include <stdio.h>
int main() {
char operator;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
// operator doesn't match any case constant +, -, *, /
default:
printf("Error! operator is not correct");
}
return 0;
}
Output
Enter an operator (+, -, *,): *
Enter two operands: 5
10
5 * 10 = 50