From the free course AP Computer Science A on Lykke

4.4 Array Traversals

Key concepts: Array traversals · For loops · Writing a for-loop header · Modifying code to correct errors

An array traversal visits array elements one at a time, usually by moving an index from the first valid position to the last. A for loop is the most compact Java tool for expressing that repeated movement.

4.4 Array Traversals

An array traversal visits array elements one at a time, usually by moving an index from the first valid position to the last. A for loop is the most compact Java tool for expressing that repeated movement.

Imagine checking every seat in a theater: start at seat 0, inspect it, move to seat 1, and stop after the final seat. For an array of length $n$, the valid indices are $0$ through $n - 1$, so a correct traversal must visit exactly those positions—no fewer and no more.

The traversal pattern

The standard index-based traversal has three parts:

  1. Initialization: begin with index $0$.
  2. Continuation condition: continue while the index is less than array.length.
  3. Update: increase the index by $1$ after each iteration.

In Java, the general header is:

for (int i = 0; i < values.length; i++) {
    // use values[i]
}

The expression values.length is the number of elements, not the final index. If values.length is $4$, the valid indices are $0, 1, 2, 3$. Therefore, i < values.length is correct, while i <= values.length eventually attempts to access values[4], producing an ArrayIndexOutOfBoundsException.

Worked example: counting qualifying values

Suppose a weather station stores four daily temperatures:

int[] temperatures = {18, 23, 27, 21};
int warmDays = 0;

for (int i = 0; i < temperatures.length; i++) {
    if (temperatures[i] >= 23) {
        warmDays++;
    }
}

The loop’s index values are $0, 1, 2, 3$. The corresponding array accesses and decisions are:

Index $i$ temperatures[i] At least $23$? warmDays after iteration
$0$ $18$ No $0$
$1$ $23$ Yes $1$
$2$ $27$ Yes $2$
$3$ $21$ No $2$

After the traversal, warmDays is $2$. The loop does not know what the values mean; it simply provides systematic access. The if statement supplies the context-specific decision.

Writing the for-loop header

When constructing a traversal, ask three questions:

  • Where does the index start? Usually 0.
  • Which indices are valid? From 0 through array.length - 1.
  • How does the index move? Usually i++.

For an array named scores, the appropriate header is:

for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

An enhanced for loop can also visit every element when the algorithm needs only the element value:

for (int score : scores) {
    System.out.println(score);
}

However, an enhanced for loop does not directly provide the index. If the task must report positions, compare neighboring elements, or replace values at particular indices, use the index-based form.

Correcting traversal errors

Consider this faulty loop:

for (int i = 1; i <= values.length; i++) {
    System.out.println(values[i]);
}

It contains two errors:

  • Starting at 1 skips index 0.
  • Using <= allows i to become values.length, which is outside the array.

The corrected version is:

for (int i = 0; i < values.length; i++) {
    System.out.println(values[i]);
}

This is an application of AP Skill 4.A, “Determine the result or output of code segments,” because tracing the index values predicts which elements are accessed. It also develops AP Skill 3.B, “Develop program code,” when you write the header or modify it to implement the intended traversal.

Misconception check: “The last index is array.length.”
The length counts elements; indexing starts at $0$. The last index is always array.length - 1.

Retrieval check

An array named rainfall has length $6$. Write a for-loop header that visits every element exactly once. Then identify the error in i <= rainfall.length.

A correct header is:

for (int i = 0; i < rainfall.length; i++) {
    // process rainfall[i]
}

The faulty condition permits i == 6, but the valid indices stop at $5$; that final attempted access causes an out-of-bounds error.

4.4 Array Traversals - AP Computer Science A - image 1
4.4 Array Traversals - AP Computer Science A - image 1
4.4 Array Traversals - AP Computer Science A - diagram 1
4.4 Array Traversals - AP Computer Science A - diagram 1

Source Materials

The whole course on Lykke · Browse all public course wikis