Skip to content
Theory · Loops · lesson 3 of 8

The for loop

In the last lesson's while loop, the lap number lived in three different places. The variable was declared before the loop, checked in the condition and changed at the end of the body. Get one of the three wrong, and the loop either never starts or never ends.

The runner has the same three jobs. Before the start, they set the board to 1 once. Before each lap, they look at the board. After each lap, they add one to the number.

The for loop gathers all three jobs into one line. Here is a program that adds up the numbers from 1 to 100:

JAVA
public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            sum += i;
        }
        System.out.println(sum); // 5050
    }
}

Let's go through it line by line:

  1. int sum = 0; sets up the sum.
  2. for (int i = 1; i <= 100; i++) repeats the body for i from 1 to 100.
  3. sum += i; adds the current i to the sum. For an int it does the same as sum = sum + i, only shorter.
  4. System.out.println(sum) runs after the loop and prints 5050.

The three parts of the header

The line for (int i = 1; i <= 100; i++) is called the loop header. Its parentheses hold three parts separated by semicolons:

  • int i = 1 is the initialization: it runs once, before the first iteration. The runner sets the board to 1.
  • i <= 100 is the condition: it is checked before every iteration, as in while. The runner looks at the board.
  • i++ is the update: it runs after the body, before the next check. The runner adds one to the number.

The header reads left to right, but it runs in a different order:

  1. The initialization, once.
  2. The condition. If it is false, the loop ends.
  3. The body.
  4. The update, and back to item 2.

The update is written in the header before the body, but it runs after it. Interviewers like to ask about exactly this order. The widget shows the same loop, only up to 3: press "Next step" and watch which part of the header runs right now.

LiveThe order of the for partsstep 1 of 13 · frames: 1

int sum = 0 sets up the sum.

Watch which part of the header runs at each step

By the time the widget reaches println, the variable i no longer exists. It was declared right in the header, and it lives only inside the loop.

This is where the stadium picture parts ways with Java. The board at the stadium stays there after the race, but the variable from a for header does not exist after the loop.

Other header forms

The update does not have to add one. -- subtracts one, and += adds any number:

  • for (int i = 0; i < 5; i++): five iterations, i from 0 to 4;
  • for (int i = 3; i >= 1; i--): a countdown, 3, 2, 1;
  • for (int i = 0; i <= 10; i += 2): the even numbers from 0 to 10.

i++ and ++i

The ++ operator adds one to a variable. It is called the increment, and it has two forms. As a statement on its own, as in the loop update, they work the same. The difference shows when the value of ++ goes on somewhere: into printing, into an assignment, into another expression.

JAVA
int n = 3;
System.out.println(n++); // 3
System.out.println(n);   // 4
System.out.println(++n); // 5
System.out.println(n);   // 5

The postfix form n++

++ stands after the name. The expression n++ gives the old value of the variable and adds one only afterwards. That is why the first line prints 3, although after it n equals 4: the second line shows that.

The prefix form ++n

++ stands before the name. The expression ++n adds one first and then gives the new value. The third line raises n from 4 to 5 and prints 5.

The order of writing helps you remember: whatever comes first happens first. In n++ the name comes first, so the value is taken first. In ++n the ++ comes first, so one is added first. -- works the same way: n-- gives the old value, --n the new one.

Interviewers often check this difference: they show a short program with i++ and ++i and ask what it prints. In your own code, to stay out of trouble, write ++ as a statement on its own, not inside another expression.

Common mistake

The value of i is needed after the loop:

JAVA
for (int i = 1; i <= 3; i++) {
    System.out.print(i + " ");
}
System.out.println(i); // ✗
TEXT
error: cannot find symbol

The compiler does not know the name i on the last line: the variable from the header is gone together with the loop. The message is the same as for a variable you forgot to declare. If you need a value after the loop, keep it in a variable declared before the loop, like sum in the first example.

Key points

  • The for initialization runs once, the condition before each iteration, the update after the body.
  • n++ gives the old value and then adds one, while ++n adds one and gives the new value.
  • As statements on their own, i++ and ++i work the same.
  • A variable declared in a for header exists only inside the loop.