java-foundations 22 min read

The while Loop — Foundations

Repeat the body as long as a condition holds — the shape underneath every loop

Every program you have written so far reads top to bottom. Declare a variable, print a message, read input, compute a value, print an answer, end. That model works as long as you know exactly how many things happen. The moment you need to print the numbers from 1 to 100, or read values until the user types 0, or count grades under 70 in a list whose length changes every term — copy-paste stops working.

A loop says: do this again, and again, until some condition tells me to stop. Java has three loop shapes (while, for, do-while), and they are interchangeable in what they can express. Today we start with while because its shape most directly reflects the idea.

In a nutshell

A while loop checks its condition before each iteration. If the condition is true, the body runs, then the condition is checked again. If the condition is false — including the very first check — the body is skipped and execution continues after the loop.

Every while loop has three parts you can point to: the initialization above the loop that creates the loop variable, the condition in the header, and the update inside the body that moves the variable toward making the condition false. If any of the three is missing or wrong, the loop misbehaves in a specific and predictable way.

The body may run zero times. Students expect a loop to run at least once because the word “loop” sounds round. A while loop does not guarantee that. If the condition is false at entry, the body is skipped entirely.

By the end of this lesson you will be able to trace a while loop on paper, recognize the two most common failure modes (trailing semicolon, missing update), and use a while with a priming read to process user input until a stop value.

Quick reference

Syntax

while (condition) {
    // body — runs while condition is true
}
// execution continues here

Evaluation order

  1. Check the condition.
  2. If true, run the body; if false, skip to after the loop.
  3. Repeat step 1.

The condition is checked before each iteration, including the first. The body may run zero times.

The three parts of every counter while

Part Where it lives What it does
Init above the loop declares and initializes the loop variable
Condition in the while (...) header boolean expression checked before each pass
Update inside the body changes the loop variable so the condition eventually becomes false

If the update is missing, the loop runs forever.


Deep dive

1. A first worked example: count 1 to 5

Plan. Print 1, 2, 3, 4, 5 on separate lines.

  • What varies? A counter i.
  • Start value? 1 (the first number to print).
  • Stop condition? When we pass 5 — so loop while i <= 5.
  • Body? Print i, then increment i.
int i = 1;
while (i <= 5) {
    System.out.println(i);
    i++;            // advance the counter every pass
}

Trace:

Check # i at top Condition Action
1 1 1 <= 5 true print 1; i becomes 2
2 2 2 <= 5 true print 2; i becomes 3
3 3 3 <= 5 true print 3; i becomes 4
4 4 4 <= 5 true print 4; i becomes 5
5 5 5 <= 5 true print 5; i becomes 6
6 6 6 <= 5 false exit

Output:

1
2
3
4
5

2. Tracing by hand — the habit that pays

Thursday’s quiz asks one question about each loop: what exactly does it print? You will not be asked to submit a trace table. You will be asked to produce the exact output of a loop you have never seen before, cold, in 10 minutes.

A trace table is the mechanical technique for getting to that output reliably. It is scratch work — a small grid you fill in on paper while pretending to be the computer, one row per iteration. You do not have to hand it in. You use it so the output you write down is right. Students who try to predict the output by reading the code in their head miss a step; students who write out a trace table catch off-by-one errors before they commit to an answer.

How to build a trace table:

  1. List the loop’s variables as column headers, plus one final column labelled output.
  2. Add one row per time the loop header is checked. Fill in each variable’s current value before the body runs.
  3. If the condition is true, execute the body on paper: update the variables, append any printed text to the output column.
  4. When the condition becomes false, stop. The output column is the output your program will print.

Practice against the clock. The Week 4 quiz-prep set on the practice platform has the same shapes as Thursday’s quiz. Work through a few with a trace table next to you, then a few without one. The goal by Thursday is to build tables quickly enough that the 10-minute budget is never in doubt.

Trace this:

int n = 3;
while (n > 0) {
    System.out.println("T minus " + n);
    n--;
}
System.out.println("launch");
Check # n at top Action
1 3 print T minus 3; n becomes 2
2 2 print T minus 2; n becomes 1
3 1 print T minus 1; n becomes 0
4 0 0 > 0 false; exit

Output:

T minus 3
T minus 2
T minus 1
launch

3. The sentinel-stop shape (body decides when to stop)

Not every loop has a counter that ticks up or down. Sometimes the body itself computes the next value, and whether the loop continues depends on what that computation produced. A classic example is the Collatz step: given n, if n is even replace it with n/2, otherwise replace it with 3n+1. Stop when n reaches 1.

int n = 6;
while (n != 1) {
    if (n % 2 == 0) {
        n = n / 2;
    } else {
        n = 3 * n + 1;
    }
    System.out.print(n + " ");
}
System.out.println();

Trace (start n = 6):

Check # n at top Action
1 6 even; n becomes 3; print 3
2 3 odd; n becomes 10; print 10
3 10 even; n becomes 5; print 5
4 5 odd; n becomes 16; print 16
5 16 even; n becomes 8; print 8
6 8 even; n becomes 4; print 4
7 4 even; n becomes 2; print 2
8 2 even; n becomes 1; print 1
9 1 1 != 1 false; exit

Output: 3 10 5 16 8 4 2 1

You cannot predict the number of iterations from the header alone. The body computes each new n, and whether the loop continues is a property of that new value. This is exactly what while is for.

Check Your Understanding
How many times does the body of this loop run?
int i = 10;
while (i < 5) {
    System.out.println(i);
    i++;
}
A0 times
B1 time
C5 times
Dinfinite times
Answer: A. The condition i < 5 is checked before the body runs. With i = 10, the condition is false on the very first check, so the body is skipped entirely. This is the "body may run zero times" rule.

4. The two most common failure modes

Recognizing common pitfalls up front saves hours of debugging later. Here are the two you are most likely to see in a first while lab:

Failure mode 1 — the trailing semicolon.

int i = 0;
while (i < 5);         // <-- semicolon is the whole body
{
    System.out.println(i);
    i++;
}

The ; after the ) makes the body an empty statement. The block that follows is unrelated to the loop — it’s a standalone block that runs once. But i never changes inside the empty body, so the loop header keeps checking 0 < 5: infinite loop.

How to recognize it: the line while (...); ends in ; when a { should follow. Delete the semicolon.

Failure mode 2 — forgot to update the counter.

int i = 0;
while (i < 5) {
    System.out.println(i);
    // no i++  <-- missing
}

The body prints i, but i never changes. Each iteration the condition is still 0 < 5: infinite loop printing 0 forever.

How to recognize it: the program hangs and the console fills with the same value. Add the update statement.

If your while loop isn’t doing what you want, check in this order:

  1. Is there a ; after while (...)? Delete it.
  2. Does the body change the loop variable? If not, add the update.
  3. Trace by hand for a small input (n = 2 is usually enough). Where does the real trace diverge from the one you imagined?

5. A small synthesis: read until the user says stop

This ties the pieces together with Scanner input.

Plan. Read integers from the user, printing each one, until the user types 0.

Scanner in = new Scanner(System.in);
System.out.print("enter an integer (0 to stop): ");
int x = in.nextInt();                          // priming read
while (x != 0) {
    System.out.println("you typed " + x);
    System.out.print("enter an integer (0 to stop): ");
    x = in.nextInt();                          // re-read at end of body
}
System.out.println("bye");

Notice the priming read — the int x = in.nextInt(); before the loop. Without it, the condition x != 0 has nothing to check on the first pass. The full sentinel pattern, with its subtleties, is Wednesday’s topic (lesson 4-c); the structure is introduced here.

Sanity check: trace this for a user who types 5, then 0.
  • Priming read: x = 5. Condition 5 != 0 is true.
  • Body: prints you typed 5, reads next value: x = 0.
  • Condition: 0 != 0 is false. Exit.
  • Print bye.

Two lines of output: you typed 5 and bye. If your trace says otherwise, re-read the evaluation rule at the top.


Before you leave

A while loop repeats the body while a condition holds — condition first, then body. The body may run zero times. Every counter while has an init above, a condition in the header, and an update inside; miss one and the loop hangs or silently does nothing. Trace by hand for small inputs and the bugs become obvious.

Tomorrow: the for loop, which packages init, condition, and update into one line — the shape to reach for when you know the iteration count up front.

Want to practice? The Week 4 quiz-prep set on the practice platform has while-loop tracing problems in the same shape as Thursday’s quiz — work through a few of these before class.