Topic 4.2 — Traversing Arrays
Goal: use loops (especially for) to visit each element in an array, compute results,
and apply common traversal patterns safely.
The big idea
Traversing an array means visiting elements one by one (often left to right) using an index.
On AP CSA, you’ll see a lot of “find the sum / count / max / average” style traversals. Most of them are just different versions of the same loop pattern.
Canonical traversal loop (memorize)
for (int i = 0; i < arr.length; i++) {
// use arr[i]
}
- Start at
0(first index) - Stop at
i < arr.length(last index isarr.length - 1)
Pattern 1: Sum (accumulator)
An accumulator variable stores a running total as you traverse.
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
Pattern 2: Count something
Count elements that match a condition.
int countEven = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] % 2 == 0) {
countEven++;
}
}
Pattern 3: Find max/min
Usually initialize with the first element, then compare.
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
Pattern 4: Compute average
Average = sum ÷ count. Watch out for integer division.
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
double avg = (double) sum / nums.length;
Classic bug: off-by-one
This tries to access arr[arr.length] (invalid).
for (int i = 0; i <= arr.length; i++) { // ❌
System.out.println(arr[i]);
}
Fix: use i < arr.length.
Traversing while updating elements
You can modify an array during traversal by assigning to arr[i].
// Add 5 to every element
for (int i = 0; i < nums.length; i++) {
nums[i] += 5;
}
This is a very common AP-style loop: “update each element based on a rule.”
Forward vs backward traversal
Sometimes you traverse from the end (especially when removing/shifting in other units).
for (int i = arr.length - 1; i >= 0; i--) {
// use arr[i]
}
When you need the index
- When updating:
arr[i] = ... - When comparing neighbors:
arr[i]vsarr[i+1] - When tracking the location of something (like the index of max)
int maxIndex = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] > nums[maxIndex]) {
maxIndex = i;
}
}
Quick self-check
- Write a loop that prints every element in
arr. - What’s wrong with
i <= arr.length? - Write a loop that counts how many values are negative.
- How do you compute an average without integer division problems?
- How would you find the index of the smallest value?