Traversing arrays: visiting every element.
Almost every AP array problem reduces to a traversal — sum, search, count, transform, compare.
A traversal is the act of visiting every element of an array in some order. The most common pattern is left-to-right with an indexed for loop, but you'll also use enhanced for loops, reverse loops, and partial loops.
Choosing the right loop type matters. The indexed loop gives you the index (needed for modification or comparison with neighbors); the enhanced loop is cleaner when you only need values (and never modifies the array).
Traversals are the heart of nearly every array FRQ — sums, maxes, counts, filters, transformations. Build the patterns into muscle memory.
Two loop styles, two purposes.
Pick by whether you need the index or just the value.
Standard for loop (with index)
int[] nums = {3, 1, 4, 1, 5, 9, 2};
for (int i = 0; i < nums.length; i++) {
System.out.println(i + ": " + nums[i]);
}
Use this when you need the index — for example, to modify elements, compare with neighbors, or report positions.
Enhanced for loop (for-each)
for (int n : nums) {
System.out.println(n);
}
Reads each element in order, one per iteration. The variable n is a copy of each element — assigning to it does not change the array.
Common traversal patterns
// Sum
int sum = 0;
for (int n : nums) sum += n;
// Maximum
int max = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > max) max = nums[i];
}
// Count matches
int count = 0;
for (int n : nums) {
if (n > 3) count++;
}
// Transform every element
for (int i = 0; i < nums.length; i++) {
nums[i] = nums[i] * 2;
}
Partial traversals
// Skip the first element
for (int i = 1; i < nums.length; i++) { ... }
// Stop one before the end (e.g., compare with i+1)
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) { ... }
}
Reverse traversal
for (int i = nums.length - 1; i >= 0; i--) {
System.out.println(nums[i]);
}
Useful when shifting elements right or printing in reverse order.
Traversal terminology.
Each appears regularly in AP rubrics and stems.
- Traversal — visiting every element of a collection.
- Indexed for loop — uses a counter variable to access elements by position.
- Enhanced for loop — iterates over each value without an explicit index.
- Partial traversal — visits only part of the array.
- Accumulator — a variable that grows across iterations (sum, count, max).
- Bound — the value the loop variable is compared against.
- Element access — reading or writing a specific position.
How traversals are tested.
Off-by-one, enhanced-for misuse, and partial bounds dominate.
MCQ patterns to expect:
- Enhanced-for cannot modify the array. Assigning to the loop variable changes only the local copy.
- Partial bounds. Loops that compare neighbors must stop at
length - 1. - Wrong starting index. Starting at 1 skips the first element.
- Off-by-one with
<=. Usingi <= arr.lengththrows an exception.
FRQ tip: pick the indexed loop when modifying elements or accessing positions; pick the enhanced loop when only the values matter and you want cleaner code.
Count adjacent equal pairs.
A classic partial traversal pattern.
Problem. Write a method that returns the number of adjacent equal pairs in an array. For {1, 1, 2, 3, 3, 3}, the answer is 3 (the two 1s, the first pair of 3s, and the second pair of 3s).
Step 1. Compare each element to its right neighbor. The last index that has a right neighbor is length - 2, so loop while i < length - 1.
Step 2. Increment a counter whenever arr[i] == arr[i + 1].
Step 3. Use the indexed loop because we need both i and i + 1.
public static int countAdjacentPairs(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] == arr[i + 1]) {
count++;
}
}
return count;
}
Trace. For {1, 1, 2, 3, 3, 3}: indices (0,1) match → 1, (1,2) no, (2,3) no, (3,4) match → 2, (4,5) match → 3. Returns 3.
Why this matters. Whenever the inner logic accesses i + 1, the loop bound must shrink by one. Many AP MCQs hide this exact trap.
Traversal errors that lose marks.
Most are off-by-one or wrong loop type.
- Modifying via enhanced-for. The loop variable is a copy; reassigning it does nothing to the array. Use an indexed loop to actually change elements.
- Wrong bound.
i <= arr.lengththrows an exception. Always usei < arr.length. - Forgetting
- 1for neighbor comparisons. Accessingarr[i + 1]without stopping atlength - 1goes out of bounds. - Starting accumulator wrong. Initialize
maxtoarr[0](not0) when finding maxima — negative arrays would break it. - Skipping elements unintentionally. Starting at index
1when you meant0, or usingi += 2by accident. - Confusing index with value. Returning
iwhen the question asked forarr[i], or vice versa.
Traversal patterns at a glance.
Choose the right one before you write any code.
Traversing Arrays Reference
AP Quick Reference| Task | Best loop | AP Exam Tip |
|---|---|---|
| Read every value | Enhanced for | Cleanest when no index is needed. |
| Modify elements | Indexed for | Enhanced for cannot modify the array. |
| Compare neighbors | Indexed for, i < length - 1 |
Stop one early to safely access i + 1. |
| Reverse order | Indexed for, decreasing | Start at length - 1; condition i >= 0. |
| Find a max or min | Indexed for from 1 |
Initialize the result with arr[0]. |
| Count or sum | Enhanced for | Initialize accumulator before the loop. |
How to gain traversal fluency.
Build a personal library of patterns you can deploy instantly.
Use the three practice tools below this lesson in order:
- MCQ Practice — for each traversal, write the values of the loop variable and the accumulator after every iteration. This crushes off-by-one and enhanced-for misuse traps.
- Java Lab — implement sum, max, min, count-matches, and a transformation. Always use
arr.lengthas the bound. - FRQ Practice — when planning, name the pattern aloud: "This is a count-matches with a guard." Naming the pattern unlocks the template.
If you can write sum, max, and count from memory in under a minute each, traversal questions become free points.
Practice — attempt these now.
AP-style assessments aligned to this lesson. Time them.