Unit 2 Cycle 2 Day 4: I/II/III: Loop Equivalence
Share
I/II/III: Loop Equivalence
Section 2.9 — For Loops
Key Concept
A for loop and a while loop can express the same logic, and the AP exam tests your ability to recognize equivalent loop structures. The for loop for (int i = 0; i < n; i++) { body } is equivalent to int i = 0; while (i < n) { body; i++; }. However, equivalence breaks when the loop body contains continue statements (not on the AP exam) or when the update expression is complex. I/II/III questions present three loop variants and ask which produce identical output.
Consider the following while loop.
Which of the following for loops produces the same output?
Answer: (A) for (int i = 0; i < 10; i += 3) { System.out.print(i + " "); }
The while loop: i starts at 0, prints while i < 10, increments by 3. Output: 0 3 6 9. Option A has identical init (i=0), condition (i < 10), and update (i += 3).
Why Not the Others?
(B) i <= 10 would include i=9, then i=12 fails. Wait, 9+3=12 > 10. Actually B gives: 0 3 6 9 same output. But the while uses < not <=. For this specific case they match, but A is the direct translation.
(C) Starting at i=3 skips the first value (0). Output would be 3 6 9.
(D) Incrementing by 1 gives 0 1 2 3 4 5 6 7 8 9, not 0 3 6 9.
Common Mistake
Converting while to for: the initialization goes before the semicolon, the condition stays the same, and the update goes after the second semicolon. while (cond) { body; update; } becomes for (init; cond; update) { body; }.
AP Exam Tip
While-to-for conversion is a standard AP exam question. Map the three parts directly: init, condition, update. The body stays the same.