Traversing an Array with an Index
The array below holds the posted wait, in minutes, at each of six rides in an amusement park.
int[] waits = {15, 40, 5, 25, 10, 35};
for (int i = 0; i < waits.length; i++)
{
System.out.print(waits[i] + " ");
}The loop prints
15 40 5 25 10 35. Its variable i is an index and never a wait time. It takes the values 0 through 5, and on each pass waits[i] reaches the element at that index.The loop bounds
The condition
i < waits.length ends the loop after index 5, the last valid index. With <= in its place, the loop gets one more pass with i equal to 6, and waits[6] throws an ArrayIndexOutOfBoundsException.Starting
i at 1 makes the opposite mistake. Nothing is thrown, but the 15 at index 0 is never printed.Part of an array
The rides at indexes 2, 3, and 4 make up the park's water section. A traversal of just those starts at 2 and stops before 5.
int waterTotal = 0;
for (int i = 2; i < 5; i++)
{
waterTotal += waits[i];
}
The body adds 5, 25, and 10, so
waterTotal is 40. When the body doesn't change i, the header alone sets which elements are visited.Other directions and steps
An index can count down. Starting at
waits.length - 1 and continuing while i >= 0 visits 35, 10, 25, 5, 40, and 15, in that order. The condition uses >=, since index 0 holds a ride too.An index can also skip. With the update
i += 2 and a start of 0, the loop visits indexes 0, 2, and 4, which hold 15, 5, and 10. Starting at 1 visits the other three.The same traversal with while
Suppose the park caps every posted wait at 30 minutes. This traversal uses a
while loop and changes the array as it goes.int i = 0;
while (i < waits.length)
{
if (waits[i] > 30)
{
waits[i] = 30;
}
i++;
}
A
for header's initialization, condition, and update are all still present. The declaration int i = 0; comes before the loop, the test sits in the parentheses, and i++ closes the body. Afterward waits holds 15, 30, 5, 25, 10, and 30. Without the i++, i would stay 0 and the loop would run forever.