In this tutorial you will learn about the C Switch Case Statement and its application with practical example.
In C programming, It evaluates an expression against multiple cases in order to identify the block of code to be executed. A switch case statement is a simplified form of the Nested if-else statement, it helps to avoid a long chain of if..else if..else statements.
Flow Diagram
C Switch Case Statement Syntax
Below is the general syntax of switch case in c programming:
Syntax:-
1 2 3 4 5 6 7 8 9 10 11 |
switch(expression){ case value1: // statements break; case value2: // statements break; default: // statements break; } |
Example of Switch Case
Below is a simple example to demonstrate the use of the present statement in c programming:
Example:-
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 |
#include <stdio.h> int main() { int dayOfWeek = 5; printf("W3Adda - C Switch Case statement.\n"); switch(dayOfWeek){ case 1: printf("Today is Monday.\n"); break; case 2: printf("Today is Tuesday.\n"); break; case 3: printf("Today is Wednesday.\n"); break; case 4: printf("Today is Thursday.\n"); break; case 5: printf("Today is Friday.\n"); break; case 6: printf("Today is Saturday.\n"); break; case 7: printf("Today is Sunday.\n"); break; default: printf("Invalid Weekday.\n"); break; } } |
In the above program, we have an integer variable dayOfWeek with an initial value of 5, and we pass this variable as an expression to the following switch statement, value of dayOfWeek is tested with multiple cases to identify the block of code to be executed. When we run the above C program, will see the following output –
Output:-