← Zurück zum Kurs: Java from scratch

Loops: while, do-while and for

Video folgt in Kürze

A loop repeats a block of code while a condition holds. Thanks to loops you can process a thousand numbers with the same three lines you would use for one, ask for a password until it is correct or walk through a whole list. Java offers three main loops: while, do-while and for. All three do the same thing at heart; what changes is how comfortable each one is for the problem at hand.

while and do-while

The while loop evaluates the condition before each round; if it is false from the start, the body never runs. It is used when you do not know how many times you will repeat, for example while the user has not typed quit. The do-while evaluates the condition at the end, so the body runs at least once; it is ideal for menus and for validating input. Beware of the infinite loop: if nothing inside the body changes the condition, the program never ends (in the terminal you stop it with Ctrl+C).

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // while: count down
        int n = 3;
        while (n > 0) {
            System.out.println("n = " + n);
            n--;                      // without this line: infinite loop
        }

        // do-while: runs at least once, ideal to validate input
        Scanner in = new Scanner("-5\n0\n12\n");   // simulated typing
        int age;
        do {
            System.out.print("Age (1-120): ");
            age = in.nextInt();
        } while (age < 1 || age > 120);
        System.out.println("\nAccepted: " + age);

        // Sum numbers until the user enters 0
        Scanner nums = new Scanner("4 9 2 0");
        int sum = 0;
        int value = nums.nextInt();
        while (value != 0) {
            sum += value;
            value = nums.nextInt();
        }
        System.out.println("Sum = " + sum);   // 15
    }
}

The for loop

The for loop gathers in a single line the three parts of a counted loop: initialization, condition and update. for (int i = 0; i < 5; i++) means: start with i at 0, repeat while i is less than 5 and add one at the end of each round. The variable i exists only inside the loop. Since indexes usually start at 0, the normal choice is < and not <= with the length; mixing them up causes the famous off-by-one error. You can also count backwards, by twos or with any step.

java
public class Main {
    public static void main(String[] args) {
        // Counting 1..5
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
        }
        System.out.println();                  // 1 2 3 4 5

        // Backwards by twos
        for (int i = 10; i >= 0; i -= 2) {
            System.out.print(i + " ");
        }
        System.out.println();                  // 10 8 6 4 2 0

        // break leaves the loop, continue skips to the next round
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) continue;          // skip even numbers
            if (i > 7) break;                  // stop after 7
            System.out.print(i + " ");
        }
        System.out.println();                  // 1 3 5 7

        // Nested loops: a small multiplication table
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 4; col++) {
                System.out.print(row * col + "\t");
            }
            System.out.println();
        }
    }
}

Two reserved words control the flow inside a loop: break leaves it completely and continue jumps to the next round without running the rest of the body. Use them in moderation; if a loop has many breaks and continues, it may read better by rewriting the condition. Nested loops (a loop inside another) multiply the work: if the outer one makes 3 rounds and the inner one 4, the inner body runs 12 times.

A trick for debugging loops: before running, trace it on paper. Write down the values of the variables in each round and check that the condition eventually becomes false. If the program hangs, it is almost always because you forgot to update the control variable.

Teste dein Wissen

Frage 1 von 1

How many times does for (int i = 0; i < 4; i++) run?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →