Switch Case Statement in C
In this chapter, we will continue the conditional statements and this marks the formal completion of repititive statements.
Switch Case Statement
Switch case statement in C is a conditional statement that is used to select one of many possible actions. It can be used as an alternative to if-else statements, and can be more efficient than if-else statements in some cases.
The syntax is:
Here, we have used break statement to stop the execution of the statements after the first match. Hence, only the first matched statement is executed.
The syntax is:
switch ( expression ) {
case value:
// expression 1
break;
case value:
// expression 2
break;
.
.
.
default:
// default expression
}
The expression inside the switch statement is evaluated once. The value of the expression is compared with each case label. If there is a match, the associated statement is executed, and then all the statements are executed. If there is no match, the statement following the default label is executed.
case value:
// expression 1
break;
case value:
// expression 2
break;
.
.
.
default:
// default expression
}
Here, we have used break statement to stop the execution of the statements after the first match. Hence, only the first matched statement is executed.
Let's have a look at an example
C
#include <stdio.h>
int main()
{
int day;
printf("Enter the day number: ");
scanf("%d", &day);
switch(day) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid day");
}
return 0;
}
int main()
{
int day;
printf("Enter the day number: ");
scanf("%d", &day);
switch(day) {
case 1:
printf("Sunday\n");
break;
case 2:
printf("Monday\n");
break;
case 3:
printf("Tuesday\n");
break;
case 4:
printf("Wednesday\n");
break;
case 5:
printf("Thursday\n");
break;
case 6:
printf("Friday\n");
break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid day");
}
return 0;
}
Output
Enter the day number: 3
Tuesday
Tuesday
Explanation
The input of the user is stored in the variable day, and the value of day is compared with each case label. If the value of day be 3, then it matches with case 3 and then the statement inside the case 3 is executed. It prints the string "Tuesday", and since the break statement is used, the control is transferred to the next statement immediately after the switch statement.