Lesson 4.4: Traversing Arrays
Lesson 4.4: Traversing Arrays
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.
Practice Questions
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);
arr in reverse order?for (int i = arr.length; i > 0; i--) {
System.out.println(arr[i]);
}
for (int i = arr.length; i >= 0; i--) {
System.out.println(arr[i]);
}
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}
for (int i = arr.length - 1; i > 0; i--) {
System.out.println(arr[i]);
}
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.int[] vals = {10, 20, 30, 40};
for (int v : vals) {
v = v + 5;
}
System.out.println(vals[0]);
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.nums?for (int n : nums) {
n *= 2;
}
for (int i = 1; i < nums.length; i++) {
nums[i] *= 2;
}
for (int i = 0; i <= nums.length; i++) {
nums[i] *= 2;
}
for (int i = 0; i < nums.length; i++) {
nums[i] *= 2;
}
nums[0]. C uses <= — throws ArrayIndexOutOfBoundsException on the last iteration. D is correct: starts at 0, uses <, modifies via index.int[] arr = {5, 3, 8, 1, 9, 2};
int count = 0;
for (int x : arr) {
if (x > 4) count++;
}
System.out.println(count);
Mastery: Traversing Arrays
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]);
for (int x : arr) {
if (x > 50)
return x;
}
return -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 50)
return arr[i];
}
return -1;
for (int i = 1; i <= arr.length; i++) {
if (arr[i] > 50)
return i;
}
return -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 50)
return i;
}
return -1;
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.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);
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.Product class has a method getPrice() that returns a double. Given Product[] inventory, which code correctly computes the total price of all products?double total = 0;
for (int i = 1; i < inventory.length; i++) {
total += inventory.getPrice();
}
double total = 0;
for (int i = 0; i < inventory.length; i++) {
total += inventory[i];
}
double total = 0;
for (Product p : inventory) {
total += p.getPrice();
}
return total;
double total = 0;
for (Product p : inventory) {
total += inventory.getPrice();
}
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.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);
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]