PeaBox Lab › PeaLang › Learn › Chapter 3 › Lesson 2

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:

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

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:

Checkcount before bodyOutputcount after update
11Count: 12
22Count: 23
33Count: 34
44Body skipped4

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:

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:

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.

GoalInitializationCondition
Process 1 through 5value = 1value <= 5
Process 0 through 4index = 0index < 5
Run while work remainsremaining = amountremaining > 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

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

2.16 Common mistakes

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

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:

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

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.

← Previous Next →