A value is obtained when the expression given inside the switch(expression) statement is checked.
The value found in the expression and the value given in the keyword case page will be compared.
If the two values are equal when compared, all the statements in that case will be executed.
After all the statements are executed, the last break statement is executed.
If you don't give a break statement then all the statements below it will be executed.
If the expression value and the case value are not equal, the statements in the default block will be executed.
This is how the switch statement works.
syntax:-
switch(expression)
{
case value 1:
//statements
break;
case value 2:
//statements
break;
.
.
.
default;
//default statement
}
EXAMPLE:
#include<stdio.h>
#include<conio.h>
void main()
{
int day;
printf("Enter a number between 1 to 7");
scanf("%d",&day);
switch(day)
{
case 1:
printf("monday\n ");
break;
case 2:
printf("tuesday\n ");
break;
case 3:
printf("wednesday\n ");
break;
case 4:
printf("thrusday\n ");
break;
case 5:
printf("friday\n ");
break;
case 6:
printf("saturday\n ");
break;
case 7:
printf("sunday\n ");
break;
default:
printf("Enter a correct number");
break;
}
getch();
}
Output:
Enter a number between 1 to 7:5
friday
Output:
Enter a number between 1 to 7:10
Enter a correct number