01 / 21

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.

AP Computer Science A

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 \).

12 7 3 25 9 0 1 2 3 4 int[] arr = {12, 7, 3, 25, 9};

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 \).

12 7 3 25 9 i = 0 0 1 2 3 4 i increments from 0 to arr.length - 1

Why Traversals Matter

★ Searching
Find whether a value exists, or locate the index of a target element.
★ Accumulation
Compute sums, averages, counts, or build new data from the array.
★ Transformation
Modify every element: doubling values, shifting characters, filtering data.

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.

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

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 (int val : arr) { System.out.println(val); }

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

Forward
\( \texttt{for (int i = 0; i < arr.length; i++)} \)
Visit \( 0 \to n{-}1 \)
Backward
\( \texttt{for (int i = arr.length - 1; i >= 0; i--)} \)
Visit \( n{-}1 \to 0 \)
Even indices
\( \texttt{for (int i = 0; i < arr.length; i += 2)} \)
Visit \( 0, 2, 4, \ldots \)
Partial
\( \texttt{for (int i = 1; i < arr.length - 1; i++)} \)
Skip first and last

How to Apply a Traversal

1
Identify the goal. Are you searching, accumulating, or transforming?
2
Choose your loop. Need the index? Use a for loop. Read-only? for-each works.
3
Set up any variables before the loop: accumulators (\( \text{sum} = 0 \)), flags (\( \text{found} = \text{false} \)), or counters.
4
Write the loop body. Process each element: compare, add, assign, or call a method.
5
Use the result after the loop: return the sum, print the count, or check the flag.

Example: Sum of Elements

Compute the total of all values in the array {12, 7, 3, 25, 9}.

int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } // sum is now 56
12 7 3 25 9 sum=12 sum=19 sum=22 sum=47 sum=56 Result: sum = 56

Example: Find the Maximum

Traverse an array to find the largest element. Initialize with the first element, then compare each subsequent value.

int max = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; } } // max is now 25

Example: Count Matches

Count how many elements in an array are greater than 10. This combines traversal with a conditional check.

int count = 0; for (int val : arr) { if (val > 10) { count++; } } // For {12, 7, 3, 25, 9}: count = 2
12 7 3 25 9 ✓ ✕ ✕ ✓ ✕
\( > 10 \)
\( \le 10 \)
\( \le 10 \)
\( > 10 \)
\( \le 10 \)

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.

for (int i = arr.length - 1; i >= 0; i--) { System.out.print(arr[i] + " "); } // Output: 9 25 3 7 12
12 7 3 25 9 i starts here

Early Exit with break

When searching for a specific value, you can stop early once found using break or return. This avoids unnecessary iterations.

int target = 25; int index = -1; for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { index = i; break; } } // index = 3

Common Mistakes

✕ Off-by-one error
Using \( \texttt{i <= arr.length} \) instead of \( \texttt{i < arr.length} \). The last valid index is \( n{-}1 \), not \( n \).
✕ Modifying with for-each
Assigning to the loop variable in a for-each loop: val = 0; does not change the array element.
✕ Wrong initialization
Initializing max/min to 0 instead of arr[0]. If all values are negative, the "max" of 0 is wrong.

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]);
}

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?