Unit 4 Cycle 1 Day 4: For Loop Array Traversal
Share
For Loop Array Traversal
Section 4.2 — Traversing Arrays
Key Concept
A standard for loop traverses an array using an index variable: for (int i = 0; i < arr.length; i++). This pattern provides full control over the index, allowing you to skip elements, traverse backward, or access adjacent elements. The index i is both the position indicator and the access key via arr[i]. On the AP exam, for loop traversal is used for algorithms that need to know the position of each element or need to modify array elements in place.
Consider the following code segment.
What is printed?
Answer: (A) 30
sum = 2+4+6+8+10 = 30. The loop visits every element from index 0 to 4.
Why Not the Others?
(B) 20 would miss some elements. All 5 are summed.
(C) 10 is just the last element.
(D) The accumulator starts at 0 but accumulates all values.
Common Mistake
The standard for loop traversal uses i = 0; i < arr.length; i++. Using <= instead of < would cause an out-of-bounds error.
AP Exam Tip
Use < (not <=) with arr.length. This is the most common array traversal pattern and the most common off-by-one error source.