Part I — Foundations · Chapter 3 · Lesson 2 of 5 · 8 min read
Lesson 2: while Loops and Loop Invariants
Lesson level: Foundation
Purpose: Repeat controlled work safely by reasoning about loop state, progress, invariants, and termination.
Learning objectives
By the end of this lesson, you should be able to:
- explain how a while loop evaluates its condition;
- identify loop initialization, condition, body, and update;
- trace state across iterations;
- state and verify a loop invariant;
- prove that a loop makes progress toward termination;
- prevent off-by-one and infinite-loop defects;
- use bounds and validation defensively; and
- choose a while loop only when its control logic is explicit.
2.1 Why loops exist
A loop repeats a block while a condition remains true-like. Repetition is useful when the number of required steps depends on changing state rather than a fixed sequence written directly in source.
Examples include retrying a bounded operation, reducing a balance in installments, scanning until a sentinel value appears, or improving an estimate until it meets a tolerance.
2.2 Basic while syntax
let count = 1
while count <= 3 {
print "Count: {count}"
count += 1
}
The loop condition is checked before every iteration. If it is true-like, the body runs. After the body finishes, control returns to the condition. When the condition becomes false-like, execution continues after the loop.
2.3 The four parts of a controlled loop
- Initialization: create the state used by the condition.
- Condition: decide whether another iteration is allowed.
- Body: perform one unit of work.
- Update: change state so the loop approaches termination.
In the counting example, initialization sets count to 1, the condition permits values through 3, the body prints one value, and the update increments count.
2.4 Pre-test behavior
A while loop may execute zero times because its condition is tested before the first body execution.
let remaining = 0
while remaining > 0 {
print remaining
remaining -= 1
}
The initial condition is false, so the body is skipped. Design any required one-time work outside the loop rather than assuming the body runs once.
2.5 Trace each iteration
Trace state at the condition, during the body, and after the update. For the counting loop:
| Check | count before body | Output | count after update |
|---|---|---|---|
| 1 | 1 | Count: 1 | 2 |
| 2 | 2 | Count: 2 | 3 |
| 3 | 3 | Count: 3 | 4 |
| 4 | 4 | Body skipped | 4 |
The final failed check is part of the execution model. It explains why the loop stops and helps reveal boundary mistakes.
2.6 Loop invariants
A loop invariant is a statement that is true before the first iteration and remains true after every completed iteration. It describes the relationship between the current state and the work already completed.
For the counting loop, one invariant is: before each condition check, count equals one more than the number of values already printed.
An invariant is not merely an observation. Use it to reason about correctness:
- Initialization: prove it is true before the loop starts.
- Preservation: assume it is true at the start of an iteration and prove the body keeps it true for the next check.
- Termination: combine the invariant with the false loop condition to derive the final result.
2.7 Progress measures
A progress measure is a value that moves predictably toward a bound. For a counter increasing toward a maximum, the remaining distance can be maximum - count. For a balance decreasing toward zero, the balance itself may be the measure.
A sound progress argument answers three questions:
- Is the measure bounded?
- Does every permitted iteration move it toward termination?
- Can any branch skip or reverse that movement?
If the answer to the second or third question is uncertain, the loop may not terminate.
2.8 Accumulator pattern
An accumulator preserves a running result across iterations.
let number = 1
let total = 0
while number <= 5 {
total += number
number += 1
}
print "Total: {total}"
A useful invariant is: before each check, total equals the sum of the integers from 1 through number - 1. When the loop ends with number equal to 6, the invariant implies that total contains the sum from 1 through 5.
2.9 Countdown pattern
let remaining = 3
while remaining > 0 {
print "Remaining: {remaining}"
remaining -= 1
}
The invariant is that remaining is never negative and equals the number of countdown values not yet completed. The update decreases it by one, so the loop must eventually reach zero.
2.10 Sentinel-controlled loops
A sentinel is a distinguished value that signals completion. When source-defined sample data is used, a variable can model the sentinel state.
let status = "pending"
let attempts = 0
const max_attempts = 3
while status == "pending" and attempts < max_attempts {
attempts += 1
if attempts == 2 {
status = "complete"
}
}
The status is the logical sentinel, while max_attempts is a defensive bound. Even if status never changes, the attempt limit guarantees termination.
2.11 Defensive iteration bounds
Whenever progress depends on data, an external result, or complex branching, add an explicit maximum when the domain permits it. A bound converts an uncontrolled loop into a predictable resource decision.
After the loop, distinguish successful completion from exhaustion:
if status == "complete" {
print "Completed in {attempts} attempts"
} else {
print "Stopped after reaching the attempt limit"
}
2.12 Off-by-one errors
An off-by-one error includes one iteration too many or one too few. It usually comes from mismatched initialization and boundary operators.
| Goal | Initialization | Condition |
|---|---|---|
| Process 1 through 5 | value = 1 | value <= 5 |
| Process 0 through 4 | index = 0 | index < 5 |
| Run while work remains | remaining = amount | remaining > 0 |
Write the intended first and last processed values before coding. Then trace the final successful check and the first failed check.
2.13 Infinite-loop causes
- Missing update: condition state never changes.
- Wrong update direction: the state moves away from the stopping boundary.
- Conditional update: one path through the body skips progress.
- Reset inside the loop: state repeatedly returns to an earlier value.
- Unreachable sentinel: completion depends on a value that cannot occur.
- Unbounded external dependency: progress depends on an event with no deadline or attempt limit.
- Floating-point equality: repeated decimal updates may never equal one exact target.
2.14 Floating-point termination
Avoid requiring repeated floating-point arithmetic to land on exact equality.
let value = 0
while value < 1 {
value += 0.1
}
Binary floating-point representation may produce small differences. Prefer an integer iteration count or a tolerance-based stopping rule when numerical approximation is intended.
2.15 Loop debugging workflow
- Write the initial state.
- Evaluate the condition manually.
- Record every variable read or changed by the body.
- Verify that every body path preserves the invariant.
- Verify that every continuing path advances the progress measure.
- Trace the final successful iteration.
- Trace the first failed condition.
- Add or review an explicit defensive bound.
- Compare the predicted trace with actual output.
2.16 Common mistakes
- Assuming the body runs once: while is a pre-test loop and may run zero times.
- Changing several control variables without a trace: keep the progress logic obvious.
- Updating after a branch that can skip it: ensure all continuing paths progress.
- Using < when the endpoint must be included: verify the exact boundary.
- Using == for approximate numeric termination: use a counter or tolerance.
- Omitting a maximum retry count: external or data-dependent work needs a defensive bound.
- Mixing unrelated work into the body: keep each iteration focused.
- Failing to distinguish success from exhaustion: inspect state after the loop.
2.17 Worked example: Bounded payment plan
A program applies fixed payments until a balance reaches zero or a maximum number of payments is reached.
let balance = 230
const payment = 50
const max_payments = 6
let payments_made = 0
while balance > 0 and payments_made < max_payments {
if balance >= payment {
balance -= payment
} else {
balance = 0
}
payments_made += 1
print "After payment {payments_made}: balance {balance}"
}
The invariant is: balance is nonnegative, payments_made is between 0 and max_payments, and balance represents the unpaid amount after exactly payments_made applications. The counter always increases, and the balance never increases.
With the supplied values, the loop makes five payments. The last branch sets the remaining balance from 30 to zero without making it negative.
2.18 Guided practice
- Trace the counting loop and identify its final failed check.
- State an invariant for summing 1 through 10.
- Correct a loop that starts at 1, uses count < 5, but must print 1 through 5.
- Explain why a missing update causes nontermination.
- Add a maximum-attempt bound to a sentinel-controlled loop.
- Identify every path that changes the progress measure in the payment example.
- Rewrite a floating-point step loop to use an integer counter.
- Describe how zero initial work affects a pre-test loop.
2.19 Hands-on lab: Build a bounded validation simulator
Create validation_loop.pea. It simulates repeated validation attempts using source-defined state rather than interactive input.
Requirements:
- Declare attempts, valid, and current_score as mutable values.
- Declare required_score and max_attempts as constants.
- Continue while the result is invalid and attempts remain.
- Increment attempts exactly once per iteration.
- Increase current_score through a deterministic sample update.
- Set valid when current_score reaches the requirement.
- Print the attempt number, score, and validity after each iteration.
- After the loop, print whether validation succeeded or the attempt limit was exhausted.
State one loop invariant and one progress measure before running the file. Trace every iteration for at least three configurations: immediate success, success on the final permitted attempt, and exhaustion without success.
Deliverable: The source file, invariant proof, progress argument, iteration traces, predicted and actual outputs, and one deliberately defective version that fails to terminate until a defensive bound is restored.
2.20 Review questions
- When is a while condition evaluated?
- Why can a while loop execute zero times?
- What are the four parts of a controlled loop?
- What does a loop invariant describe?
- How do initialization, preservation, and termination establish correctness?
- What is a progress measure?
- Why must every continuing path advance toward termination?
- How do < and <= change iteration boundaries?
- Why should retry loops have an explicit maximum?
- Why is exact floating-point equality risky as a stopping condition?
- How does an accumulator invariant explain a final result?
- What post-loop check distinguishes success from exhaustion?
2.21 Applied challenge
Extend the Chapter 2 unit converter with a bounded approximation exercise. Starting from an initial estimate, repeatedly improve it toward a target while tracking iteration count, absolute difference, and a maximum iteration limit. Define a tolerance-based stopping rule, state an invariant and progress measure, and test immediate convergence, ordinary convergence, and limit exhaustion. Keep the exercise separate from the converter’s approved formulas.
Lesson summary
A while loop checks its condition before each iteration and repeats only while that condition remains true-like. Safe loops have explicit initialization, focused work, a reliable update, and a false condition that is eventually reachable. Loop invariants explain correctness; progress measures explain termination. Iteration traces, exact boundary tests, counters, tolerances, and defensive limits prevent off-by-one errors, stalled progress, and unbounded execution.
Lesson status: Approved.