Article by: Manish Methani
Last Updated: November 4, 2021 at 2:04pm IST
The Switch statement is a selection statement in C that allows you to execute different statements depending on the value of an expression. It's similar to an if-else statement but it's more concise and easier to read when you have to compare a large number of values.
In this tutorial, we'll go through everything you need to know about the switch statement in C, including its syntax, usage, and some examples.
switch(expression) { case constant-expression: statement(s); break; case constant-expression: statement(s); break; . . . default: statement(s); }
Now let's take a look at some examples to understand the usage of the switch statement.
#include int main() { int day = 3; switch (day) { case 1: printf("Monday"); break; case 2: printf("Tuesday"); break; case 3: printf("Wednesday"); break; case 4: printf("Thursday"); break; case 5: printf("Friday"); break; case 6: printf("Saturday"); break; case 7: printf("Sunday"); break; default: printf("Invalid day"); } return 0; }
In this example, we have a simple switch statement that takes an integer variable day
and prints the corresponding day of the week. If the value of day
is not between 1 and 7, it prints "Invalid day". The output of this program will be "Wednesday".
#include int main() { int score = 85; switch (score) { case 80: case 81: case 82: case 83: case 84: printf("Grade B"); break; case 85: case 86: case 87: case 88: case 89: printf("Grade A-"); break; case 90: case 91: case 92: case 93: case 94: printf("Grade A"); break; default: printf("Invalid score"); } return 0; }
In this example, we have a switch statement that takes an integer variable score
and prints the corresponding grade. If the value of score
is between 80 and 84, it prints "Grade B". If it's between 85 and 89, it prints "Grade A-". If it's between 90 and 94, it prints "Grade A". If the value of score
is not between 80 and 94, it prints "Invalid score". The output of this program will be "Grade A-".
That's it for this tutorial. We have covered the basics of the switch statement in C with some examples. I hope this tutorial has been helpful for you to understand the switch statement in C.