switch case Statement in C
Notes:
switch case statement in C programming language:
- When there is more than one alternative choice present, we use switch case statement.
syntax:
switch(expression)
{
case label-1:
statements;
break;
case label-2:
statements;
break;
…
default:
statements;
break;
}
Note:
- Computer executes the case whose label matches the value of the given expression
- A value or a variable name followed by a colon symbol indicates a label
- A given expression must be evaluated to an integer constant, no other type is allowed
- Every case must be terminated with a break statement
- All cases under the matching case are executed; until a break statement or end of switch block is hit
- break statement transfers the control outside the switch block
- default case is executed when there is no matching case found
- The position of the default case does not matter
- Last case in the switch block need not be terminated with break statement
Example Code: Program to display an equivalent day name for the given day number
#include <stdio.h>
int main()
{
int day = 1;
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\n");
}
printf("Outside switch\n");
return 0;
}