Select a Fixed Choice with switch
Match a numbered day
A schedule uses 1 for Monday and 2 for Tuesday. A switch works well when each exact integer value has its own result. Use if instead for a range, such as checking whether an age is at least 12.
#include <stdio.h>
int main(void) {
int day = 2;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Unknown day\n");
break;
}
return 0;
}
switch (day) reads day and starts at the matching case. Each case label ends with a colon. Since day is 2, the program prints Tuesday. The following break leaves the switch; execution then reaches return 0;.
Without the break after Tuesday, execution would continue into default and also print Unknown day. It does not check for another matching value once it has entered a case. This behavior is called fall-through. When no case matches initially, execution starts at default; changing day to 9 would print only Unknown day.
Run the example, then trace which lines it skips. The next exercise uses desk numbers instead of days, so you can apply the same pattern to a different set of choices.