AP CSA Lesson 4.2: Traversing Arrays

AP CSA • Unit 4: Data Collections • Lesson 4.2

Traversing Arrays: Index Loops and For-Each

Walk every slot exactly once. Use an index loop when you need the position or want to change elements; use a for-each when you just read the values.

Design Code Develop Code Analyze Code Document Code Use Computers Responsibly
Loading the interactive lesson. If this note stays visible, this preview is blocking JavaScript. Download the file and open it in a browser (Chrome), or view it on the live page, to use the editor, game, and quiz.
Learn
Practice
Assess
Scenario

The problem this code solves

A gradebook stores one score per student in an array. To show the class average, the top score, or how many passed, the program has to walk the whole array and do something with each score. That walk is a traversal, and nearly every array question on the exam is one. The only real choices are whether you need the index and whether you are reading or changing the data.

Skill focus: today you Analyze code (predict what a traversal produces), Develop it (write both loop styles), and Design it (pick the right one for the task).
Learn

Traversing an array: visit every element, exactly once

An array stores its elements in numbered slots. The first is index 0 and the last is index length - 1. Almost every array algorithm is a traversal: walk the slots in order, doing something with each element.

Two ways to traverse

// index loop: you have the position i
for (int i = 0; i < data.length; i++) {
    System.out.println(data[i]);
}

// enhanced for-each: just the values
for (int x : data) {
    System.out.println(x);
}
Which to use
need the index i index loop
need to change elements index loop
just reading values for-each

data.length is the number of slots. Notice it is a field, so there are no parentheses (that is length, not length(), which is the String method).

The for-each catch: it is a copy

Watch out: in for (int x : data), x is a copy of each element. Assigning to x does not change the array. To modify elements, use an index loop and write to data[i].

The bound: less-than, not less-than-or-equal

Watch out: valid indices run 0 to length - 1. The loop condition is i < data.length. Writing i <= data.length steps one slot past the end and throws ArrayIndexOutOfBoundsException.

Vocabulary

Term Meaning
Index The position of an element, from 0 up to length - 1.
length The number of slots in an array. A field, so no parentheses: arr.length.
Traversal Visiting each element of the array in order, exactly once.
Enhanced for loop for (int x : arr): reads each value in turn without an index; the variable is a copy.
ArrayIndexOutOfBoundsException Thrown when you access an index below 0 or at length or higher.

Predict first, then check

1. int[] arr = {10, 20, 30}; What is arr.length?
2. In an array of length 5, the valid indices run from 0 to ____.
3. for (int i = 0; i < arr.length; i++) visits how many elements if arr has 6 slots?
See it in memory

See the traversal find the max

The maximum starts at index 0, then each element is compared to the best seen so far. Play it and watch the pointer walk the array while max updates.

int max = data[0];
for (int i = 1; i < data.length; i++) {
    if (data[i] > max) { max = data[i]; }
}
max3
03
19
22
37
45
Original interactive traversal. The blue box is the current element; the green box is the best (max) so far.
Practice • write and run real Java

Live code editor

Eight problems, six scaffolded and two open-ended. Write Java, press Run to execute it, and Check to test against the expected output. Hints and the solution are here if you need them, but using them is tracked, so try first.

Practice • fluency

Array Traversal Arcade

Six quick rounds. Read the array or the loop and type the result. Sharpens the index and for-each patterns you use on every array FRQ.

Assess • six questions at AP difficulty

Multiple choice

Predict your answer before reading the options. Watch for the qualifier words. After you answer, the rationale explains every distractor.

Assess • free-response connection

FRQ connection: count within a range

FRQ 1 and the array FRQs lean on traversal plus a conditional. Practice it: walk the array and count the elements that fall in a range.

Every student challenged

Choose your lane

Support

  • Reread the Code and Memory panels
  • Editor problems 1 to 3 with hints on
  • Retry the quiz until 80%
  • Use the FRQ method shell

Core

  • All 8 editor problems
  • Full game run
  • The 6-question quiz once
  • The FRQ connection

Challenge

  • Open-ended problems 7 and 8 with no hints
  • Rewrite one loop a different way
  • Extend the FRQ
  • Lead a class trace
This lesson reports to the gradebook: lesson (completion), exercise-1 (code editor), exercise-2 (game), quiz (MCQ), and exercise-3 (FRQ). Live usage is tracked in window.LESSON_USAGE.

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]