Lesson 4.4: Traversing Arrays

Unit 4 · Lesson 4.4 · Arrays

Lesson 4.4: Traversing Arrays

🕑 40–50 min · 10 Practice Questions · New Syntax · Code Tracing

What You'll Learn

  • 4.4.A: Traverse the elements in a 1D array.
  • Write standard for loops to traverse arrays from front to back, back to front, and partial ranges.
  • Write enhanced for-each loops and explain when to use each loop type.
  • Identify the off-by-one error pattern and how it causes ArrayIndexOutOfBoundsException.
  • Read and modify array elements during traversal.

Key Vocabulary

Term Definition
traversal Visiting every element in a collection exactly once, typically using a loop.
standard for loop A loop with an index variable that gives direct control over which elements are visited and in what order.
enhanced for loop (for-each) A loop that automatically visits every element from front to back without an explicit index variable. Cannot modify elements or traverse in reverse.
off-by-one error A logic error where a loop iterates one too many or one too few times, often caused by using <= instead of < or starting at 1 instead of 0.

Standard For Loop Traversal (4.4.A)

The most common pattern for traversing an array uses a standard for loop with an index variable i that starts at 0 and runs while i < array.length:

int[] scores = {92, 74, 88, 58, 95};

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

This prints every element from index 0 to index 4. The loop runs exactly scores.length times — once per element.

📌 Why i < array.length, not i <= array.length

When i equals array.length, that index doesn't exist. The last valid index is always array.length - 1. Using <= is the classic off-by-one error — the loop runs one extra time and throws ArrayIndexOutOfBoundsException.

Modifying Elements During Traversal

Because the standard for loop gives you the index, you can read and write elements in the same loop:

// Double every value in the array
for (int i = 0; i < scores.length; i++) {
    scores[i] = scores[i] * 2;
}
// scores is now {184, 148, 176, 116, 190}

Traversing in Reverse

Start at the last index and decrement:

for (int i = scores.length - 1; i >= 0; i--) {
    System.out.println(scores[i]);
}

This prints elements from index 4 down to index 0 — last to first.

Partial Traversal

You don't have to visit every element. Adjust the start or end condition:

// Print only the first 3 elements
for (int i = 0; i < 3; i++) {
    System.out.println(scores[i]);
}

// Print only elements at even indices (0, 2, 4...)
for (int i = 0; i < scores.length; i += 2) {
    System.out.println(scores[i]);
}

✅ Example: Finding the Maximum

int[] scores = {92, 74, 88, 58, 95};
int max = scores[0];  // assume first is largest

for (int i = 1; i < scores.length; i++) {
    if (scores[i] > max) {
        max = scores[i];
    }
}
System.out.println(max);  // 95

Start max at scores[0], then loop from index 1 onward. Starting the loop at 1 avoids comparing the first element to itself unnecessarily.

Enhanced For Loop (For-Each)

Java's enhanced for loop removes the need for an index variable when you only need to read every element front to back:

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

Read it as: "for each int named score in scores, do..." The loop automatically visits every element from first to last.

For-Each vs. Standard For — Know the Difference

Situation Use This Loop
Read every element, front to back for-each ✓
Modify (write to) elements standard for ✓
Traverse in reverse standard for ✓
Access the index value itself standard for ✓
Partial traversal (skip elements) standard for ✓
Compare adjacent elements standard for ✓

⚠️ AP Exam Trap: For-Each Cannot Modify the Array

for (int score : scores) {
    score = score * 2;  // DOES NOT modify the array
}

score is a copy of each element, not a reference to the slot. Assigning to it has no effect on the array. This is one of the most common errors tested on the AP exam. To modify elements, use a standard for loop with scores[i] = ....

The Off-By-One Error

This error trips up every programmer at some point. It comes in two flavors:

// Error 1: Using <= instead of <
for (int i = 0; i <= scores.length; i++) {  // throws exception on last iteration
    System.out.println(scores[i]);
}

// Error 2: Starting at 1 instead of 0
for (int i = 1; i < scores.length; i++) {  // skips scores[0]
    System.out.println(scores[i]);
}

On the AP exam, off-by-one errors are tested both as bugs to identify and as correct-or-incorrect code questions.

Traversing Arrays of Objects

The same loop patterns work for any element type. For an array of objects, access attributes using getter methods:

Student[] roster = { new Student("Alice", 92),
                     new Student("Ben",   74),
                     new Student("Carlos", 58) };

// Print every student's name
for (Student s : roster) {
    System.out.println(s.getName());
}

// Find the highest score
int max = roster[0].getScore();
for (int i = 1; i < roster.length; i++) {
    if (roster[i].getScore() > max) {
        max = roster[i].getScore();
    }
}

Summary

  • Standard for loop: for (int i = 0; i < arr.length; i++) — use when you need the index, must modify elements, traverse in reverse, or do a partial traversal.
  • Enhanced for loop: for (Type x : arr) — use when reading every element front to back. Cleaner but cannot modify the array.
  • Off-by-one: using <= causes an out-of-bounds exception; starting at 1 skips the first element.
  • For-each copies the element value — assigning to the loop variable does not change the array.
▶ Java Code Editor
Try It Yourself
Write real Java, hit Run, and your code executes on a live compiler. Output is checked automatically.

Practice Questions

MCQ 1
What is printed by the following code?
int[] arr = {1, 2, 3, 4, 5};
int total = 0;
for (int i = 0; i < arr.length; i++) {
    total += arr[i];
}
System.out.println(total);
Predict before reading the options.
A 10
B 15
C 14
D 5
B. The loop visits all 5 elements (indices 0–4). 1+2+3+4+5 = 15. A (10) would be missing 5. C (14) would be missing 1. D (5) is the last element only.
MCQ 2
Which loop correctly prints every element of arr in reverse order?
Predict before reading the options.
A
for (int i = arr.length; i > 0; i--) {
    System.out.println(arr[i]);
}
B
for (int i = arr.length; i >= 0; i--) {
    System.out.println(arr[i]);
}
C
for (int i = arr.length - 1; i >= 0; i--) {
    System.out.println(arr[i]);
}
D
for (int i = arr.length - 1; i > 0; i--) {
    System.out.println(arr[i]);
}
C. Start at arr.length - 1 (last valid index), stop when i >= 0 (includes index 0). A and B start at arr.length which is out of bounds. D uses i > 0 which stops before printing arr[0] — misses the first element.
MCQ 3
What is the result of this code?
int[] vals = {10, 20, 30, 40};
for (int v : vals) {
    v = v + 5;
}
System.out.println(vals[0]);
Predict before reading the options.
A 10
B 15
C 5
D 20
A. The for-each loop copies each element into v. Assigning to v changes only the copy — the array is untouched. vals[0] remains 10. This is the most commonly tested for-each trap on the AP exam.
MCQ 4
Which of the following correctly doubles every element in an array nums?
A
for (int n : nums) {
    n *= 2;
}
B
for (int i = 1; i < nums.length; i++) {
    nums[i] *= 2;
}
C
for (int i = 0; i <= nums.length; i++) {
    nums[i] *= 2;
}
D
for (int i = 0; i < nums.length; i++) {
    nums[i] *= 2;
}
D. A uses for-each — won't modify the array. B starts at index 1 — skips nums[0]. C uses <= — throws ArrayIndexOutOfBoundsException on the last iteration. D is correct: starts at 0, uses <, modifies via index.
MCQ 5
What is printed?
int[] arr = {5, 3, 8, 1, 9, 2};
int count = 0;
for (int x : arr) {
    if (x > 4) count++;
}
System.out.println(count);
Predict before reading the options.
A 2
B 4
C 3
D 6
C. Elements greater than 4: 5 ✓, 3 ✗, 8 ✓, 1 ✗, 9 ✓, 2 ✗. Three elements qualify. This is a classic filter-and-count traversal — a pattern that appears on FRQ #3 every year.
Tier 3 · AP Mastery

Mastery: Traversing Arrays

MCQ 6
What is printed by the following code?
int[] arr = {2, 4, 6, 8, 10};
for (int i = 0; i < arr.length - 1; i++) {
    arr[i] = arr[i + 1];
}
System.out.println(arr[0] + " " + arr[3]);
Trace carefully — elements shift as the loop runs.
A 2 8
B 4 10
C 4 8
D 2 10
B. The loop shifts every element one position left (each element gets the value of its right neighbor). Trace: i=0: arr[0]=arr[1]=4 · i=1: arr[1]=arr[2]=6 · i=2: arr[2]=arr[3]=8 · i=3: arr[3]=arr[4]=10. Final array: {4,6,8,10,10}. So arr[0]=4 and arr[3]=10.
MCQ 7
A method receives an array of integers and should return the index of the first element greater than 50. Which implementation is correct?
Predict before reading the options.
A
for (int x : arr) {
    if (x > 50)
        return x;
}
return -1;
B
for (int i = 0; i < arr.length; i++) {
    if (arr[i] > 50)
        return arr[i];
}
return -1;
C
for (int i = 1; i <= arr.length; i++) {
    if (arr[i] > 50)
        return i;
}
return -1;
D
for (int i = 0; i < arr.length; i++) {
    if (arr[i] > 50)
        return i;
}
return -1;
D. The method must return the index, not the element value. A uses for-each — no index available. B returns the element value arr[i] instead of the index i. C starts at index 1 (skips index 0) and uses <= (out-of-bounds). D starts at 0, uses <, and returns i — correct.
MCQ 8
What is printed?
int[] arr = {1, 2, 3, 4, 5};
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
    if (arr[i] % 2 == 0) result += arr[i];
}
System.out.println(result);
Note the loop bound carefully before tracing.
A 6
B 2
C 4
D 10
A. The bound is arr.length - 1 = 4, so the loop visits indices 0–3 only (skips index 4, which holds 5). Even values in that range: arr[1]=2 ✓, arr[3]=4 ✓. Sum = 6. D (10) would be correct if the loop included index 4, but 5 is odd so it wouldn't matter — the trap is whether students notice the loop skips the last element.
MCQ 9
A Product class has a method getPrice() that returns a double. Given Product[] inventory, which code correctly computes the total price of all products?
Predict before reading the options.
A
double total = 0;
for (int i = 1; i < inventory.length; i++) {
    total += inventory.getPrice();
}
B
double total = 0;
for (int i = 0; i < inventory.length; i++) {
    total += inventory[i];
}
C
double total = 0;
for (Product p : inventory) {
    total += p.getPrice();
}
return total;
D
double total = 0;
for (Product p : inventory) {
    total += inventory.getPrice();
}
C. A calls getPrice() on the array itself (not an element) and skips index 0. B adds the object reference, not its price. D calls inventory.getPrice() — same error as A. C correctly uses for-each to visit each Product object and calls getPrice() on it.
MCQ 10
What is printed?
int[] arr = {3, 1, 4, 1, 5, 9};
int prev = arr[0];
int count = 0;
for (int i = 1; i < arr.length; i++) {
    if (arr[i] < prev) count++;
    prev = arr[i];
}
System.out.println(count);
Trace step by step — this compares adjacent elements.
A 1
B 2
C 3
D 4
B. The loop counts how many times an element is less than the one before it (a "drop"). Trace: prev=3 · i=1: arr[1]=1 < 3 ✓ count=1, prev=1 · i=2: arr[2]=4 < 1? No, prev=4 · i=3: arr[3]=1 < 4 ✓ count=2, prev=1 · i=4: arr[4]=5 < 1? No, prev=5 · i=5: arr[5]=9 < 5? No. Final count=2. Note the loop starts at i=1 — this is the correct pattern for comparing adjacent elements.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]