Unit 2 Cycle 2 Day 3: Error: Off-By-One in Loops
Share
Error: Off-By-One in Loops
Section 2.13 — Informal Code Analysis
Key Concept
Off-by-one errors are the most common loop mistakes and occur when a loop iterates one too many or one too few times. They typically result from using < instead of <= (or vice versa), starting at 0 instead of 1, or miscalculating the ending condition. For string processing, i < str.length() is correct for accessing charAt(i), but i <= str.length() would cause an IndexOutOfBoundsException on the last iteration. The AP exam frequently presents two similar code segments that differ by one in a boundary.
A method is intended to count the number of even numbers from 2 to n, inclusive.
The call countEvens(10) returns 4 instead of the expected 5. What is the error?
Answer: (B) The condition should be i <= n
Even numbers 2-10: 2, 4, 6, 8, 10 (5 numbers). The loop uses i < n, so when n=10, the loop runs for i=2,4,6,8 (stops before 10). Changing to i <= n includes i=10, giving count=5.
Why Not the Others?
(A) Starting at 0 would count 0 as even, which is not in the range 2 to n.
(C) Incrementing by 1 would visit every number, not just evens, requiring an additional if-check.
(D) Starting count at 1 would overcount by 1 for all inputs.
Common Mistake
The off-by-one error is the most common loop bug. i < n excludes the value n itself. When the range should be inclusive of n, use i <= n.
AP Exam Tip
When a loop is supposed to include a boundary value, check whether < should be <=. Test with the boundary value itself to verify.