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 nested loops with break
What is the output of the following Java code snippet?
Java
public class Main { public static void main(String[] args) { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (j == 2) { break; } System.out.print(i + "-" + j + " "); } } } }
Attempts:
2 left
💡 Hint
Remember that break exits the innermost loop immediately.
✗ Incorrect
The inner loop breaks when j == 2, so only j=1 prints for each i. Thus output is "1-1 2-1 3-1 ".
❓ Predict Output
intermediate2:00remaining
Output of while loop with continue
What will be printed by this Java code?
Java
public class Main { public static void main(String[] args) { int i = 0; while (i < 5) { i++; if (i == 3) { continue; } System.out.print(i + " "); } } }
Attempts:
2 left
💡 Hint
The continue skips the print when i equals 3.
✗ Incorrect
When i is 3, continue skips the print statement, so 3 is not printed. All other values from 1 to 5 print.
🔧 Debug
advanced2:00remaining
Identify the error in for loop increment
What error will this Java code produce when run?
Java
public class Main { public static void main(String[] args) { for (int i = 0; i < 5; i = i++) { System.out.print(i + " "); } } }
Attempts:
2 left
💡 Hint
Look carefully at the increment expression i = i++.
✗ Incorrect
The expression i = i++ does not change i because i++ returns the original value before increment. So i stays 0, causing an infinite loop.
❓ Predict Output
advanced2:00remaining
Output of for loop with multiple variables
What is the output of this Java code?
Java
public class Main { public static void main(String[] args) { for (int i = 0, j = 5; i < j; i++, j--) { System.out.print(i + "-" + j + " "); } } }
Attempts:
2 left
💡 Hint
The loop stops when i is no longer less than j.
✗ Incorrect
The loop runs while i < j. Iterations: (0,5), (1,4), (2,3). When i=3 and j=2, condition fails, loop stops.
🧠 Conceptual
expert2:00remaining
Number of iterations in nested loops with dependent conditions
Consider the following Java code. How many times will the innermost print statement execute?
Java
public class Main { public static void main(String[] args) { int count = 0; for (int i = 1; i <= 4; i++) { for (int j = i; j <= 4; j++) { count++; } } System.out.println(count); } }
Attempts:
2 left
💡 Hint
Count how many times j runs for each i.
✗ Incorrect
For i=1, j=1..4 (4 times); i=2, j=2..4 (3 times); i=3, j=3..4 (2 times); i=4, j=4..4 (1 time). Total 4+3+2+1=10.