Sub topic 4
Traversing Arrays
Traversing an array means visiting its elements, usually from the first to the last. An array is a fixed-size sequence of values. Each value is called an element.
Traversal lets you print values, add them, check them, or change them. In Java, two common ways to traverse an array are an indexed for loop and an enhanced for loop.
This chapter assumes you have seen how to create an array and access an element. We will use an array of int values, or whole numbers.
Traversing with an index
An index is the position of an element in an array. Java starts counting positions at 0. For an array of three elements, the indexes are 0, 1, and 2.
A loop repeats instructions. An indexed for loop uses a variable to keep track of the current index.
Save this program as ScoresWalk.java, compile it with javac ScoresWalk.java, and run it with java ScoresWalk:
public class ScoresWalk {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
for (int i = 0; i < scores.length; i++) {
System.out.println(i + ": " + scores[i]);
}
}
}The program prints three lines: 0: 80, 1: 90, and 2: 100.
The loop has three parts inside its parentheses:
int i = 0creates the index variable and starts it at0.i < scores.lengthis the condition. A condition is a test that is either true or false. The loop continues while this test is true.i++adds1toiafter each pass through the loop.
scores.length gives the number of elements in the array. Inside the loop, scores[i] gets the element at the current index. One pass through the loop is called an iteration.
| Iteration | Index `i` | Test `i < scores.length` | Element |
|---|---|---|---|
| First | 0 | `0 < 3` is true | `scores[0]` is 80 |
| Second | 1 | `1 < 3` is true | `scores[1]` is 90 |
| Third | 2 | `2 < 3` is true | `scores[2]` is 100 |
| After the third | 3 | `3 < 3` is false | None; the loop stops |
The last valid index is always one less than the length. Using i < scores.length makes the loop stop before it tries to access index 3.
Why the bounds matter
An array’s bounds are the range of indexes it allows. Trying to use an index outside that range causes an ArrayIndexOutOfBoundsException. This error stops the program unless it is handled.
A common mistake is to use i <= scores.length. For an array of length 3, that test lets i reach 3, but scores[3] does not exist.
An empty array has length 0 and no valid indexes. The usual loop test still works: 0 < 0 is false, so the loop body never runs.
Traversing with an enhanced for loop
Sometimes you need each value but do not need its index. An enhanced for loop, also called a for-each loop, is useful for that case.
The next program adds the scores and counts those that are at least 90. Save it as ScoreSummary.java:
public class ScoreSummary {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
int total = 0;
int highScores = 0;
for (int score : scores) {
total += score;
if (score >= 90) {
highScores++;
}
}
System.out.println("Total: " + total);
System.out.println("Scores at least 90: " + highScores);
}
}Run it with javac ScoreSummary.java and then java ScoreSummary. It prints Total: 270 and Scores at least 90: 2.
Read int score : scores as “for each int value called score in scores.” On each iteration, score receives the next element’s value, starting with the first element.
The loop body uses two variables to keep results:
total += scoreadds the current score to the running total.highScores++adds1to the count when the conditionscore >= 90is true.
The if statement checks every score. The body inside the if runs only for 90 and 100.
If scores were empty, the loop would run zero times. Both result variables would stay at 0.
Choosing a loop
Both loop forms visit every element in order when written as shown above. Choose based on what the task needs.
| Task | Useful loop | Why |
|---|---|---|
| Print or total every value | Enhanced `for` | You can use each value directly. |
| Print each value’s position | Indexed `for` | You have the index in `i`. |
| Replace an element | Indexed `for` | You can assign a value to `scores[i]`. |
| Visit elements in reverse order | Indexed `for` | You control where the index starts and how it changes. |
An enhanced for loop does not provide an index. If you need the position, an indexed loop is usually clearer than maintaining a separate counter.
Changing array elements
For an int array, the enhanced loop variable receives a copy of each value. Changing that variable does not change the array element.
To replace an element, assign a new value through its index. Save this program as UpdateScores.java:
public class UpdateScores {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
for (int score : scores) {
score += 5;
}
System.out.println("First score is still " + scores[0]);
for (int i = 0; i < scores.length; i++) {
scores[i] += 5;
}
for (int score : scores) {
System.out.println(score);
}
}
}Run it with javac UpdateScores.java and java UpdateScores. The first line says First score is still 80. The remaining lines show 85, 95, and 105.
In the first loop, score += 5 changes only the loop variable. In the second loop, scores[i] += 5 changes the element at index i. The final enhanced loop reads the updated values.
Changing the order or stopping early
An indexed loop gives you control over which indexes to visit. To visit every element from last to first, start at length - 1 and subtract 1 after each iteration.
A loop can also stop as soon as it finds a value. The break statement exits the loop immediately.
Save this program as ReverseAndFind.java:
public class ReverseAndFind {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
for (int i = scores.length - 1; i >= 0; i--) {
System.out.println(scores[i]);
}
int foundIndex = -1;
for (int i = 0; i < scores.length; i++) {
if (scores[i] == 90) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
System.out.println("Found at index " + foundIndex);
} else {
System.out.println("Not found");
}
}
}Run it with javac ReverseAndFind.java and java ReverseAndFind. The first loop prints 100, 90, and 80. The second loop prints Found at index 1.
In the reverse loop, i-- subtracts 1 from the index. The test i >= 0 includes index 0 and stops before index -1. For an empty array, length - 1 is -1, so the test is false from the start.
In the search loop, == checks whether the current score equals 90. foundIndex starts at -1, which is not a valid index. If the loop finds the score, it records the index and stops. If it does not find the score, foundIndex remains -1.
Check your loop
When a traversal does not behave as expected, check these points:
- Does the index start at the position you intend? Starting at
1skips the first element. - Does the condition stop at the right point? For a forward loop, use
i < array.lengthto avoid going past the end. - Does the index change in the right direction? A reverse loop needs
i--, noti++. - Do you need the index? Use an indexed loop when you need to identify or replace a position.
- Are you changing an array element or only an
intloop variable? Usearray[i]to replace an element.
Exercises
Exercise
For int[] scores = {80, 90, 100}, which values does for (int i = 1; i < scores.length; i++) visit?
Show answer
It visits 90 and 100. Starting at index 1 skips the value 80 at index 0.
Exercise
Write a loop that adds 2 to every element of an int[] named values.
Show answer
for (int i = 0; i < values.length; i++) { values[i] += 2; }
Exercise
An empty array is traversed with for (int i = 0; i < values.length; i++). How many times does the loop body run?
Show answer
Zero times. The first test is 0 < 0, which is false.