Challenge - 5 Problems
Loop Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple for loop
What is the output of this C++ code snippet?
C++
#include <iostream> int main() { for (int i = 1; i <= 3; i++) { std::cout << i << " "; } return 0; }
Attempts:
2 left
💡 Hint
The loop starts at 1 and runs while i is less than or equal to 3.
✗ Incorrect
The loop variable i starts at 1 and increments by 1 each time until it reaches 3, printing each value followed by a space.
🧠 Conceptual
intermediate1:30remaining
Why use loops instead of repeated code?
Why are loops useful in programming compared to writing the same code multiple times?
Attempts:
2 left
💡 Hint
Think about how many times you want to do the same task.
✗ Incorrect
Loops let you write a task once and repeat it many times, which saves time and reduces mistakes.
❓ Predict Output
advanced2:30remaining
Output of nested loops
What is the output of this nested loop code?
C++
#include <iostream> int main() { for (int i = 1; i <= 2; i++) { for (int j = 1; j <= 2; j++) { std::cout << i << j << " "; } } return 0; }
Attempts:
2 left
💡 Hint
The outer loop controls the first digit, the inner loop controls the second digit.
✗ Incorrect
The outer loop runs i=1 then i=2. For each i, the inner loop runs j=1 and j=2, printing i and j together.
🔧 Debug
advanced2:00remaining
Identify the error in this loop
What error will this code produce when compiled or run?
C++
#include <iostream> int main() { for (int i = 0; i < 5; i++) std::cout << i << std::endl; std::cout << j; return 0; }
Attempts:
2 left
💡 Hint
Check if all variables used are declared.
✗ Incorrect
Variable 'j' is used but never declared, causing a compilation error.
🚀 Application
expert2:30remaining
Count how many times a loop runs
How many times will the loop body execute in this code?
C++
#include <iostream> int main() { int count = 0; for (int i = 10; i > 0; i -= 3) { count++; } std::cout << count; return 0; }
Attempts:
2 left
💡 Hint
Start from 10 and subtract 3 each time until i is no longer greater than 0.
✗ Incorrect
The loop runs while i is 10, 7, 4, 1 (4 times). When i becomes -2, loop stops.