Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 201 ยท Control Flow

while and do-while Loops

Repeat code in Java with while and do-while loops - counters, sentinel values, input loops, infinite loops with break, and the bugs that make loops never stop.

A loop repeats a block of code. Without loops, printing the numbers from 1 to 1,000 would take 1,000 lines; with one, it takes three. Loops are how programs process every line of a file, keep a game running until the player quits, or retry an operation until it succeeds.

Java has three loop statements. This lesson covers the two condition-controlled ones: while, which checks its condition before each pass, and do-while, which checks it after. They are the natural choice when you don't know in advance how many times the loop will run. The counting loop, for, is the next lesson.

The while loop

Java
while (condition) {
    // body: runs again and again while condition is true
}

Java checks the condition. If it's true, it runs the body, then goes back and checks the condition again. As soon as the condition is false, the loop ends and the program continues after the closing brace. Each pass through the body is called an iteration.

Java Counting with while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Every working loop has those three ingredients: a start state, a condition that eventually becomes false, and an update inside the body that moves toward that point. After the loop, count is 6: the value that made the condition false.

If the condition is false from the start, the body never runs at all. A while loop runs zero or more times.

Loops where you don't know the count

while shines when the number of iterations depends on the data. Here the loop keeps dividing until no digits are left, so a 3-digit number takes 3 iterations and a 10-digit number takes 10:

Java Digits of a number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the output for 0: zero digits, because 0 > 0 is false and the body never runs. That's an edge case, an input at the boundary of what the code expects. Testing your loops with 0, 1 and empty input catches many bugs; here, a do-while loop (below) is the natural fix.

Another classic is the Collatz sequence: halve even numbers, turn odd numbers into 3n + 1, and repeat until you reach 1. Nobody has proved it always reaches 1, but it does for every number ever tried:

Java Collatz steps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The do-while loop

do-while puts the condition at the end, so the body always runs at least once:

Java
do {
    // body
} while (condition);   // note the semicolon

That fits any situation where you must do something before you can decide whether to repeat it. The best-known case is input validation: you have to read a value before you can check it.

Java Validating input with do-while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The example echoes each line it reads so you can see the input in the output. text.matches("\\d+") checks that the text consists only of digits (see Regular Expressions), and the && short-circuit means parseInt only runs on text that passed that check.

A do-while scope trap

A variable declared inside the body isn't visible in the while (...) condition, because the condition is outside the braces:

Java
do {
    String answer = IO.readln("Again? ");
} while (answer.equals("y"));   // error: cannot find symbol: answer

Declare the variable before the loop, as the rating example does with valid.

while or do-while?

while do-while
Condition checked Before each iteration After each iteration
Minimum runs 0 1
Typical use Processing data that may be empty Menus, prompts, validation, "try at least once"

In practice while is far more common. Use do-while when "at least once" is genuinely part of the logic.

Sentinel loops

A sentinel is a special value that means "stop", such as 0, -1, an empty line or the word quit. The loop reads values and processes them until it sees the sentinel, which itself is not processed.

Java Summing until a sentinel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the shape: one read before the loop and one at the end of the body. This "priming read" makes sure the sentinel is tested before it's ever added to the total. It's also why the average check matters: if the very first value is 0, count stays 0, and dividing by it would give NaN.

Reading until the input ends

Sometimes there's no sentinel; you just process every line until the input runs out. IO.readln() returns null at the end of input, which gives a compact loop that reads and tests in one condition:

Java Reading every line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The parentheses around (line = IO.readln()) matter: the assignment happens first, and then its value is compared with null. continue jumps straight to the next check of the condition; break, continue and Labels covers it properly.

With a Scanner (from Reading User Input), the same idea uses its hasNext methods:

Java
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {        // stops at end of input or at the first non-number
    int value = in.nextInt();
    // ...
}

Infinite loops

A loop whose condition never becomes false runs forever. Sometimes that's a bug; sometimes it's deliberate.

Accidental infinite loops

The usual causes are a missing update, an update in the wrong direction, or a condition that can "jump over" its target:

Java
int i = 0;
while (i < 10) {
    IO.println(i);
    // forgot i++  -> prints 0 forever
}

int j = 1;
while (j != 10) {
    j += 2;          // 1, 3, 5, 7, 9, 11, ... never exactly 10
}

Floating-point numbers are a particularly sneaky version, because values like 0.1 can't be stored exactly. This example has a safety limit so it stops:

Java A loop that skips its target

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After ten additions x is 0.9999999999999999, not 1.0, so x != 1.0 stays true and the loop shoots past. Prefer < or <= over != in loop conditions, and use an integer counter when you can (see Working with Numbers).

If one of your programs here runs forever, press Stop or wait for the time limit; on your own machine, press Ctrl + C in the terminal.

Deliberate infinite loops

Servers, games and menus often loop "forever" and leave from the middle with break when something happens:

Java A menu with while (true)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler understands while (true). If such a loop has no break, any statement after it is reported as an unreachable statement compile error, because it could never run. In the same way, while (false) { ... } is a compile error, since its body is unreachable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many times does this print "hi"? int n = 10; while (n < 5) { IO.println("hi"); n++; }

    The condition 10 < 5 is false at the first check, so the body of a while loop never runs.
  2. 2. How many times does this print "hi"? int n = 10; do { IO.println("hi"); n++; } while (n < 5);

    A do-while loop runs its body before checking the condition, so it always runs at least once. Then 11 < 5 is false and it stops.
  3. 3. What is the value of i after this loop? int i = 0; while (i < 3) { i++; }

    The loop runs for i = 0, 1 and 2. After the third increment i is 3, the condition 3 < 3 is false, and the loop ends.
  4. 4. Why does while (x != 1.0) { x += 0.1; } starting from 0.0 never stop?

    After ten additions x is 0.9999999999999999, then about 1.1. It never equals 1.0 exactly. Use < or an integer counter instead.
  5. 5. In a sentinel loop that reads prices until 0, why read the first value before the loop?

    The priming read lets the condition check each value before the body adds it, so the sentinel 0 ends the loop without being counted.

Summary

  • while (condition) { ... } checks before each iteration and may run zero times; do { ... } while (condition); checks afterward and always runs at least once.
  • Every loop needs a start state, a condition that eventually turns false, and an update that moves toward it.
  • Use do-while for "do it, then decide": prompts, menus and input validation. Variables declared in its body aren't visible in its condition.
  • Sentinel loops read a first value before the loop and the next one at the end of the body; while ((line = IO.readln()) != null) reads until the input ends.
  • Avoid != with floating-point loop conditions; deliberate while (true) loops leave with break.

Next: for Loops, where you'll write counting loops compactly and walk through arrays and collections with for-each.