You want to write a switch statement that prints "Weekend" for cases 6 and 7, and "Weekday" for cases 1 to 5. Which code correctly does this?
hard📝 Application Q15 of 15
C - onditional Statements
You want to write a switch statement that prints "Weekend" for cases 6 and 7, and "Weekday" for cases 1 to 5. Which code correctly does this?
Aswitch(day) { case 1: printf("Weekday\n"); break; case 2: printf("Weekday\n"); break; case 3: printf("Weekend\n"); break; case 4: printf("Weekday\n"); break; case 5: printf("Weekday\n"); break; case 6: printf("Weekend\n"); break; case 7: printf("Weekend\n"); break; }
Bswitch(day) { case 1: case 2: case 3: case 4: case 5: printf("Weekday\n"); break; case 6: case 7: printf("Weekend\n"); break; default: printf("Invalid\n"); }
Cswitch(day) { case 1: case 2: case 3: case 4: case 5: printf("Weekend\n"); break; case 6: case 7: printf("Weekday\n"); break; }
Dswitch(day) { case 1: case 2: case 3: case 4: case 5: printf("Weekday\n"); case 6: case 7: printf("Weekend\n"); break; }
Step-by-Step Solution
Solution:
Step 1: Group cases for same output
Cases 1 to 5 print "Weekday", so group them before one printf and break.
Step 2: Group weekend cases
Cases 6 and 7 print "Weekend" similarly grouped with break.
Step 3: Check default case
switch(day) { case 1: case 2: case 3: case 4: case 5: printf("Weekday\n"); break; case 6: case 7: printf("Weekend\n"); break; default: printf("Invalid\n"); } includes default for invalid days, which is good practice.
Final Answer:
Groups weekday cases 1-5 and weekend cases 6-7 with breaks and default -> Option B
Quick Check:
Group cases with same output, add break after each group [OK]
Quick Trick:Group cases with same output, add break after group [OK]
Common Mistakes:
Printing wrong labels for grouped cases
Missing breaks causing fall-through
Not handling default case
Master "onditional Statements" in C
9 interactive learning modes - each teaches the same concept differently