---
title: "AP CSA 4.4: Traversing Arrays"
description: "Review AP Computer Science A 4.4, including array traversal, indexed for loops, while loops, enhanced for loops, array indices, modifying array elements, object references in arrays, and rewriting enhanced for loops."
canonical: "https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t"
type: "study-guide"
subject: "AP Computer Science A"
unit: "Unit 4 – Data Collections"
lastUpdated: "2026-06-09"
---

# AP CSA 4.4: Traversing Arrays

## Summary

Review AP Computer Science A 4.4, including array traversal, indexed for loops, while loops, enhanced for loops, array indices, modifying array elements, object references in arrays, and rewriting enhanced for loops.

## Guide

Traversing a [1D array](/ap-comp-sci-a/key-terms/1d-array "fv-autolink") means using a loop to visit its elements in order so you can read, calculate, search, or update values. The main tools are an indexed `for` loop, a `while` loop with an index, and an enhanced `for` loop. For [AP Computer Science A](/ap-comp-sci-a "fv-autolink"), choose an indexed loop when you need positions or updates and an enhanced loop when you only need to read values.

## Why This Matters for the AP Computer Science A Exam

Array traversal is one of the most heavily used skills in AP Computer Science A. [Unit 4](/ap-comp-sci-a/unit-4 "fv-autolink") carries a large share of the exam, and [traversal](/ap-comp-sci-a/key-terms/traversal "fv-autolink") shows up constantly in both multiple-choice and free-response code writing.

On multiple-choice questions you will often trace traversal code to predict output, decide which loop visits the right elements, or explain why a segment will not [compile](/ap-comp-sci-a/key-terms/compile "fv-autolink") or runs incorrectly. When an array is not given to you, you can make a small sample array and trace the loop on it. In free-response code writing, you frequently [traverse](/ap-comp-sci-a/key-terms/traverse "fv-autolink") arrays to compute results, search for values, or update elements, so a reliable loop pattern saves time and prevents bugs.

## Key Takeaways

- Traversing an array uses a [repetition](/ap-comp-sci-a/unit-2/algorithms-with-selection-and-repetition/study-guide/42crNSZyW8IRsntk9IHe "fv-autolink") statement to access all elements or an ordered sequence of them.
- An indexed `for` loop or `while` loop accesses elements by index, so you can read or change `array[i]` directly.
- An enhanced `for` loop gives you a copy of each element through the loop [variable](/ap-comp-sci-a/unit-1/expressions-and-assignment-statements/study-guide/01dr6uUPDAn3SjtK2Psr "fv-autolink"), without using an index.
- Reassigning the enhanced `for` loop variable does not change the array; assigning through an index like `array[i] = value` does.
- When an array stores [object references](/ap-comp-sci-a/key-terms/object-reference "fv-autolink"), you can call [methods](/ap-comp-sci-a/unit-3/abstraction-and-program-design/study-guide/o9VgVeIpKRYZ7N7rXfUz "fv-autolink") on the enhanced `for` loop variable to change that object's attributes, but the stored references stay the same.
- Any enhanced `for` loop over an array can be rewritten as an indexed `for` loop or a `while` loop.

## The Three Ways to Traverse a 1D Array

### Indexed for loop

The indexed `for` loop is the most flexible traversal. You control the starting index, the stopping condition, and how the index changes each pass. Because you have the index, you can read and modify elements directly with `array[i]`.

```java
int[] scores = {85, 92, 78, 96, 88};

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

The standard pattern starts `i` at 0, continues while `i < array.length`, and increases `i` by 1. Valid indices run from 0 to `array.length - 1`, so using `<` instead of `<=` keeps you in [bounds](/ap-comp-sci-a/key-terms/bounds "fv-autolink").

You need an index when you want to:

- modify elements with `array[i] = value`
- compare elements at different positions, like `array[i]` and `array[i + 1]`
- traverse in [reverse](/ap-comp-sci-a/unit-4/developing-algorithms-using-arraylists/study-guide/MKbteieYvLOpWIwfqiND "fv-autolink") using `i--`
- work with two arrays at the same position

### while loop with an index

A `while` loop traverses by index too. You just manage the index yourself: declare it before the loop, check it in the condition, and update it inside the loop.

```java
int[] scores = {85, 92, 78, 96, 88};

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

Forgetting to update the index inside a `while` loop creates an [infinite loop](/ap-comp-sci-a/key-terms/infinite-loop "fv-autolink"), which is a common trap. Anything you can write with an indexed `for` loop you can also write with a `while` loop.

### Enhanced for loop (for-each)

The enhanced `for` loop visits each element in order without using an index. Each pass copies the current element into the loop variable.

```java
int[] scores = {85, 92, 78, 96, 88};

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

The loop variable type must match the element type. This loop is clean for reading values, but it has an important limit: the variable is a copy of the element, not the element itself.

## Copy Semantics: The Most Tested Idea Here

The enhanced `for` loop variable holds a copy of each element. Reassigning that variable changes only the copy, not the array.

```java
int[] nums = {1, 2, 3};

for (int n : nums) {
    n = n * 10;   // changes the copy, not the array
}
// nums is still {1, 2, 3}
```

To actually change stored values, use an index:

```java
int[] nums = {1, 2, 3};

for (int i = 0; i < nums.length; i++) {
    nums[i] = nums[i] * 10;   // changes the array
}
// nums is now {10, 20, 30}
```

### Arrays of objects behave a little differently

When an array stores object references, the enhanced `for` loop variable copies the [reference](/ap-comp-sci-a/key-terms/reference "fv-autolink"), which still points to the same object. That means you can call methods on the loop variable to change the object's attributes, and those changes stick because both the variable and the array element point to the same object.

```java
// Assume Student has a method addPoints(int p)
for (Student s : roster) {
    s.addPoints(5);   // modifies the actual Student object
}
```

What you cannot do is replace the stored reference by reassigning the loop variable. Writing `s = new Student(...)` inside the loop only changes the copy, so the array still holds the original reference.

## Rewriting One Loop as Another

These three loops produce the same output. Being able to convert between them helps when a problem requires an index you do not have, or when you want to trace code more carefully.

```java
int[] data = {4, 8, 15, 16, 23};

// Enhanced for loop
for (int value : data) {
    System.out.println(value);
}

// Indexed for loop
for (int i = 0; i < data.length; i++) {
    System.out.println(data[i]);
}

// while loop
int i = 0;
while (i < data.length) {
    System.out.println(data[i]);
    i++;
}
```

If a task asks you to modify elements or use positions, switch from an enhanced `for` loop to an indexed `for` loop or `while` loop so you have the index available.

## Traversal Patterns You Will Reuse

These patterns all build on the same [loop structure](/ap-comp-sci-a/key-terms/loop-structure "fv-autolink"). What changes is the work inside the loop. The standard [algorithms](/ap-comp-sci-a/key-terms/algorithm "fv-autolink") that depend on these traversals (sums, max, counts, and so on) are covered more fully in 4.5 Implementing Array Algorithms, but the traversal itself is the foundation.

```java
int[] scores = {85, 92, 78, 96, 88, 73, 91};

// Sum and average
int total = 0;
for (int i = 0; i < scores.length; i++) {
    total += scores[i];
}
double average = (double) total / scores.length;

// Count elements that meet a condition
int highScores = 0;
for (int i = 0; i < scores.length; i++) {
    if (scores[i] >= 90) {
        highScores++;
    }
}

// Find the index of the maximum value
int maxIndex = 0;
for (int i = 1; i < scores.length; i++) {
    if (scores[i] > scores[maxIndex]) {
        maxIndex = i;
    }
}
```

Notice the loop structure stays the same. Only the body changes based on what you need.

## How to Use This on the AP Computer Science A Exam

### Code Tracing

When you trace traversal code, write down the index and any running variables for each pass. Track the loop bound carefully: a loop with `i <= array.length` will reach an invalid index and throw an `ArrayIndexOutOfBoundsException`. If no array is provided, build a small one like `{3, 1, 4}` and step through it.

### Free Response

When you write a method that traverses an array, pick the loop that matches the job. If you only read values, an enhanced `for` loop is clean. If you change elements or need positions, use an indexed `for` loop or `while` loop. Double-check your bounds and your [accumulator](/ap-comp-sci-a/key-terms/accumulator "fv-autolink")'s starting value before moving on.

### Common Trap

Watch for code that reassigns an enhanced `for` loop variable and expects the array to change. The array stays the same. Also check whether a method needs to visit every element (like an average) or can stop early once it finds a match.

## Common Misconceptions

- Assigning a new value to an enhanced `for` loop variable does not change the array. To change stored values, use an index and write `array[i] = value`.
- Calling a method on an enhanced `for` loop variable that is an object reference does change that object. People mix this up with reassignment, but modifying an object's attributes is different from replacing the reference.
- Valid indices stop at `array.length - 1`. Using `i <= array.length` runs one step too far and throws an `ArrayIndexOutOfBoundsException`.
- The array's `length` is an attribute written as `array.length` with no parentheses. It is not a [method call](/ap-comp-sci-a/key-terms/method-call "fv-autolink") like `array.length()`.
- An enhanced `for` loop does not give you the index. If you need the position of an element, use an indexed `for` loop or a `while` loop instead.
- A `while` loop used for traversal needs you to update the index yourself. Leaving out the `i++` creates an infinite loop.

## Related AP Computer Science A Guides

- [4.11 2D Arrays](/ap-comp-sci-a/unit-4/2d-arrays/study-guide/5WDx6ZFeWhx2aVuiZI6R)
- [4.5 Developing Algorithms Using Arrays](/ap-comp-sci-a/unit-4/developing-algorithms-using-arrays/study-guide/c6dpJfmjG7oVFDqnXFAk)
- [4.1 Ethical and Social Implications](/ap-comp-sci-a/unit-4/ethical-and-social-implications/study-guide/iec7yzDQ2qENx5UAdiPJ)
- [4.9 Traversing ArrayLists](/ap-comp-sci-a/unit-4/traversing-arraylists/study-guide/U4SdcheNw5PMSIzjU2oL)
- [4.13 Implementing 2D Array Algorithms](/ap-comp-sci-a/unit-4/implementing-2d-array-algorithms/study-guide/9ucC5cB6ffrLnA4b3FU3)
- [4.16 Recursion](/ap-comp-sci-a/unit-4/recursion/study-guide/p4D3YegZCLwQ3KJVvsd4)

## Vocabulary

- **array index**: The numeric position used to access a specific element in an array.
- **array traversal**: The process of using repetition statements to systematically access elements in an array.
- **enhanced for loop**: A Java loop construct that iterates through all elements of a collection without using an index variable.
- **enhanced for loop variable**: The variable in an enhanced for loop header that is assigned a copy of each array element during each iteration.
- **indexed for loop**: A loop that accesses array elements by using their index positions to control iteration.
- **object reference**: A value that points to the memory location where an object is stored, allowing access to that object.
- **traverse**: To visit each element in a data structure (such as a string, array, or ArrayList) in a systematic way, often using recursion.
- **while loop**: An iterative statement that repeatedly executes a block of code as long as a specified Boolean expression evaluates to true.

## FAQs

### What does traversing an array mean in AP CSA?

Traversing an array means using a loop to access every element or an ordered sequence of elements. In AP CSA, you commonly traverse arrays to print values, search for a value, calculate totals, or update elements.

### When should you use an indexed for loop to traverse an array?

Use an indexed for loop when you need the index, need to change array elements, compare neighboring elements, traverse backward, or use the same index across multiple arrays. The standard pattern is i = 0 while i < array.length.

### When should you use an enhanced for loop with an array?

Use an enhanced for loop when you only need to read each element in order and do not need the index. It is shorter and cleaner, but the loop variable receives a copy of each element.

### Can an enhanced for loop change array values?

Reassigning the enhanced for loop variable does not change the value stored in the array. To replace array elements, use an indexed loop and assign directly with array[i] = newValue.

### How do enhanced for loops work with arrays of objects?

For arrays of object references, the enhanced for loop variable receives a copy of the reference. Calling methods on that object can change its attributes, but assigning the loop variable to a new object does not replace the reference stored in the array.

### What is a common AP CSA mistake when traversing arrays?

A common mistake is using i <= array.length instead of i < array.length. Valid array indices run from 0 to array.length - 1, so using <= can cause an ArrayIndexOutOfBoundsException.

## Structured Data

```json
{"@context":"https://schema.org","@type":"FAQPage","inLanguage":"en","mainEntity":[{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t#what-does-traversing-an-array-mean-in-ap-csa","name":"What does traversing an array mean in AP CSA?","acceptedAnswer":{"@type":"Answer","text":"Traversing an array means using a loop to access every element or an ordered sequence of elements. In AP CSA, you commonly traverse arrays to print values, search for a value, calculate totals, or update elements."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t#when-should-you-use-an-indexed-for-loop-to-traverse-an-array","name":"When should you use an indexed for loop to traverse an array?","acceptedAnswer":{"@type":"Answer","text":"Use an indexed for loop when you need the index, need to change array elements, compare neighboring elements, traverse backward, or use the same index across multiple arrays. The standard pattern is i = 0 while i < array.length."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t#when-should-you-use-an-enhanced-for-loop-with-an-array","name":"When should you use an enhanced for loop with an array?","acceptedAnswer":{"@type":"Answer","text":"Use an enhanced for loop when you only need to read each element in order and do not need the index. It is shorter and cleaner, but the loop variable receives a copy of each element."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t#can-an-enhanced-for-loop-change-array-values","name":"Can an enhanced for loop change array values?","acceptedAnswer":{"@type":"Answer","text":"Reassigning the enhanced for loop variable does not change the value stored in the array. To replace array elements, use an indexed loop and assign directly with array[i] = newValue."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t#how-do-enhanced-for-loops-work-with-arrays-of-objects","name":"How do enhanced for loops work with arrays of objects?","acceptedAnswer":{"@type":"Answer","text":"For arrays of object references, the enhanced for loop variable receives a copy of the reference. Calling methods on that object can change its attributes, but assigning the loop variable to a new object does not replace the reference stored in the array."}},{"@type":"Question","@id":"https://fiveable.me/ap-comp-sci-a/unit-4/traversing-arrays/study-guide/kRcOqfawCcBz6gcT646t#what-is-a-common-ap-csa-mistake-when-traversing-arrays","name":"What is a common AP CSA mistake when traversing arrays?","acceptedAnswer":{"@type":"Answer","text":"A common mistake is using i <= array.length instead of i < array.length. Valid array indices run from 0 to array.length - 1, so using <= can cause an ArrayIndexOutOfBoundsException."}}]}
```
