Challenge - 5 Problems
Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a loop printing numbers
What is the output of this Java code that uses a loop to print numbers from 1 to 3?
Java
for (int i = 1; i <= 3; i++) { System.out.print(i + " "); }
Attempts:
2 left
💡 Hint
Look at the loop start and end conditions carefully.
✗ Incorrect
The loop starts at 1 and runs while i is less than or equal to 3, printing each number followed by a space.
🧠 Conceptual
intermediate1:30remaining
Why use loops instead of repeating code?
Why do programmers use loops instead of writing the same code multiple times?
Attempts:
2 left
💡 Hint
Think about what happens if you want to change repeated code.
✗ Incorrect
Loops help avoid repeating the same lines many times, so if you need to change something, you only change it once inside the loop.
❓ Predict Output
advanced2:00remaining
Output of nested loops
What is the output of this nested loop code?
Java
for (int i = 1; i <= 2; i++) { for (int j = 1; j <= 2; j++) { System.out.print(i * j + " "); } }
Attempts:
2 left
💡 Hint
Multiply i and j for each pair in the loops.
✗ Incorrect
The outer loop runs i=1 and i=2. For each i, inner loop runs j=1 and j=2. Multiplying gives 1*1=1, 1*2=2, 2*1=2, 2*2=4.
🔧 Debug
advanced2:00remaining
Identify the error in this loop
What error does this code cause?
Java
for (int i = 0; i < 5; i++) { System.out.println(i); i++; }
Attempts:
2 left
💡 Hint
Check where variable i is used and declared.
✗ Incorrect
The code increments i twice per loop iteration, but this is allowed and i is in scope. The code prints 0, 2, 4.
🚀 Application
expert2:00remaining
How many times does this loop run?
How many times will the loop body execute in this code?
Java
int count = 0; for (int i = 10; i > 0; i -= 3) { count++; } System.out.println(count);
Attempts:
2 left
💡 Hint
Count how many times i stays greater than 0 when subtracting 3 each time.
✗ Incorrect
i starts at 10, then 7, then 4, then 1, then -2 (loop stops). So loop runs 4 times.