Array
Traversals
Master the art of visiting every element in an array: from basic for loops to enhanced for-each, with patterns you will use on the AP exam and beyond.
What Is an Array?
An array is a fixed-size, ordered collection of elements stored in contiguous memory. Each element is accessed by its index: an integer starting at \( 0 \) and ending at \( \text{length} - 1 \).
What Is a Traversal?
A traversal is the process of visiting every element of a data structure exactly once (or until a condition is met). For arrays, this means stepping through indices \( 0, 1, 2, \ldots, n{-}1 \).
Why Traversals Matter
The Standard for Loop
The most common traversal pattern uses a standard for loop with an index variable that starts at \( 0 \) and increments until it reaches arr.length.
The Enhanced for-each Loop
Java's enhanced for loop (for-each) simplifies traversal when you don't need the index. It gives you each element value directly.
for vs for-each
| Feature | Standard for | Enhanced for-each |
|---|---|---|
| Access index? | ✓ Yes | ✕ No |
| Modify elements? | ✓ Yes | ✕ No (copy only) |
| Traverse backwards? | ✓ Yes | ✕ No |
| Skip elements? | ✓ Yes | ✕ No |
| Simpler syntax? | ✕ More verbose | ✓ Cleaner |
Traversal Variations
Visit \( 0 \to n{-}1 \)
Visit \( n{-}1 \to 0 \)
Visit \( 0, 2, 4, \ldots \)
Skip first and last
How to Apply a Traversal
Example: Sum of Elements
Compute the total of all values in the array {12, 7, 3, 25, 9}.
Example: Find the Maximum
Traverse an array to find the largest element. Initialize with the first element, then compare each subsequent value.
Example: Count Matches
Count how many elements in an array are greater than 10. This combines traversal with a conditional check.
Example: Reverse Traversal
Sometimes you need to traverse backwards: printing in reverse order, or checking elements from the end. Start at \( \text{arr.length} - 1 \) and decrement.
Early Exit with break
When searching for a specific value, you can stop early once found using break or return. This avoids unnecessary iterations.
Common Mistakes
Traversal Summary
| Pattern | Code Template | Use Case |
|---|---|---|
| Forward | \( \texttt{for (i=0; i| General purpose |
|
| Backward | \( \texttt{for (i=len-1; i>=0; i--)} \) | Reverse print, right-to-left |
| For-each | \( \texttt{for (int v : arr)} \) | Read-only access |
| Partial | \( \texttt{for (i=start; i| Subarray processing |
|
| Search | \( \texttt{for + if + break} \) | Find first match |
Question 1 of 5
What is the output of the following code?int[] a = {5, 10, 15};
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
Question 2 of 5
Which loop can modify the elements of an array in place?
Question 3 of 5
What happens when this code runs?int[] b = {2, 4, 6};
for (int i = 0; i <= b.length; i++) {
System.out.print(b[i]);
}
i <= b.length allows i to reach 3. The loop prints b[0], b[1], b[2] successfully (outputting 246), but then tries b[3] which is out of bounds, causing an exception. The fix is to use i < b.length.Question 4 of 5
Given int[] nums = {3, -1, 7, -4, 2}, what value does this code produce?int count = 0;
for (int n : nums) {
if (n > 0) count++;
}
// count = ?
Question 5 of 5
Which initialization is best for finding the minimum value in an array arr of integers?