In this lesson, you will learn about the switch…case statement in C, its usage, and examples to better understand the topic.
Switch… case is identical to the if-then… else control structure. It executes only one block of code depending on the condition’s value. If no condition is encountered, the default code block will be performed.
switch (var) { case control1: //block of code will be processed if var = control1; break; case control2: //block of code will be processed if var = control2; break; case control3: //block of code will be processed if var = control3; break; default: //block of code will be processed if var is different from all controls; }
“Switch (…) { … }” is the control structure block code “case value: case …” which is the code blocks to be executed depending on the value that matches the “default” condition value: is the code block to be executed if no value matches the condition.
Note: Switch Statement without break keyword; all cases will be executed.
//C Program *** Switch Statement*** #include <stdio.h> int main() { char luxuryCars; printf("Enter the any alphabet to win a car: "); scanf("%c", & luxuryCars); switch (luxuryCars) { case 'A': printf("Congratulation!!Your won Audi luxury car!"); break; case 'F': printf("Congratulation!!Your won Ferrari luxury car!"); break; case 'V': printf("Congratulation!!Your won Volvo luxury car!"); break; default: printf("Sorry, better luck next time!"); } return 0; }
Output
Enter the any alphabet to win a car: F Congratulation!!Your won Ferrari luxury car!
Don’t miss the break keyword! Below is a similar program, but without the break keyword. You will notice that all cases will be printed out to the output.
//C Program *** Switch without break Statement*** #include <stdio.h> int main() { char luxuryCars; printf("Enter the any alphabet to win a car: "); scanf("%c", & luxuryCars); switch (luxuryCars) { case 'A': printf("Congratulation!!Your won Audi luxury car!\n"); //break; case 'F': printf("Congratulation!!Your won Ferrari luxury car!\n"); //break; case 'V': printf("Congratulation!!Your won Volvo luxury car!\n"); //break; default: printf("Sorry, better luck next time!"); } return 0; }
Output
Enter the any alphabet to win a car: A Congratulation!!Your won Audi luxury car! Congratulation!!Your won Ferrari luxury car! Congratulation!!Your won Volvo luxury car! Sorry, better luck next time!
In the next lesson, you will learn about other essential topics in C Language Programming, Loops!