Skip to content

Array Loops

The Course
•
20 min study

Arrays let a loop visit real data rather than values calculated from the loop counter. An indexed loop starts at 0 and continues while index < length. Use the index to read or update each element. The condition excludes length itself, which prevents the out-of-bounds mistake from the previous lesson.

An enhanced for loop, for (int value : values), visits each int in order without exposing its position. Read the colon as "in". Prefer this form when you need values but not indexes. Use an indexed loop when you must replace elements or report their positions. Both forms handle an empty array by running zero times.

Reuse the accumulator pattern

The pattern from Day 2 still works: initialize before the loop, update inside, return or report after it. To count matching values, add one when the condition holds. To total matching values, add the value instead. Keeping those operations separate avoids a common confusion between "how many sessions" and "how much time".

State what happens on empty input. A total naturally starts at zero, so an empty sum is zero. An average needs a separate rule because division by zero is not a meaningful empty average. Do not invent an element at index 0 to initialize a sum; zero is already a useful neutral starting value.

Read every value safely Java
public class Main {
    public static void main(String[] args) {
        int[] minutes = {10, 25, 40};

        for (int index = 0; index < minutes.length; index++) {
            System.out.println(index + ": " + minutes[index]);
        }
    }
}
Check your prediction
Text
0: 10
1: 25
2: 40

There are three body executions. The final condition checks index=3 and stops. If you use <=, the first three lines print before the fourth access fails; partial output does not mean the program completed successfully.

A reusable total handles empty input Java
public class Main {
    public static void main(String[] args) {
        System.out.println(total(new int[] {10, 25, 40}));
        System.out.println(total(new int[] {}));
    }

    static int total(int[] values) {
        int sum = 0;

        for (int value : values) {
            sum += value;
        }

        return sum;
    }
}
Check your prediction
Text
75
0

Inside a method call, new int[] supplies an array expression. The helper reads it without needing separate variables for every input. It does not change the supplied array.

Count and total the selected values Java
public class Main {
    public static void main(String[] args) {
        int[] minutes = {10, 25, 40};
        int count = 0;
        int selectedTotal = 0;

        for (int value : minutes) {
            if (value >= 25) {
                count++;
                selectedTotal += value;
            }
        }

        System.out.println(count);
        System.out.println(selectedTotal);
    }
}
Check your prediction
Text
2
65

The condition selects two values, but their total is 65, not 2. Trace both columns for the same input. Changing >= to > removes the boundary value 25 from both results.

Choose a loop by the information you need

An enhanced for loop gives you each value in order. An indexed loop gives you a position that can also be used to replace an element or connect related data. If you only total values, the enhanced loop has fewer moving parts. If you need to print position numbers, an index is useful.

Trace total on {10, 25, 40}:

valuesum beforesum after
10010
251035
403575

On an empty array there are no rows, and the starting 0 is the answer. A return inside the loop would stop after the first row.

Changing a local loop variable does not replace an array element. To update the array itself, use values[index] = ... deliberately. Today's total method promises not to change input, so no such assignment belongs in its implementation.

Debug a plausible mistake

A correct first iteration can conceal an early return. A method return ends the complete call, not only the current loop iteration. Use a two-element or longer input to distinguish a first-element implementation from a real total.

Exercise

Repair the array total

total must include every array element without changing the input. The supplied array must total 75. Predict what the current program actually prints before changing it. Make the smallest repair, then also call total on an empty array (expect 0) and on {7} (expect 7). The supplied version compiles; its behavior is the problem.

Debugging workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println(total(new int[] {10, 25, 40}));
    }

    static int total(int[] values) {
        int total = 0;
        for (int value : values) {
            total += value;
            return total;
        }
        return total;
    }
}
Hint 1: the idea

The result is complete only after every contribution has been considered.

Hint 2: a first step

Keep the accumulator update inside the loop and put the successful return after it.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(total(new int[] {10, 25, 40}));
    }

    static int total(int[] values) {
        int total = 0;
        for (int value : values) {
            total += value;
        }
        return total;
    }
}

Expected output after repair:

Text
75

The bug was the return total; inside the loop: it ended the whole method after the first element, so the program printed 10. With the return moved after the loop, every element is added first. {7} gives 7 with either version, which is why a one-element test could never have found this bug.

Your turn

Exercise

Find the longest session

Implement largest(int[] values), which returns the biggest value in the array. Contract: the array has at least one element (an empty array has no largest value, so it is outside this exercise). Do not change the input. The editor checks {10, 25, 40} → 40, {40, 10} → 40, {7} → 7 and {-5, -2} → -2. Its normal main prints 40.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println(largest(new int[] {10, 25, 40}));
    }

    static int largest(int[] values) {
        return 0; // Replace the placeholder.
    }
}
Hint 1: the idea

Keep a "best so far" value and compare every element with it. Unlike a total, 0 is not a safe starting value: think about the {-5, -2} case.

Hint 2: a first step

Start with int best = values[0];, which is allowed because the contract promises at least one element. Then loop over the values and replace best when the current value is bigger.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(largest(new int[] {10, 25, 40}));
    }

    static int largest(int[] values) {
        int best = values[0];

        for (int value : values) {
            if (value > best) {
                best = value;
            }
        }

        return best;
    }
}
Text
40

The deciding line is int best = values[0];. Starting at 0 would pass the first three cases but return 0 for {-5, -2}, a value that is not even in the array. Starting from a real element is safe only because the contract rules out an empty array.

Change it and explain

Write largestIndex, an indexed version that returns the position of the largest value instead of the value, and compare it with the enhanced-for version. Then implement a countAtLeast method with both an array and a threshold parameter. For {10,25,40} and 25 it should return 2; for an empty array it should return 0. Explain why countAtLeast can start at 0 but largest cannot.

Explain why assigning a different number to the enhanced-for variable does not replace an array element. That variable holds the current int value. If you want to update the stored elements, use values[index] in an indexed loop deliberately.

Was this article helpful?

Your response is saved on this device.