Traversing Arrays

Naveen AnamaneniUpdated · 4 min read

Most array work is "do something with every element": add up a bill, find the highest score, count the free seats. Visiting each element in turn is called traversing the array. You have two loops for it, the counting for and the for-each, and each is better at different jobs.

Two Ways to Walk Through

Bill.java▶ Try it
public class Bill {
    public static void main(String[] args) {
        int[] prices = {340, 165, 190, 45};
        int total = 0;
        for (int price : prices) {
            total += price;
        }
        System.out.println("Total: Rs. " + total);
    }
}
Output
Total: Rs. 740

Both add up all four prices. The for-each version has no index to get wrong; the counting version knows where it is in the array.

Finding the Largest, and Where It Is

TopScore.java▶ Try it
public class TopScore {
    public static void main(String[] args) {
        String[] names = {"Navika", "Srihitha", "Advitha"};
        int[] scores = {82, 95, 88};
        int best = 0;
        for (int i = 1; i < scores.length; i++) {
            if (scores[i] > scores[best]) {
                best = i;
            }
        }
        System.out.println("Top: " + names[best] + " with " + scores[best]);
    }
}
Output
Top: Srihitha with 95

How it works

  1. best holds the index of the best score so far, starting with index 0.
  2. The loop starts at 1 and compares each score with the best so far.
  3. Because we keep the index, we can print the matching name from the second array.

This needs a counting for: for-each would give the score, but not its position.

Try it yourself: change it to find the lowest score instead.

Backwards, and Every Other Element

Order.java▶ Try it
public class Order {
    public static void main(String[] args) {
        int[] stops = {1, 2, 3, 4, 5, 6};
        for (int i = stops.length - 1; i >= 0; i--) {
            System.out.print(stops[i] + " ");
        }
        System.out.println();
        for (int i = 0; i < stops.length; i += 2) {
            System.out.print(stops[i] + " ");
        }
        System.out.println();
    }
}
Output
6 5 4 3 2 1
1 3 5

Only a counting loop can start at the end (length - 1) or jump in steps of 2.

Common Mistakes

Starting best at 0 for a "largest value" search when values can be negative. Start from the first element instead, as TopScore does with its index.

Using i <= length. It goes one past the end and throws ArrayIndexOutOfBoundsException.

Changing elements through a for-each variable. It's a copy; the array doesn't change.

Practice

  1. Easy: Count how many marks in {45, 82, 17, 93, 60, 34} are below 35.
  2. Harder: Find the second-highest value in an array in a single loop, keeping two variables: highest and second.

Quick check: Traversing arrays

4 questions
1Which loop do you need to find the position of the largest value?
2Where does a backwards loop start?
3Which loop header visits every other element starting from the first?
4What's the quickest way to print a whole array while testing?

Key Takeaways

Was this tutorial helpful?

Lesson 70 of 482