Unit 2 Cycle 2 Day 16: For Loop with Multiple Updates
Share
For Loop with Multiple Updates
Section 2.9 — For Loops
Key Concept
A for loop can have multiple update expressions separated by commas (though this is uncommon on the AP exam) or can increment by values other than 1. Loops like for (int i = 0; i < n; i += 2) skip every other value. The AP exam may also show loops where the loop variable is modified inside the body in addition to the update expression, creating unexpected behavior. When the body modifies the loop variable, the update still applies after the body, potentially causing the variable to jump or skip values.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 5 5
left and right converge: (0,10)→(1,9)→(2,8)→(3,7)→(4,6)→(5,5). When left=5, right=5: 5 < 5 is false, loop ends. Prints 5 5.
Why Not the Others?
(B) The loop stops when left equals right (both 5), not when left exceeds right.
(C) left starts lower and increases; right starts higher and decreases. They meet at 5.
(D) Both variables change by 1 each iteration. Starting 10 apart, they meet after 5 iterations at (5,5).
Common Mistake
Two-pointer convergence: when one variable increases and another decreases by the same amount, they meet at the midpoint. For 0 and 10, the midpoint is 5.
AP Exam Tip
Two converging pointers is a common algorithm pattern. They always meet at (start + end) / 2 when moving at the same speed.