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.
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.
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 = array.length - 1; i >= 0; i--) {
do something with array[i]
}
Different Start Index
Other times we don't want to traverse through all elements in the array, but only starting from the second element to the end. For this we start at index i = 1
and end at i = array.length - 1
. Our for loop would be written as:
for (int i = 1; i < array.length; i++) {
do something with array[i]
}
Different End Index
Perhaps we want to traverse only through the first n elements (assume n is smaller than array.length - 1
). For this, we start at index i = 0
and end at i = n - 1
. Our for loop would be written as:
for (int i = 0; i < n; i++) {
do something with array[i]
}
Subsection
We can combine the two concepts above to traverse through any subsection of this array. For example, if we only want to go from the third to seventh element of array, inclusive, we could start at index i = 2
and end at i = 6
. Our for loop would be written as:
for (int i = 2; i < 7; i++) {
do something with array[i]
}
Using this for loop traversal, we can modify every value in the array. For example, this is a method that doubles every element in the array.
/** Doubles each element of the array
*/
public static void doubleArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] *= 2; // doubles each individual element
}
}
This can be read as "for all indices i between 0
to array.length - 1
, we find the array element at index i and double it."
It is less common, but while loops can also be used to traverse an array. For example, we can rewrite the method above using a while loop:
/** Doubles each element of the array
*/
public static void doubleArray(int[] array) {
int i = 0;
while (i < array.length) {
array[i] *= 2; // doubles each individual element
i++;
}
}
As you can see, the while loop takes more lines to write and it's not as easy to just look at one line and figure out how many times the loop will occur. That's one of the reasons why for loops are more common for array traversals.
When traversing arrays, it's easy to mess up the index by 1. If that happens and you try to access an index that does not exist (for example, index 10
in an array that only has indices 0
to 9
), you'll get an ArrayIndexOutOfBoundsException
.