Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

5.2: Array Traversal

Use indexed traversal when positions matter or elements must be replaced. An enhanced for loop provides each element value, not an assignable array slot.

College Board Unit 4

How it works

Standard traversal runs an index from 0 while it is less than length, visiting every element once. The enhanced for loop gives read-only access to each element without an index and is the cleaner choice when position does not matter. Choosing between them is a real decision: you need the indexed form whenever you must write to the array, compare neighbors, or know where a value sits.

Choose the indexed form whenever the array must be modified.

Common error

Assigning to the enhanced for variable and expecting the array to change. It does not.

Worked example

Java

int[] values = {2, 5, 1};
int sum = 0;
for (int value : values) sum += value;
System.out.println(sum);

Output

8

Each array value contributes once to the sum.

Exercises

5.2.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int[] values = {2, 5, 1};
for (int value : values) value *= 2;
System.out.println(Arrays.toString(values));
Show solution

Output

[2, 5, 1]

Assigning the local enhanced-for variable does not replace primitive array elements.

5.2.2 · Write code

Write public static int countAbove(int[] values, int cutoff). Return the number strictly greater than cutoff. Empty arrays must return 0.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static int countAbove(int[] values, int cutoff) {
    int count = 0;
    for (int value : values) if (value > cutoff) count++;
    return count;
}

Check your code

Java

System.out.println(countAbove(new int[]{4, 7, 7, 2}, 4));
System.out.println(countAbove(new int[]{}, 4));

Expected output

2
0
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic