Unit 2 Cycle 1 Day 22: Identifying Loop Errors
Share
Identifying Loop Errors
Section 2.13 — Informal Code Analysis
Key Concept
Informal code analysis involves identifying errors without running the code. Common loop errors include: off-by-one (iterating one too many or too few times), using < versus <= in the condition, starting at 0 versus 1, forgetting to update the loop variable, and placing statements inside or outside the loop body incorrectly. The AP exam asks you to identify what is wrong with a given code segment, or to determine the effect of a specific error on the output.
A method is intended to return the sum of all elements in an array. Consider the following implementation.
What happens when sum(new int[]{1, 2, 3}) is called?
Answer: (C) Throws ArrayIndexOutOfBoundsException
The loop uses i <= arr.length instead of i < arr.length. For an array of length 3, valid indices are 0, 1, 2. When i reaches 3, arr[3] is out of bounds, throwing an exception.
Why Not the Others?
(A) The exception occurs before the method can return. The loop would sum correctly for i=0,1,2 but crashes at i=3.
(B) total starts at 0 but gets updated before the crash.
(D) The code compiles fine. The error is a runtime out-of-bounds exception.
Common Mistake
The classic off-by-one error: i <= arr.length should be i < arr.length. Array indices go from 0 to length-1. Using <= with length accesses one index past the end.
AP Exam Tip
For array traversal, the standard pattern is for (int i = 0; i < arr.length; i++). Using <= instead of < is the most common off-by-one error on the AP exam.