Unit 05 · lesson

Every Loop Needs a Reason to Stop

Consider:

int count = 0;

while (count < 5) {
    IO.println(count);
    count = count + 1;
}

Do not summarize this as "it loops five times." Trace why.

Concept flow

A loop must make measurable progress toward stopping

Iteration is safer to reason about when state transition and termination are explicit.

  1. INITIAL STATEestablish the starting values
    check
  2. CONDITIONdecide whether another iteration is allowed
    run
  3. WORKperform one bounded unit of behavior
    update
  4. STATE CHANGEmove controlling state toward the boundary
    eventually
  5. TERMINATIONthe continuation condition becomes false
initial count: 0
continue while: count < 5
change each pass: +1
terminal boundary: first time count becomes 5

The loop stops because its state moves predictably toward a condition that becomes false.

Remove progress and termination disappears

int count = 0;

while (count < 5) {
    IO.println(count);
}

count never changes. If the condition begins true, it stays true.

An infinite loop is not mysterious here. The state lacks a transition toward the stopping boundary.

A loop invariant

An invariant is a property that remains true at a meaningful point during each iteration.

For a running total:

int total = 0;
int n = 1;

while (n <= 4) {
    total = total + n;
    n = n + 1;
}

One useful invariant is:

At the start of each iteration, total equals the sum of all positive integers already processed.

This kind of statement helps you reason about correctness without running every possible case.

You do not need formal proof notation. You do need to stop treating loop bodies as opaque blocks.

Trace the state

Create a table:

iterationn beforetotal beforetotal aftern after

Fill it before running the code.

Then execute and compare.

Sentinel-controlled loops

Sometimes the number of repetitions is not known in advance. A loop can stop when a sentinel appears.

void main() {
    String command = "status";
    int attempts = 0;

    while (!command.equals("quit") && attempts < 3) {
        IO.println("processing: " + command);
        attempts++;
        command = "quit"; // supplied state change for this example
    }
}

Real interactive programs may read a new command each pass. Notice the second condition: a maximum-attempt boundary can prevent an otherwise uncontrolled interaction from running forever.

Design from the stop condition backward

For each problem, write the stop condition before the loop body.

  1. Print values from 1 through 10.
  2. Count down from 5 through 1.
  3. Add measurements until 8 samples have been processed.
  4. Process commands until the command is quit or 20 commands have been handled.

For each, identify:

  • initial state;
  • continuation condition;
  • required state change;
  • terminal state.

Evidence

Submit one loop with at least four iterations. Include a pre-run state table and a one-paragraph termination argument.

Then break the state change deliberately. Explain why the loop no longer makes progress. Do not actually leave an uncontrolled infinite loop running in a shared browser tab; reason about the state and restore the guard.