In Java, consider the following loop. Predict the exact printed value of i after the loop terminates. int i = 0; while (1) // treated as constant true in many MCQ contexts; assume an endless loop with break { if (i == 4) { break; } ++i; } System.out.println("i = " + i);
-
Ai = 0
-
Bi = 3
-
Ci = 4
-
DCompilation fails.
-
Ei = 5
Answer
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:
istarts at 0.- The loop repeats until explicitly broken.
- A
breakoccurs wheni == 4. ++iincrementsiat 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