zuai-logo

Traversing Arrays

Sophie Anderson

Sophie Anderson

5 min read

Listen to this study note

Study Guide Overview

This guide covers array traversal using primarily for loops. It explains forward, reverse, and limited traversal (different start/end indices and subsections). Examples demonstrate array manipulation during traversal, such as doubling array elements, and briefly touches upon using while loops for traversal. It also mentions ArrayIndexOutOfBoundsException.

What is Traversing?

Traversing an array means to access every value in the array. To do this, we need to use a loop, and we most often use a for loop.

Forward Traversal

To do so, we use the following:

for (int i = 0; i < array.length; i++) {
do something with array[i]
}

Here is an example where we use a constructor to make a copy of arrayOne from the previous section:

int[] arrayTwo = new int[10] {
for (int i = 0; i < array.length; i++) {
arrayTwo[i] = i;
}
}

Using regular for loops, we can either access array elements or manipulate them as above.

Reverse Traversal

Sometimes, we want to go in reverse, from the end of the array to the beginning. This requires a change to the for loop condition to the following:

for (int i = arr...

Question 1 of 10

What does it mean to traverse an array? 🤔

To sort the array in ascending order

To access every value in the array

To change the size of the array

To remove all the elements from the array