1Z0-819 · Question #174
Given the code fragment: ``java int x = 0; while(x < 10) { System.out.print(x++); } `` Which "for" loop produces the same output?
The correct answer is C. for (int d = 0; d < 10; ) { System.out.print(d); ++d; }. Option C is the correct answer because it faithfully replicates the while loop's behavior: d initializes to 0, the loop condition checks d < 10, the body prints d first (before incrementing), and ++d advances the counter - exactly mirroring System.out.print(x++) which prints…
Question
int x = 0;
while(x < 10) {
System.out.print(x++);
}
Which "for" loop produces the same output?Options
- Afor (int a = 0; a < 10; a++) { System.out.print(++a); }
- Bfor (a; a < 10; a++) { System.out.print(a); }
- Cfor (int d = 0; d < 10; ) { System.out.print(d); ++d; }
- Dfor (int c = 0; c < 10; c++) { System.out.print(c); if (c == 10) { break; } }
How the community answered
(61 responses)- A7% (4)
- B11% (7)
- C80% (49)
- D2% (1)
Explanation
Option C is the correct answer because it faithfully replicates the while loop's behavior: d initializes to 0, the loop condition checks d < 10, the body prints d first (before incrementing), and ++d advances the counter - exactly mirroring System.out.print(x++) which prints then increments.
Option A is wrong because it uses ++a (pre-increment) inside the body and a++ in the update clause, so a is incremented twice per iteration, printing only odd numbers: 1, 3, 5, 7, 9.
Option B is a compile error - a is used in the initializer without being declared; a for initializer requires either a declaration (int a = 0) or an assignment to a pre-existing variable.
Option D is a distractor: the if (c == 10) break is dead code that never executes, because the loop condition c < 10 guarantees c is always 0–9 inside the body. While D accidentally produces the same output, it introduces logic not present in the original loop and is therefore not a true equivalent.
Memory tip: When converting a while loop to a for loop, move the init before the for, put the condition in the for's second slot, and leave the update inside the body or in the third slot - but never double-up increments in both places (that's the A trap).
Topics
Community Discussion
No community discussion yet for this question.