Challenge - 5 Problems
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple while loop
What is the output of the following Java code?
Java
int i = 1; while (i <= 3) { System.out.print(i + " "); i++; }
Attempts:
2 left
💡 Hint
Remember the loop runs while the condition is true and increments i each time.
✗ Incorrect
The loop starts with i=1 and runs while i is less than or equal to 3. It prints i and then increments it. So it prints 1, 2, and 3 with spaces.
❓ Predict Output
intermediate2:00remaining
While loop with break statement
What will be printed by this Java code?
Java
int i = 0; while (i < 5) { if (i == 3) { break; } System.out.print(i + " "); i++; }
Attempts:
2 left
💡 Hint
The break stops the loop when i equals 3.
✗ Incorrect
The loop prints i starting from 0. When i reaches 3, the break stops the loop before printing 3. So output is 0 1 2
❓ Predict Output
advanced2:00remaining
While loop with continue statement
What is the output of this Java code snippet?
Java
int i = 0; while (i < 5) { i++; if (i == 3) { continue; } System.out.print(i + " "); }
Attempts:
2 left
💡 Hint
The continue skips printing when i is 3.
✗ Incorrect
The loop increments i first. When i is 3, continue skips the print statement. So it prints 1, 2, 4, 5 with spaces.
🧠 Conceptual
advanced2:00remaining
Understanding while loop condition evaluation
Consider this code:
int i = 5;
while (i > 0) {
System.out.print(i + " ");
i -= 2;
}
How many times does the loop run?
Attempts:
2 left
💡 Hint
Count how i changes each loop and when the condition fails.
✗ Incorrect
i starts at 5, then becomes 3, then 1, then -1 which stops the loop. So it runs 3 times.
❓ Predict Output
expert2:00remaining
While loop with nested conditions and variable changes
What is the output of this Java code?
Java
int i = 1; int sum = 0; while (i <= 5) { if (i % 2 == 0) { i++; continue; } sum += i; i++; } System.out.println(sum);
Attempts:
2 left
💡 Hint
Only odd numbers are added to sum because even numbers skip the addition.
✗ Incorrect
The loop adds 1, 3, and 5 to sum. Even numbers 2 and 4 are skipped. So sum = 1+3+5 = 9.