Skip to content
Study Hall
Lesson 1 of 3Looping
Unit 4 · Lesson 1 of 3

while and do-while

The three parts every loop needs, what happens when one is missing, and the two loops that test their condition at opposite ends of the body.

5 min read11 practice questionsInteractiveAsk AI about this →

Key things to remember

  1. 1Every loop needs three parts: initialize before, a condition to test, and an update inside the body.
  2. 2A while loop tests first, so its body can run zero times.
  3. 3A do-while loop tests last, so its body always runs at least once, and its condition is followed by a semicolon.
  4. 4An infinite loop means the condition never becomes false — the update is almost always missing or wrong.
  5. 5A sentinel loop needs a priming read before the loop and another read at the end of the body.
  6. 6count++ is shorthand for count = count + 1, and total += value is shorthand for total = total + value.

So far every line you have written runs at most once. That is a serious limit: a program that adds up twenty marks would need twenty nearly identical lines, and a program that keeps asking until the user types something valid could not be written at all. A loop solves both. It is a block of code the computer runs over and over while some condition stays true, so one block of code can do a job any number of times — including a number you do not know until the program is already running.

Every loop needs three parts
Initialize: create the variable the condition depends on, before the loop starts. Condition: the boolean test that decides whether to run the body again. Update: change that variable inside the body so the condition eventually becomes false. Miss any one of these and the loop is broken — and the failure looks different for each, so it is worth learning to spot which one is missing.
Every loop needs all three parts. Miss one and it either never runs or never stops.int i = 0;while (i < 5) { System.out.print(i); i++;}1231initialise — once, before2test the condition3body, then updatefalse → outDelete the update and you have an infinite loopint i = 0;while (i < 5) { System.out.print(i);} // i++ is missingi stays 0 for ever, so i < 5is always true. The programprints 0 until you kill it.Ctrl+C is not a fix.The condition is checked before every pass, so a condition that starts false means the body runs zero times.
Fig 1Initialize, test, body, update — and back to the test.

The while loop

A while loop reads almost like English: while this is true, keep doing this. Java checks the condition first, and only then runs the body. If the condition is false the very first time, the body never runs at all — not even once. That is the defining behaviour of while, and it is exactly what you want whenever "zero times" is a legitimate answer.

public class CountUp {
    public static void main(String[] args) {
        int count = 1;                      // 1. initialize
        while (count <= 5) {                // 2. condition
            System.out.println(count);
            count++;                        // 3. update
        }
        System.out.println("Done");
    }
}
Prints 1, 2, 3, 4, 5 on separate lines, then Done.
count before the testcount <= 5Printedcount after count++
1true12
2true23
3true34
4true45
5true56
6falsenothing — the loop ends6
The body ran 5 times, but count finishes at 6. A counter always ends one step past the last value it used.
The infinite loop
Delete the count++ line and the condition count <= 5 is true forever, because nothing ever changes count. The program prints 1 endlessly and never reaches the line after the loop. Nothing crashes — the computer is doing exactly what you asked — so the only clue is output that will not stop. Press Ctrl+C in a terminal, or click the stop button in your editor, to kill it. You cannot fix it from inside the running program.

The do-while loop

int count = 10;
do {
    System.out.println(count);
    count++;
} while (count <= 5);            // semicolon is required here
Prints 10 once. The body runs before the condition is ever tested, so 10 is printed even though 10 is not less than or equal to 5. Note the semicolon after the condition — required for do-while and never for a plain while.
Awhile — test first
  • The condition is checked before the body
  • The body runs zero or more times
  • Use it when there may be nothing to do at all
  • Reading a file that might be empty
  • Repeating while a total stays under a limit
Bdo-while — test last
  • The condition is checked after the body
  • The body runs one or more times
  • Use it when the first pass must happen regardless
  • Showing a menu, then asking whether to show it again
  • Asking for input, then checking whether it was valid

Sentinel and validation loops

Often you do not know how many values the user will enter — that is their choice, not yours. The standard solution is a sentinel: an agreed stop value meaning "I am finished" rather than being real data. It must be a value real data could never take, which is why 0 works for a list of positive prices but would be a terrible sentinel for a list of Ontario winter temperatures. The loop condition tests the value, so the value must already exist before the first test — that first read is called the priming read, and the matching read at the bottom of the body is the update.

import java.util.Scanner;

public class SumUntilZero {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int total = 0;

        System.out.print("Enter a number (0 to stop): ");
        int value = input.nextInt();          // priming read

        while (value != 0) {
            total = total + value;
            System.out.print("Enter a number (0 to stop): ");
            value = input.nextInt();          // update: read the next one
        }

        System.out.println("Total: " + total);
    }
}
The read appears twice on purpose. Reading at the top of the body instead would fold the sentinel itself into the total.
Scanner input = new Scanner(System.in);
int mark;

do {
    System.out.print("Enter a mark from 0 to 100: ");
    mark = input.nextInt();
} while (mark < 0 || mark > 100);

System.out.println("Accepted: " + mark);
A validation loop: it repeats while the value is out of range, so it can only exit with a value in range. Note the or — no number is both below 0 and above 100, so using and here would accept everything.
Loading interactive…
Step through a loop one statement at a time and watch each variable change.

Worked examples

Reveal one step at a time and try to beat it to the next line.

Example 1
Trace this loop by hand. What is the final value of n, and how many times does the body run? int n = 20; int steps = 0; while (n > 1) { n = n / 2; steps++; }
Example 2
This loop never stops. Find the bug and fix it. int total = 0; int i = 1; while (i <= 100) { total += i; }
Example 3
How many times does each of these run? A: int x = 7; while (x < 5) { System.out.println(x); x++; } B: int x = 7; do { System.out.println(x); x++; } while (x < 5);
Example 4
Design a sentinel loop that reads positive prices until the user enters -1, then prints how many items were entered and their total.

Where marks get lost

  • Leaving out the update, so the condition never becomes false — the single most common cause of an infinite loop.
  • Writing a semicolon straight after the condition: while (i < 5); compiles, but the semicolon becomes the entire body, so the loop does nothing forever.
  • Declaring the counter inside the loop body. The condition cannot see it, so the code fails to compile with cannot find symbol rather than looping forever - declare the counter before the loop.
  • Forgetting the priming read in a sentinel loop, so the condition tests a variable that has no value yet and the program will not compile.
  • Reading the next value at the top of the body instead of the bottom, which adds the sentinel itself to the total before the loop notices it.

Flashcards 10

What three parts does every loop need?
Minimum number of times a while body runs
Minimum number of times a do-while body runs
What is an infinite loop?
+ 6 more

Practice

1
A loop prints the same value forever. Which part is most likely missing?
2
How many times does the body run? int i = 1; while (i <= 10) { System.out.println(i); i += 3; }
3
In that same loop, what is the value of i immediately after the loop ends?
4
What does this print? int x = 100; do { System.out.println(x); x++; } while (x < 5);
5
Trace and give the final value of steps: int n = 20; int steps = 0; while (n > 1) { n = n / 2; steps++; }
6
What name is given to the agreed value a user types to signal that they have finished entering data?
7
Why does while (count < 5); followed by an indented block of statements fail?
8
Which loop should you choose to keep re-asking for a password until it is at least 8 characters long?
9
Put the parts of a correct sentinel-controlled input loop in order.
  1. 1Prompt and read the next value at the end of the body
  2. 2Update the accumulator with the current value
  3. 3Report the result after the loop finishes
  4. 4Initialize the accumulator before the loop
  5. 5Prompt and read the first value (the priming read)
  6. 6Test the value against the sentinel in the loop condition
10
Match each piece of int i = 0; while (i < 8) { total += i; i++; } to its role.
int i = 0
i < 8
total += i
i++
11
A program reads prices until the user types -1, but the reported total is 1 lower than expected. What is the likely cause?

Spot a mistake on this page? Let us know