Skip to content

for Loops

The Course
•
20 min study

A loop repeats a block. A for loop puts three pieces on one line: initialize a counter, test whether another iteration should happen, and update the counter after the body. In for (int day = 1; day <= 3; day++), day starts at 1, the body runs while day is at most 3, and day++ increases it by one afterward.

Trace the condition before each iteration, including the final false check. The counter reaching 4 is what stops this loop; the body does not run with day=4. Choose meaningful starting and stopping values instead of changing < to <= until the example happens to print the desired answer.

Keep a running total outside the loop

An accumulator stores a result built across iterations. Initialize it before the loop, update it inside the body and report it afterward. A variable declared inside the body is created again on each iteration. Putting a total there would forget earlier work. Keep the current day's amount separate from the accumulated amount so you can explain both.

Three days, including the endpoint Java
public class Main {
    public static void main(String[] args) {
        for (int day = 1; day <= 3; day++) {
            System.out.println("Day " + day);
        }
    }
}
Check your prediction
Text
Day 1
Day 2
Day 3

List day before and after each update. The increment is not a print; no Day 4 line appears. Change the condition to day < 3 and explain which boundary value is lost.

Accumulate rather than overwrite Java
public class Main {
    public static void main(String[] args) {
        int total = 0;

        for (int day = 1; day <= 3; day++) {
            int minutes = day * 10;
            total = total + minutes;
        }

        System.out.println(total);
    }
}
Check your prediction
Text
60

The amounts are 10, 20 and 30; the cumulative values are 10, 30 and 60. Assigning total=minutes would keep only 30. Resetting total inside the loop would have the same losing-history problem.

A loop can run zero times Java
public class Main {
    public static void main(String[] args) {
        int count = 0;

        for (int index = 0; index < 0; index++) {
            count++;
        }

        System.out.println(count);
    }
}
Check your prediction
Text
0

The condition is checked before the first body execution. A zero-iteration loop is a normal case, not an error. Later, this behavior will make empty arrays and lists easy to handle.

For the int counters and totals here, count++ means increase count by one, and total += value is a shorter way to write total = total + value. Both update an existing variable. You can use the longer assignment until the shorter form feels familiar; trace the same old and new values either way. Similarly, total -= value means total = total - value. The pricing checkpoint will use that subtraction form.

Write the missing final row in your trace

Trace for (int day = 1; day <= 3; day++) adding day * 10 to total:

dayday <= 3?body addstotal after
1true1010
2true2030
3true3060
4false(stop)60

The last row prints nothing but explains why the body ran exactly three times. With an upper bound of 0, the very first test is false and total stays 0. No special code is needed for that case.

Debug a plausible mistake

A trace table separates a traversal defect from an accumulation defect. Here the counter visits 1, 2 and 3; the lost history is in the assignment to total. Rewriting the loop boundary would solve the wrong problem.

Exercise

Repair the running total

The program visits all three values correctly but must print 60 rather than the final day's amount. Keep total outside the loop. Predict what the current program actually prints before changing it. Make the smallest repair, then change the bound to 1 (expect 10) and 0 (expect 0). The supplied version compiles; its behavior is the problem.

Debugging workspace Java
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int day = 1; day <= 3; day++) {
            int minutes = day * 10;
            total = minutes;
        }
        System.out.println(total);
    }
}
Hint 1: the idea

Each update must include the accumulated result from previous iterations.

Hint 2: a first step

Write the old total and the incoming minutes on the right side of the assignment.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        int total = 0;
        for (int day = 1; day <= 3; day++) {
            int minutes = day * 10;
            total = total + minutes;
        }
        System.out.println(total);
    }
}

Expected output after repair:

Text
60

The bug was total = minutes;, which replaced the total on every pass, so only the last day's 30 survived. total = total + minutes; keeps the earlier days. A one-day loop prints 10 either way, which is why that input alone could not find this bug; three days can.

Your turn

Exercise

Count and total even numbers

Visit the integers 1 through 6 inclusive. Count the even values and add them to a total. Print 3 and 12. Use % 2 to ask whether a value is even. Keep the count and total outside the loop.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        int total = 0;
        // Visit each value and update only for even values.
    }
}
Hint 1: the idea

A count answers how many; a total answers how much. They need different updates.

Hint 2: a first step

Make the loop visit every integer first. Inside it, put both updates in the branch that selects even values. += adds to the existing value.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        int total = 0;

        for (int value = 1; value <= 6; value++) {
            if (value % 2 == 0) {
                count++;
                total += value;
            }
        }

        System.out.println(count);
        System.out.println(total);
    }
}
Text
3
12

Both updates sit inside if (value % 2 == 0), so odd values change nothing. count++ adds one per even value; total += value adds the value itself.

Change it and explain

Change the upper bound to 1, 2 and 7 and predict both answers. If a loop ran 100 times, would your count always be 100? Explain which condition decides that. Try printing current value, count and total inside the body to inspect a trace, then remove the extra debugging output from the final report.

Avoid incrementing the loop variable both in the header and inside the body. It skips values and makes the number of iterations harder to reason about. Declare it in the header when it is only needed for this loop.

Was this article helpful?

Your response is saved on this device.