Concepts / while loop

while loop

A do..while loop tests its continuation condition at the end.

  • Programming
Interactive lab

Try it: while Loops, break and continue

How a while loop re-evaluates its condition before every pass, how break leaves the loop at once, how continue jumps back to the condition, how a sentinel value ends a while True loop, and why a loop whose condition never becomes False runs forever.

How it works

  1. Evaluate the condition. If it is False, skip the body and continue after the loop.
  2. If it is True, run the body from the top, then go back and evaluate the condition again.
  3. continue skips the rest of the body and goes straight back to the condition check.
  4. break leaves the loop immediately; the condition is not checked again (while True loops rely on it, e.g. stopping at a sentinel like 'done').
  5. If nothing in the body can make the condition False, the loop never ends; the lab's guard stops it after N iterations and says so.

Default run (21 steps): Ready: Countdown. A while loop checks its condition before every pass. … Finished after 5 iterations and 6 condition checks.

Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type in the list, one per call (the prompt is not printed), and raises EOFError when they run out, like a closed keyboard stream. The guard is the lab's, not Python's.

Educational simulation

Loading the simulation…

Repetition Controlled by a Condition

Many programs need to do the same work more than once: print a list of values, keep asking for input until it is valid, or keep adding up numbers until a target is reached. A while loop is the control structure that handles this kind of condition-based repetition. Instead of deciding in advance how many times to repeat, the loop asks a question on each pass: should the work continue? As long as the answer stays yes, the repetition continues.

This article follows one idea through several small examples: the repeated statement runs only while a condition remains true, and the position of that condition decides when the check happens. You will trace how a variable changes on each pass, compare a while loop with a do..while loop, and learn to recognize the mistakes that cause loops to behave unexpectedly.

Tracing a Counter Through a Loop

Start with the simplest picture. A while loop has a condition and a statement. The statement is repeated only while the condition is true. The easiest way to see this is to follow a variable step by step. Consider a counter that starts at zero. The loop keeps running while the counter is less than three, and each pass adds one to the counter.

java

Trace it by hand before you run it. Before the first pass, count is 0 and the condition count < 3 is true, so the body runs: it prints 0 and then count becomes 1. Back at the top, the condition is checked again with count equal to 1. It is still true, so the body runs and prints 1. The same pattern repeats with count equal to 2. When count becomes 3, the condition count < 3 is false, and the loop stops without running the body again.

The diagram shows the key pattern. Each pass changes the variable, and the condition is checked against the new value. The loop does not stop because some number of passes has been counted; it stops because the condition has become false. That is why the important question, when a loop behaves unexpectedly, is whether the condition is still true.

What a while Loop Repeats

Definition

A while loop is a control structure for condition-based repetition. Its statement repeats only while the specified condition remains true.

The statement inside a while loop is not repeated forever just because the loop has started. Repetition depends on the condition. The condition is the part that controls whether the statement runs again. The statement is the work being repeated. Keeping these two roles separate is the first step to reading any while loop correctly.

Key point

In the basic while-loop structure, the condition is the test that is evaluated, and the statement is the work that is repeated. A loop with a false condition from the start runs its statement zero times.

Where the do..while Condition Sits

A do..while loop tests its continuation condition at the end. Its shape places the repeated statement first and the condition afterward. Read the statement in this order: enter the do part, perform its statement or statement block, reach the while condition, and use that condition to decide whether the loop continues.

java

Each token in this strip has a job. The do keyword starts the loop. The body, written as one statement or a block of statements, holds the work to repeat. The while keyword introduces the condition, which is a boolean expression in parentheses. The semicolon at the end belongs to the complete statement.

Comparing the Two Condition Positions

A common first impression is that every loop checks its condition before doing any work. That expectation fits a while loop, but it does not describe a do..while loop. The position of the condition is the detail that determines the basic behavior of each loop. In a while loop, the condition is tested at the beginning, so the body may never run. In a do..while loop, the body comes first, so the body runs at least once before the condition is ever checked.

Featurewhile loopdo..while loop
Where the condition is testedAt the beginningAt the end
Order of work on entryCondition first, then bodyBody first, then condition
Body runs at least onceNo, if the condition starts falseYes
Ends the statement with a semicolonNoYes, after the closing parenthesis

Comparing the two loop forms by condition position

Single Statement or Block of Statements

The syntax of a loop body allows either a single statement or a block of statements. A while loop can contain one statement or, commonly, a block of statements. A block is a group of statements wrapped in braces, so every line inside the braces belongs to the loop body and repeats together.

Before
int n = 0;
while (n < 3)
    System.out.println(n);
    n++;

Only the println line is governed by the loop. The line n++ sits after the loop body and runs once, outside the loop.

After
int n = 0;
while (n < 3) {
    System.out.println(n);
    n++;
}

Braces wrap both statements, so the println and the increment both belong to the loop body and repeat together.

Worked Example: Predicting the Stopping Point

Worked example

When does this loop stop?

A variable x starts at 10, and the loop repeats while x is less than 13. Each pass adds 1 to x. How many times does the body run, and what is x when the loop stops?

  1. 1
    Identify the condition

    The loop continues while x < 13 is true. This is the test that controls repetition.

  2. 2
    Check the first pass

    x is 10, so 10 < 13 is true. The body runs and x becomes 11.

  3. 3
    Check the second pass

    x is 11, so 11 < 13 is true. The body runs and x becomes 12.

  4. 4
    Check the third pass

    x is 12, so 12 < 13 is true. The body runs and x becomes 13.

  5. 5
    Check the stopping test

    x is 13, so 13 < 13 is false. The condition has become false, and the loop stops without running the body again.

Result

The body runs 3 times, and x is 13 when the loop stops.

Notice that the answer came from the condition, not from a count you chose in advance. The stopping point is the first moment the condition is false. This method works for any while loop: trace the variable, check the condition on each pass, and stop when it turns false.

Why the Final Semicolon Matters

The closing parenthesis is not the end of a do..while statement. The semicolon comes after it, and that semicolon belongs to the complete statement. Leaving it out is a syntax error. This is easy to miss because the body already uses braces and the condition already has closing parentheses, so the statement looks finished before it actually is.

java

If Java reports a syntax problem at the end of a do..while statement, first check whether the semicolon follows the closing parenthesis. If the unexpected result concerns whether another repetition should occur, look at the boolean expression and its position instead.

Infinite Loops from Conditions That Never Change

If the condition never becomes false, the result is an infinite loop. The loop keeps repeating because the stopping test is never satisfied. A common first impression is that starting a while loop means the statement inside it will run forever. That is not the rule. The statement repeats only while the condition stays true, so the real danger is a condition whose controlling value never changes in the direction needed to make it false.

java

In this version, count is 0 on every pass. The condition count < 3 is therefore always true, and the loop never reaches a stopping point. Compare this with the earlier counter, where count++ changed the value on each pass and eventually made the condition false. The difference is entirely in whether the controlling variable moves toward a false condition.

Predicting a do..while Run

What do you think happens?

Given int n = 5; and the loop do { System.out.println(n); n++; } while (n < 3); how many lines does the program print?

Reveal answer
Answer:

One line, containing 5.

The body of a do..while loop runs before the condition is checked, so the body runs once with n equal to 5. Then n becomes 6, and 6 < 3 is false, so the loop stops. A while loop with the same condition would print nothing, because its condition would be checked first and found false.

EASY

Write a while loop that prints the values 1 through 4, using a variable that starts at 1 and increases by 1 on each pass. Then rewrite it as a do..while loop. Explain in one sentence what changes if the starting value is changed to 10.

Hints
  • Decide which value the condition should compare against to stop after printing 4.
  • Move the condition to the end in the do..while version, but keep the body identical.
  • With a starting value of 10 and a while loop, ask whether the condition is true before the first pass.

Key Takeaways

  • A while loop repeats its statement only while its condition remains true, so the condition, not a fixed count, controls repetition.
  • A do..while loop tests its continuation condition at the end, so its body always runs at least once.
  • The body of either loop can be one statement or a block wrapped in braces, and the do..while statement must end with a semicolon after the closing parenthesis.
  • If the condition never becomes false, the loop is an infinite loop; when a loop behaves unexpectedly, inspect the condition first.