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 for-loop with multiple updates
What is the output of the following Java code?
Java
public class Main { public static void main(String[] args) { int sum = 0; for (int i = 1, j = 10; i < j; i += 2, j -= 3) { sum += i + j; } System.out.println(sum); } }
Attempts:
2 left
💡 Hint
Trace the values of i and j in each loop iteration and add their sum.
✗ Incorrect
The for-loop initializes i=1, j=10. Condition: i < j. Updates: i += 2, j -= 3.
- Iteration 1: i=1 < j=10 true, sum += 11 → sum=11, update i=3, j=7
- Iteration 2: i=3 < j=7 true, sum += 10 → sum=21, update i=5, j=4
- Next: i=5 < j=4 false, end.
Output: 21.
❓ Predict Output
intermediate2:00remaining
Output of a while-loop with complex condition
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { int i = 0; int count = 0; while (i < 10) { i += 3; if (i % 2 == 0) { count++; } } System.out.println(count); } }
Attempts:
2 left
💡 Hint
Check the values of i after each increment and count how many are even.
✗ Incorrect
The while loop checks i < 10 before the body:
- i=0 <10: i+=3 → i=3 (odd)
- i=3 <10: i=6 (even, count=1)
- i=6 <10: i=9 (odd)
- i=9 <10: i=12 (even, count=2)
- i=12 <10 false.
Output: 2.
🔧 Debug
advanced2:00remaining
Identify the error in loop initialization
What error will this Java code produce when compiled?
Java
public class Main { public static void main(String[] args) { for (int i = 0; i < 5; i++) int j = i * 2; System.out.println(j); } }
Attempts:
2 left
💡 Hint
Check the scope of variable j declared inside the loop.
✗ Incorrect
Variable j is declared inside the for-loop body and is not accessible outside it. The System.out.println(j) tries to access j outside its scope, causing a compilation error: cannot find symbol j.
❓ Predict Output
advanced2:00remaining
Output of nested for-loops with update expressions
What is the output of this Java program?
Java
public class Main { public static void main(String[] args) { int count = 0; for (int i = 1; i <= 3; i++) { for (int j = i; j <= 3; j += 2) { count++; } } System.out.println(count); } }
Attempts:
2 left
💡 Hint
Count how many times the inner loop runs for each i.
✗ Incorrect
Trace inner loop:
- i=1: j=1 (count=1), j=3 (count=2)
- i=2: j=2 (count=3)
- i=3: j=3 (count=4)
Total: 4.
🧠 Conceptual
expert2:00remaining
Effect of loop update expression on iteration count
Consider the loop:
How many times will the loop body execute?
for (int i = 0; i < 20; i += 4) { /* body */ }How many times will the loop body execute?
Attempts:
2 left
💡 Hint
Count how many increments of 4 fit before i reaches 20.
✗ Incorrect
i starts at 0 and increases by 4 each time: 0,4,8,12,16. Next would be 20 which is not less than 20, so loop stops. The loop runs 5 times.