Challenge - 5 Problems
Switch vs If Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of switch with fall-through
What is the output of this C code snippet?
C
#include <stdio.h> int main() { int x = 2; switch (x) { case 1: printf("One\n"); case 2: printf("Two\n"); case 3: printf("Three\n"); break; default: printf("Default\n"); } return 0; }
Attempts:
2 left
💡 Hint
Remember that switch cases fall through unless you use break.
✗ Incorrect
The switch starts at case 2, prints "Two", then falls through to case 3 and prints "Three", then breaks. Case 1 is skipped.
❓ Predict Output
intermediate2:00remaining
If-else equivalent output
What is the output of this if-else code?
C
#include <stdio.h> int main() { int x = 3; if (x == 1) { printf("One\n"); } else if (x == 2) { printf("Two\n"); } else if (x == 3) { printf("Three\n"); } else { printf("Default\n"); } return 0; }
Attempts:
2 left
💡 Hint
Check which condition matches the value of x.
✗ Incorrect
Since x is 3, the third else-if condition is true, so it prints "Three".
❓ Predict Output
advanced2:00remaining
Switch with non-constant case labels
What error does this code produce?
C
#include <stdio.h> int main() { int a = 1; int b = 2; switch (a) { case b: printf("B\n"); break; default: printf("Default\n"); } return 0; }
Attempts:
2 left
💡 Hint
Case labels must be constant expressions in C.
✗ Incorrect
In C, case labels must be compile-time constants. Using variable 'b' causes a compilation error.
🧠 Conceptual
advanced2:00remaining
Difference in evaluation between switch and if
Which statement about switch and if is true in C?
Attempts:
2 left
💡 Hint
Think about how switch jumps directly to a case.
✗ Incorrect
Switch evaluates the expression once and jumps directly to the matching case label. If-else evaluates conditions one by one until one is true.
❓ Predict Output
expert2:00remaining
Output of nested switch and if
What is the output of this code?
C
#include <stdio.h> int main() { int x = 1, y = 2; switch (x) { case 1: if (y == 2) { printf("A\n"); break; } printf("B\n"); break; case 2: printf("C\n"); break; default: printf("D\n"); } return 0; }
Attempts:
2 left
💡 Hint
Check the if condition inside case 1 and where the breaks are.
✗ Incorrect
Inside case 1, y == 2 is true, so it prints "A" and breaks out of the switch. "B" is not printed.