The while Loop

Repeating things

A loop runs the same code again and again. A while loop keeps going while its condition is true:

public class Main {
    public static void main(String[] args) {
        int count = 1;
        while (count <= 5) {
            System.out.println("Count: " + count);
            count++;
        }
        System.out.println("Done!");
    }
}

Output

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done!

Think of it like this: “While the plate is not empty, take another bite.” Each bite, you check the plate again. When it's empty, you stop.

Step by step: check count <= 5 → print → add 1 → check again... When count becomes 6, the condition is false and the loop ends.

Adding things up

public class Main {
    public static void main(String[] args) {
        int total = 0;
        int n = 1;
        while (n <= 100) {
            total += n;
            n++;
        }
        System.out.println("1 + 2 + ... + 100 = " + total);
    }
}

Output

1 + 2 + ... + 100 = 5050

Looping until the user says stop

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int sum = 0;
        int number = sc.nextInt();
        while (number != 0) {
            sum += number;
            number = sc.nextInt();
        }
        System.out.println("Sum: " + sum);
    }
}

Input (what the user types)

4
10
6
0

Output

Sum: 20

The 0 works as a stop signal (a sentinel).

Common mistake: If the condition never becomes false, the loop runs forever – an infinite loop. Forgetting count++ in the first example would do exactly that.

HOME LABS COMMUNITY DASHBOARD