Search Result
Details here...

Switch Case Statement in C

Previous

Break and Continue in C

Next

Introduction to Functions


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:
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.

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.

Did you notice?

The value after each case label is compared with the expression inside the switch statement.

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;
}

Output

Enter the day number: 3
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.

Woow!

Are you planning to make a simple CLI calculator app? Don't forget to use the switch statement.

Info

If the break statement isn't used, then all the codes after the match will be executed.
In that case, the output would be:

Output

Enter the day number: 3
Tuesday
Wednesday
Thursday
Friday
Saturday
Invalid day
Even the default case is executed.

Info

The example of a simple calculator app is present in the example section of the course.

By darpan.kattel
Previous

Break and Continue in C

Next

Introduction to Functions