Challenge - 5 Problems
Loop Control Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Java loop with break?
Consider the following Java code snippet. What will it print?
Java
public class Test { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 3) { break; } System.out.print(i + " "); } } }
Attempts:
2 left
💡 Hint
The break statement stops the loop when i equals 3.
✗ Incorrect
The loop prints numbers starting from 0. When i reaches 3, the break stops the loop immediately, so 3 and 4 are not printed.
❓ Predict Output
intermediate2:00remaining
What does this Java loop with continue print?
Look at this Java code. What will be printed?
Java
public class Test { public static void main(String[] args) { for (int i = 0; i < 5; i++) { if (i == 2) { continue; } System.out.print(i + " "); } } }
Attempts:
2 left
💡 Hint
The continue statement skips the current loop iteration when i is 2.
✗ Incorrect
When i is 2, continue skips the print statement for that iteration, so 2 is not printed.
🧠 Conceptual
advanced2:00remaining
Why is loop control important in programming?
Which of the following best explains why loop control statements like break and continue are required?
Attempts:
2 left
💡 Hint
Think about what happens if a loop never stops or processes unnecessary steps.
✗ Incorrect
Loop control statements let us stop loops early or skip certain steps, which helps prevent infinite loops and improves efficiency.
❓ Predict Output
advanced2:00remaining
What is the output of nested loops with break?
What will this Java program print?
Java
public class Test { 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
The inner loop breaks when j equals 2, so only j=1 prints each time.
✗ Incorrect
For each i, the inner loop prints only when j=1. When j=2, break stops the inner loop, so output is '1-1 2-1 3-1 '.
❓ Predict Output
expert2:00remaining
What error does this Java loop cause?
What error will this Java code produce when run?
Java
public class Test { public static void main(String[] args) { int i = 0; while (i < 5) { System.out.print(i + " "); } } }
Attempts:
2 left
💡 Hint
Check if the loop variable changes inside the loop.
✗ Incorrect
Variable i never changes, so condition i < 5 is always true, causing an infinite loop printing 0 repeatedly.