while Loops

The Course
•
4 min read

A while loop repeats as long as its condition is true. Unlike a for loop, it does not collect initialization and updating in the header. Put the initial state before the loop and make the change that moves it toward stopping visible in the body. A loop whose state never changes can run forever.

Use for when a fixed sequence or count is the clearest plan. Use while when the next step depends on current progress: save until a goal is reached, or process input until it ends. The condition is checked before the body, so a goal already met means zero iterations. Keep those boundary cases in your tests.

State a stopping argument

Before pressing Run, name the value that changes and the direction it moves. For this savings example, a positive addition moves saved upward toward the goal. If the addition were zero or negative, that argument would fail. In an editor, Stop can end a runaway program, but a well-designed loop should also terminate for its intended inputs.

Save until the goal is reached Java
public class Main {
    public static void main(String[] args) {
        int saved = 0;
        int weeks = 0;

        while (saved < 50) {
            saved += 15;
            weeks++;
        }

        System.out.println(saved);
        System.out.println(weeks);
    }
}
Check your prediction
60
4

The saved values are 15, 30, 45 and 60. Reaching at least 50 does not mean landing exactly on 50. Using saved != 50 would never stop for increments of 15.

Bound the amount of work Java
public class Main {
    public static void main(String[] args) {
        int saved = 0;
        int weeks = 0;

        while (saved < 200 && weeks < 3) {
            saved += 15;
            weeks++;
        }

        System.out.println(saved);
        System.out.println(saved >= 200);
    }
}
Check your prediction
45
false

The step limit bounds this attempt but does not prove success. Report the unmet goal honestly. Distinguish a stopping condition from a success condition when there is more than one way to stop.

Stop early or skip a value Java
public class Main {
    public static void main(String[] args) {
        int total = 0;

        for (int value = 1; value <= 5; value++) {
            if (value == 3) {
                continue;
            }

            total += value;
        }

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

continue skips the rest of this iteration; the for-loop update still happens. Replace continue with break: the loop ends entirely and the total becomes 3. In a while loop, a continue can skip your own update, so keep updates visible.

Your turn

Exercise

Reach a study target

Start at 0 completed minutes and add 20 minutes per session until at least 55 minutes are complete. Count sessions. Print 60 and 3. Then try a target of 0 and explain why both results should be 0.

Your workspace Java
public class Main {
    public static void main(String[] args) {
        int completed = 0;
        int sessions = 0;
        int target = 55;
        // Repeat until the target is met.
    }
}
Hint 1: the idea

Keep repeating while the target has not yet been reached. Equality is not guaranteed when you add a fixed amount.

Hint 2: a first step

Update both completed work and the number of sessions inside the loop. The completed update must move toward the target.

Show one solution
public class Main {
    public static void main(String[] args) {
        int completed = 0;
        int sessions = 0;
        int target = 55;

        while (completed < target) {
            completed += 20;
            sessions++;
        }

        System.out.println(completed);
        System.out.println(sessions);
    }
}
60
3

Change it and explain

For targets 1, 20, 21 and 60, predict the session count before running. Add an upper bound of two sessions, then print whether the target was actually reached. Explain which condition stopped the loop for target=55.

If an experiment runs too long, press Stop, inspect the condition and update, and reset if needed. The browser’s safety limit is not a substitute for a termination argument. You should be able to explain why your intended inputs finish without relying on a hidden timeout.

Was this article helpful?

Your response is saved on this device.