Definition: The switch-case statement is a decision-making control structure used to select one block of statements from multiple possible choices based on the value of an expression.
Definition: The switch-case statement
is a decision-making control structure used to select one block of
statements from multiple possible choices based on the value of an
expression.
switch-case to display a day name
based on a number from 1 to 7.
switch (expression)
{
case value1:
statement;
break;
case value2:
statement;
break;
default:
statement;
}
case: Defines one possible value to compare with the switch expression.
case 1: can represent Monday when the input is 1.
break: Ends the current case and prevents execution from continuing into the next case.
break; stops the switch
from executing the next case.
default: Executes when none of the specified case values match the expression.
default block executes.
A menu-driven application can use switch-case when
the user has to choose one option from a fixed list of choices.
Write a C program that accepts a number from 1 to 7 and displays
the corresponding day of the week using switch-case.
switch-case construct to select among several fixed outcomes.break statement.default to handle invalid input.
Map 1 to Monday, 2 to Tuesday,
and so on up to 7 to Sunday. Use
default for values outside this range.
The switch statement compares one expression with a
list of constant case values and executes the matching case.
The break statement ends the case, while
default handles values that do not match any case.
#include <stdio.h>
int main()
{
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
// match the input number to the corresponding day
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 input
");
}
return 0;
}
Enter a number (1-7): 3 Wednesday
Forgetting break can cause fall-through,
where execution continues into the next case. The
default case is useful for handling invalid input.
| switch-case | if-else |
|---|---|
| Useful when one expression is compared with fixed values. | Useful for conditions and ranges. |
Uses case, break and default. |
Uses if, else if and else. |
| Good for menu-driven choices. | Good for relational and logical conditions. |
Watch a beginner-friendly explanation of switch-case in C.
A short handwritten-style revision sheet for switch-case will be provided here.
Use the mind map for quick revision of switch, case, break and default.