Java do-while with pre-increment in condition — compute final values of i and j.\n\ni = 1; j = 10;\ndo {\n if (i > j) {\n break;\n }\n j--;\n} while (++i < 5);\nSystem.out.println("i = " + i + " and j = " + j);\n\nWhat is printed?

Difficulty: Medium

Correct Answer: i = 5 and j = 6

Explanation:


Introduction / Context:
This trace problem tests order of evaluation in do-while loops, the effect of a pre-increment (++i) in the loop condition, and control-flow with break. You must track i and j across iterations.



Given Data / Assumptions:

  • Initial values: i = 1, j = 10.
  • Loop body decrements j after an early break check.
  • The while condition uses ++i, so i is incremented before the comparison with 5.


Concept / Approach:
A do-while executes the body at least once. After each body, j is decremented, then i is pre-incremented for the condition check. The break guard if(i > j) is evaluated at the top of each iteration before decrementing j. Carefully update the variables step by step.



Step-by-Step Solution:

Start: i=1, j=10 → i > j? false → j becomes 9 → condition (++i<5): i=2, 2<5 true.Iter 2: i=2, j=9 → i > j? false → j=8 → condition (++i<5): i=3, 3<5 true.Iter 3: i=3, j=8 → i > j? false → j=7 → condition (++i<5): i=4, 4<5 true.Iter 4: i=4, j=7 → i > j? false → j=6 → condition (++i<5): i=5, 5<5 false → loop exits.Final: i=5, j=6; print "i = 5 and j = 6".


Verification / Alternative check:
Note that the if(i > j) never triggers; j remains larger until exit. A quick table confirms the sequence.



Why Other Options Are Wrong:

  • Options with i=6 assume post-increment; the code uses pre-increment in the condition.
  • Other j values are inconsistent with the four decrements.


Common Pitfalls:
Forgetting that do-while checks condition after the body and that ++i changes i before comparison.



Final Answer:
i = 5 and j = 6

More Questions from Flow Control

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion