Unit 4 Cycle 1 Day 4: For Loop Array Traversal

Unit 4 Foundation (Cycle 1) Day 4 of 28 Foundation

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.

int[] arr = {2, 4, 6, 8, 10}; int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } System.out.println(sum);

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.

Review this topic: Section 4.2 — Traversing Arrays • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.