Challenge - 5 Problems
Switch vs If Mastery
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 <iostream> int main() { int x = 2; switch (x) { case 1: std::cout << "One "; case 2: std::cout << "Two "; case 3: std::cout << "Three "; break; default: std::cout << "Default "; } 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 ". It stops at break.
❓ Predict Output
intermediate2:00remaining
If-else chain output
What is the output of this C++ code using if-else?
C++
#include <iostream> int main() { int x = 2; if (x == 1) { std::cout << "One "; } else if (x == 2) { std::cout << "Two "; } else if (x == 3) { std::cout << "Three "; } else { std::cout << "Default "; } return 0; }
Attempts:
2 left
💡 Hint
If-else stops checking after the first true condition.
✗ Incorrect
The condition x == 2 is true, so it prints "Two " and skips the rest.
🧠 Conceptual
advanced2:00remaining
Switch statement limitations
Which of the following is NOT a limitation of the C++ switch statement compared to if-else?
Attempts:
2 left
💡 Hint
Think about how switch chooses which case to run.
✗ Incorrect
Switch executes only the matching case and any following cases if no break is used. It does NOT always execute all cases.
❓ Predict Output
advanced2:00remaining
Output difference between switch and if
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { int x = 5; switch (x) { case 1: std::cout << "One "; break; case 2: std::cout << "Two "; break; default: std::cout << "Default switch "; } if (x == 1) { std::cout << "One if "; } else if (x == 2) { std::cout << "Two if "; } else { std::cout << "Default if "; } return 0; }
Attempts:
2 left
💡 Hint
Both switch and if-else handle default cases here.
✗ Incorrect
The switch hits default and prints "Default switch ". The if-else hits else and prints "Default if ". Both outputs appear.
🧠 Conceptual
expert2:00remaining
When to prefer switch over if-else
Which scenario best justifies using a switch statement instead of if-else in C++?
Attempts:
2 left
💡 Hint
Switch works best with one variable and fixed values.
✗ Incorrect
Switch is ideal for one variable with many constant integral values. It is not suitable for complex conditions, ranges, or strings.