In Java, consider the following loop. Predict the exact printed value of i after the loop terminates.\n\nint i = 0;\nwhile (1) // treated as constant true in many MCQ contexts; assume an endless loop with break\n{\n if (i == 4)\n {\n break;\n }\n ++i;\n}\nSystem.out.println("i = " + i);

Difficulty: Easy

Correct Answer: i = 4

Explanation:


Introduction / Context:
This question tests control flow in Java loops, specifically how a break exits a loop and how pre-increment affects the loop variable before the break condition is checked in the next iteration.


Given Data / Assumptions:

  • i starts at 0.
  • The loop repeats until explicitly broken.
  • A break occurs when i == 4.
  • ++i increments i at the end of each non-breaking iteration.


Concept / Approach:
Track i as the loop iterates: the condition is checked at the top, then either the loop breaks (when i == 4) or increments i and continues. Understanding the order prevents off-by-one errors.


Step-by-Step Solution:
Start: i = 0.Iter 1: check i==4? no. Execute ++i ⇒ i = 1.Iter 2: check 1==4? no. ++i ⇒ i = 2.Iter 3: check 2==4? no. ++i ⇒ i = 3.Iter 4: check 3==4? no. ++i ⇒ i = 4.Iter 5: check 4==4? yes ⇒ break.Print: i = 4.


Verification / Alternative check:
Add a debug print at the loop top to observe the sequence 0,1,2,3,4 and confirm that the loop stops when i reaches 4.


Why Other Options Are Wrong:
i = 0 or i = 3 underestimate the final value; Compilation fails is inapplicable here; i = 5 assumes an extra increment after the break.


Common Pitfalls:
Confusing post-increment with pre-increment, or thinking the increment runs on the breaking iteration. The break prevents further increments.


Final Answer:
i = 4

More Questions from Flow Control

Discussion & Comments

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