Challenge - 5 Problems
Nested Loops Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested loops with break
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) { if (j == 2) break; std::cout << i << j << " "; } } return 0; }
Attempts:
2 left
💡 Hint
Look at where the break statement stops the inner loop.
✗ Incorrect
The inner loop breaks when j == 2, so only j == 1 prints for each i. So output is 11 21 31.
❓ Predict Output
intermediate2:00remaining
Counting iterations in nested loops
How many times will the inner statement execute in this code?
C++
#include <iostream> int main() { int count = 0; for (int i = 0; i < 4; ++i) { for (int j = i; j < 4; ++j) { ++count; } } std::cout << count; return 0; }
Attempts:
2 left
💡 Hint
Count how many times j runs for each i.
✗ Incorrect
For i=0, j=0..3 (4 times); i=1, j=1..3 (3 times); i=2, j=2..3 (2 times); i=3, j=3..3 (1 time). Total 4+3+2+1=10.
🔧 Debug
advanced2:00remaining
Identify the error in nested loops
What error will this code produce when compiled?
C++
#include <iostream> int main() { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) std::cout << i << j << std::endl; std::cout << "Done" << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check how indentation affects loops in C++.
✗ Incorrect
The code runs fine. The inner loop prints pairs, then the last cout prints 'Done'. No braces needed for single statements.
❓ Predict Output
advanced2:00remaining
Output of nested loops with continue
What is the output of this code?
C++
#include <iostream> int main() { for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) { if (i == j) continue; std::cout << i << j << " "; } } return 0; }
Attempts:
2 left
💡 Hint
The continue skips printing when i equals j.
✗ Incorrect
Pairs where i == j (11, 22, 33) are skipped. All others print in order.
🧠 Conceptual
expert3:00remaining
Number of iterations in nested loops with variable limits
Consider this nested loop code. How many times does the innermost statement execute?
C++
#include <iostream> int main() { int count = 0; for (int i = 1; i <= 5; ++i) { for (int j = 1; j <= i; ++j) { for (int k = 1; k <= j; ++k) { ++count; } } } std::cout << count; return 0; }
Attempts:
2 left
💡 Hint
Sum the counts: for each i, sum j=1 to i, then sum k=1 to j.
✗ Incorrect
The innermost loop runs sum_{i=1}^5 sum_{j=1}^i j = sum_{i=1}^5 (i(i+1)/2) = 35.