Like an if-else method, switch(expression selection), case(constant expression label)and break(end processing of a particular case) use together to control the statement execution on the basis of expression selection.
expression output must be an integral value.
syntax
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
switch(expression) { case constant-expression1: /*statements of this lebel executed if expression==constant-expression1*/ statement1; statement2; . . statementn; break; case constant-expression2: /*statements of this lebel executed if expression==constant-expression2*/ statement1; statement2; . . statementn; break; default: /*statements of this lebel executed if expression does not match any label constants*/ statement1; statement2; . . statementn; } |
Points to remember:
switch
statement and to branch to the end of the switch
statement.Try below example program without break statement and see the behavior.
Try below example program with real value or float input expression and see the behavior.
Example:
Program to display weekly wake-up time[Take the week number from keyboard].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#include<stdio.h> int main() { unsigned int weekNum; printf("Display Daily WakeUp time By Week of Month"); printf("\nEnter Week Number = "); scanf("%d",&weekNum); printf("\nMy Wake-Up time for %dth week",weekNum); switch(weekNum) { printf("\nMy Wake-Up time for %dst week",weekNum);/*will not execute because out of any label*/ case 1: printf("\nMonday : 6:45AM"); printf("\nTuesday : 6:45AM"); printf("\nWednesday: 6:45AM"); printf("\nThrusday : 6:45AM"); printf("\nFriday : 6:45AM"); printf("\nSaturday : 6:45AM"); printf("\nSunday : No Alarm"); break; case 2: printf("\nMonday : 6:45AM"); printf("\nTuesday : 7:45AM"); printf("\nWednesday: 8:45AM"); printf("\nThrusday : 5:45AM"); printf("\nFriday : 6:45AM"); printf("\nSaturday : 7:45AM"); printf("\nSunday : No Alarm"); break; case 3: printf("\nMonday : 5:45AM"); printf("\nTuesday : 6:45AM"); printf("\nWednesday: 7:45AM"); printf("\nThrusday : 6:15AM"); printf("\nFriday : 6:45AM"); printf("\nSaturday : 8:45AM"); printf("\nSunday : No Alarm"); break; case 4: printf("\nMonday : 6:45AM"); printf("\nTuesday : 6:05AM"); printf("\nWednesday: 8:45AM"); printf("\nThrusday : 5:15AM"); printf("\nFriday : 6:45AM"); printf("\nSaturday : 7:45AM"); printf("\nSunday : No Alarm"); break; default: printf("\nPlease Enter Correct week"); } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 |
Output: Display Daily WakeUp time By Week of Month Enter Week Number = 3 My Wake-Up time for 3th week Monday : 5:45AM Tuesday : 6:45AM Wednesday: 7:45AM Thrusday : 6:15AM Friday : 6:45AM Saturday : 8:45AM Sunday : No Alarm |