AP® Computer Science A · Unit 4 · Topic 4.4
Traversing an Array with a for Loop
Traversing an array with a for loop means using a counter variable as the index to visit each element in turn, so one small block of code handles arrays of any size.
Writing a hundred print statements for a hundred values is slow and error prone. A for loop fixes this by using a counter, usually named i, that counts through the valid indices of the array, 0 up to a.length - 1. On each pass, a[i] refers to a different element, so the same line of code reaches every slot in the array just by changing i. The loop condition, typically i < a.length, stops the loop exactly after the last index, which avoids running off the end and causing an ArrayIndexOutOfBoundsException.
The counter is not just along for the ride, it IS the index. When i is 0, a[i] is the first element; when i is a.length - 1, a[i] is the last. This double duty is what makes forward traversal work: start i at 0, increment by 1, stop before a.length. Reverse that pattern and you walk backward: start i at a.length - 1, decrement by 1, stop after 0, visiting the same elements in opposite order. Change the step instead of the direction, incrementing i by 2, and you skip every other element, which is useful for sampling or pairing up values.
This simple pattern is the foundation for everything else in the unit. Linear search is a traversal that stops early when it finds a target. Many sorting algorithms traverse the array repeatedly, comparing neighbors. Traversing a 2D array extends this idea with a nested loop, one counter for rows and one for columns. Get comfortable with plain traversal first, since every variant just adjusts the start, stop, or step of the same loop.
Key terms
- Index
- The integer position of an element in an array, starting at 0 and ending at a.length - 1.
- Traversal
- Visiting each element of a data structure once, usually in order, to read or process it.
- Loop counter
- The variable, often i, that tracks progress through a loop and doubles as the array index.
- ArrayIndexOutOfBoundsException
- The runtime error thrown when code accesses an array index outside 0 through a.length - 1.
Watch it explained
- How it worksHow does the loop counter double as the index into the array on every pass?
- Worked exampleTrace a loop that prints every element of {4, 8, 15, 16, 23} beside its index.
- Worked exampleFind what a loop running backwards from a.length - 1 down to 0 prints for that array.
- Going furtherWhat changes when you visit only every other element by stepping i by 2?
Check yourself
End of topic.