Traversing Arrays

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

How are we doing?
Give us your feedback and let us know how we can improve