How Can We Prove a Repeated Procedure Stays Correct Until It Finishes? Teach learners to write a statement that is true at each loop checkpoint, prove that each iteration preserves it, and explain why the finished state satisfies the requested result. A correct answer for a single input does not establish that the procedure is correct for every allowed input.
This international lab uses a fictional list of signed score adjustments and a running-sum algorithm. It extends Recursion and Termination and State Transition by focusing on a proof of iterative correctness rather than only tracing or stopping. AI can generate candidate programs, but learners verify the contract and invariant. The activities are proposed coursework; future superintelligence remains hypothetical.
- State the input contract and expected result.
- Trace the processed prefix and accumulator.
- Prove initialization, maintenance and the exit implication.
- Show termination separately using a decreasing quantity.
- Expose off-by-one and unjustified early-stop errors.
- Independently construct a new invariant and test its boundaries.
Choose your reading route
Coursework series: Recursion and Termination Lab · State Transition Lab · Proof and Counterexample Lab · Interface Contract Studio · Vocabulary Coding and Engineering
Continue this coursework series: Matrix Transformations Lab · Loop Invariants Lab (this article) · Confidence Interval Coverage Lab · Lexical Entailment Studio
Full chapter index
Chapters 1–5
Chapters 6–10
Chapters 11–15
Chapters 16–20
Chapters 21–25
Chapter 26
1. The capability: establish correctness before trusting automation
A repeated procedure can produce a correct final number for one example by accident. A different input may reveal that it skips an item or counts it twice. An invariant supplies a statement about the state at each agreed checkpoint, not simply an attractive summary of the final result.
The lab produces a specification, trace, invariant, maintenance argument, termination argument and independent transfer. The aim is to make algorithmic reasoning inspectable. AI may propose code and tests, but a learner must distinguish a trace for one input from a proof for an entire declared domain.
2. Define the contract and checkpoint
A precondition states the assumptions about a valid input. A postcondition states what the completed procedure must deliver. A loop invariant is a property maintained at chosen checkpoints, here each evaluation of the loop guard, including the final false evaluation.
To prove total correctness of this simple loop, establish the invariant before the first iteration, show it survives each allowed iteration, derive the result when the guard is false and prove that the loop eventually exits. A property need not hold after every individual assignment inside the loop body.
Background reading: Cornell computer science: loop invariants and correctness.
3. Vocabulary Coding and Engineering for procedure verification
Within eduKate’s proposed VCE framework, distinguish state, iteration, guard, checkpoint, precondition, invariant, postcondition and termination. A variable named total does not guarantee it equals the intended total. Its meaning must be expressed as a relationship to the input.
Record exactly what the index represents: the number of processed entries and therefore the index of the next entry under zero-based indexing. This avoids ambiguity about whether the current entry has already been included. Precise language becomes part of the verification contract.
Related framework: Vocabulary Coding and Engineering.
4. The original signed adjustment register
Use the fictional fixed list a=[4,−3,7,−2,1] with length n=5. The task is to return the sum of all its entries. The general input contract permits any finite list of integers, including an empty list, and assumes exact integer arithmetic without overflow.
The algorithm begins with i=0 and s=0. While i<n, first set s to s+a[i], then increase i by one. Return s after the loop. The list remains unchanged throughout. These rules are mathematical pseudocode, not a claim about an actual financial or operational system.
5. Trace the reference input
Initially the processed prefix is empty, with i=0 and s=0. After processing the first entry, i=1 and s=4. The next states are (2,1), (3,8), (4,6) and (5,7). At the last checkpoint, the guard i<5 is false.
The returned sum is seven. Each prefix sum is available as a check. A learner should compare every state with the entries already processed rather than simply add the final list on a separate calculator. That is how a trace can reveal the first point of divergence.
| Checkpoint i | Entry just processed | s | Remaining n−i |
|---|---|---|---|
| 0 | None | 0 | 5 |
| 1 | 4 | 4 | 4 |
| 2 | -3 | 1 | 3 |
| 3 | 7 | 8 | 2 |
| 4 | -2 | 6 | 1 |
| 5 | 1 | 7 | 0 |
6. Write the invariant explicitly
At each guard evaluation, require 0≤i≤n, with i an integer, and s equal to the sum of entries with indices from 0 through i−1. Equivalently, s is the sum of the first i entries. Define the sum of an empty prefix to be zero.
Notice that this statement relates s to a moving boundary i. It is not the claim that s never changes. An invariant describes a relationship that remains true even while the variables change. The bounds on i also prevent treating an invalid index as a valid processed prefix.
7. Prove initialization
Before the first guard test, i=0 and s=0. Since the list is finite with n≥0, the index is within the allowed range. The first zero entries have sum zero, so s equals that prefix sum.
This is true for every valid input, not just the five-entry example. For an empty list n=0, the guard is false immediately and the invariant already holds. There is no need to read a[0], which would be invalid for that input.
8. Prove maintenance of the invariant
Assume the invariant holds before an iteration and i<n. Then 0≤i<n, so entry a[i] exists. Adding a[i] to s changes the old prefix sum into the sum of the first i+1 entries. Incrementing i makes the new index exactly that prefix length.
The updated i remains an integer between zero and n. The updated accumulator is the sum of the first updated-i entries, so the invariant holds at the next guard evaluation. This reasoning uses arbitrary integer values, including negative entries and zeros.
9. Derive the postcondition at exit
If the guard is false, i≥n. The invariant also gives i≤n, hence i=n. Substituting into the prefix relationship gives s equal to the sum of the first n entries, which is the entire list.
The result follows from the invariant together with the exit condition, not from the invariant alone. If a loop exited early with i<n, the invariant could still hold while the intended full sum had not yet been obtained.
10. Find the off-by-one error
A flawed variant uses guard i<n−1. For the reference list it processes only the first four entries, leaving i=4 and s=6. The prefix relationship is still true but the required result is seven. The exit condition no longer implies i=n.
Test the one-entry list [9]. The faulty guard is false at the start, returning zero instead of nine. That minimal example exposes the error cleanly. Repair the guard and explain why the corrected exit implies the postcondition.
11. Prove termination using remaining work
Let the remaining-work quantity be n−i. At every guard checkpoint it is a nonnegative integer. Whenever the guard is true, n−i≥1 and the iteration increments i by one, so remaining work decreases by one.
A nonnegative integer cannot decrease indefinitely by one while staying nonnegative. The loop therefore reaches i=n and exits after exactly n iterations from i=0. This termination argument is separate from the reasoning that the returned value is correct.
12. A true invariant need not ensure termination
Consider the defective loop that starts at i=0, s=0 and, while i<n, changes neither variable. For a nonempty list, the prefix invariant remains true indefinitely, but the guard never becomes false. It makes no progress toward its result.
This demonstrates why an invariant alone cannot prove total correctness. The reference algorithm has both maintenance and a decreasing remaining-work quantity. Ask AI to identify these as two distinct obligations rather than merely stating that the invariant proves everything.
13. A weak invariant may not prove the desired result
The assertion 0≤i≤n is maintained by the original loop, but by itself says nothing about s. A procedure that sets s=0 at every iteration could preserve that index property and terminate yet fail the sum task.
Strengthen the statement to connect s to the processed prefix. The appropriate invariant should be strong enough, together with the false guard, to imply the result. Invariant design therefore depends on the postcondition rather than just on properties that happen to hold.
14. Inspect an update-order error
A flawed variant increments i first and then adds a[i], using the same initial state and guard. On the reference list it first adds −3 rather than four. Eventually, when the old index is four, incrementing it to five causes an invalid access.
Trace the first iteration against the intended prefix relationship: after i=1, s is −3 but the first entry sums to four. The invariant identifies the failure before the final error. Repair the operation order or redesign the index convention and prove it consistently.
15. Do not assume a running sum always increases
The reference trace falls from four to one when the second entry is processed, and from eight to six when the fourth is processed. An assertion that s increases on every iteration is therefore false for the valid input domain.
Use the number of unprocessed entries as the termination measure, not the signed total. A new contract restricted to positive integers might permit other properties, but would not justify them for the original domain. Always preserve the input assumptions beside the proof.
16. Extend the register to count positive entries
Add a variable c initially zero. On each iteration, add one to c if the current entry is greater than zero, then advance i as before. Strengthen the invariant to say that c counts positive entries among the first i, alongside the sum invariant.
For the reference list the positive counts after each entry are 1,1,2,2,3. At exit s=7 and c=3. This extension illustrates how a second accumulator requires its own maintained relationship. Zero is not positive under the declared condition.
| i | Sum s | Positive count c |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 4 | 1 |
| 2 | 1 | 1 |
| 3 | 8 | 2 |
| 4 | 6 | 2 |
| 5 | 7 | 3 |
17. Check arithmetic assumptions and side effects
The proof assumes exact integers and an unchanged finite input. An actual machine using bounded integers might overflow even when the pseudocode proof is sound for mathematical integers. Concurrent changes to the list would likewise invalidate the prefix interpretation.
A real implementation must preserve or replace those assumptions with checks appropriate to its environment. Do not treat a mathematical proof of pseudocode as a certification of every compiled program or deployment. Document what the proof establishes and what remains to be tested.
18. Prompt AI to produce a proof and a failing trace
Try: For a fixed finite integer list, initialize i=0 and s=0; while i<n, add a[i] to s and then increment i. Define the invariant at every guard check. Prove initialization, maintenance, postcondition at exit and termination using n−i.
Request a trace for [4,−3,7,−2,1] and for an empty list. Then ask for the first failing state of the guard i<n−1 and increment-first variants. Independently check the trace and the proof obligations; do not accept a passing demonstration as a universal proof.
19. A proposed assessment rubric
Use four dimensions scored zero to three: explicit input contract and invariant; accurate trace and initialization; maintenance, postcondition and termination reasoning; independent transfer with a boundary counterexample. Zero means absent evidence, one a substantial gap, two mostly correct work with a missing check, and three reproducible reasoning.
Keep the dimensions separate so a learner can target a specific reasoning gap. Use written, spoken, diagrammatic or code-based evidence as appropriate. This rubric is an original teaching proposal, not a validated measure of computing ability.
20. Independent transfer: sum the negative entries only
Use b=[−2,0,5,−4,3]. Modify the loop to add an entry to s only when it is strictly negative, but increment i after every iteration. Formulate the invariant, trace the reference input and explain why the loop terminates even if there are no negative entries.
Worked check: after the five entries, the running sums are −2,−2,−2,−6,−6. The invariant says s equals the sum of negative entries in the first i positions and 0≤i≤n. It holds initially; adding the next entry only if negative preserves it. At i=n the desired sum is −6. Remaining work decreases independently of the conditional addition. Empty input returns zero.
21. Primary learning: keep a tally of the cards already read
Use a small stack of labelled number cards and a running collection of counters. Have the child identify the cards already processed and show that the current total matches those cards. Use nonnegative counts initially and accessible materials.
The formal invariant can wait until the learner is ready. The capability is connecting the running state to the completed part of the task. Adults may prepare and check fictional variations using AI; no direct child access is required.
22. Secondary learning: turn a trace into a general explanation
Students can construct a table of i, entry processed, s and remaining work, then state the invariant in words or notation. Include an empty list and a one-entry list to test the guard. Ask which step of the proof fails in each defective variant.
Learners ready for code can implement the procedure in a suitable environment, compare it with the proof and inspect integer behaviour. Keep the mathematical argument separate from language syntax. Provide alternatives to visually dense trace tables when necessary.
23. University, institutions and EnDist
Advanced study may investigate formal specifications, inductive invariants, termination variants and automated verification. More complex programs require reasoning about aliases, mutable state, concurrency and arithmetic. The simple example deliberately avoids those complications.
Within eduKate’s proposed EnDist framework, AI may distribute access to generating executable procedures. Education should also distribute the capability to state what those procedures must preserve, prove why they reach the desired state and detect a result that merely looks right. This is a proposed direction, not an empirical outcome.
24. A four-week Loop Invariants Lab
Week one establishes the input contract, pseudocode and reference trace. Week two derives the prefix invariant, proves initialization and maintenance, and derives the result at exit. Submit a written argument independent of any particular example.
Week three studies off-by-one errors, weak invariants, missing progress and changed input assumptions. Week four completes the negative-only transfer, tests empty input and revises an AI-generated proof. Adapt pacing and access supports while retaining all four proof obligations.
25. Questions about loop correctness
Does invariant mean a variable never changes? No; a relationship can stay true while variables change. Is a correct trace a proof for all inputs? Not generally. Can an invariant hold in a loop that never terminates? Yes; the no-progress example demonstrates this.
Does a proof for exact integers guarantee safe bounded-integer code? No; the implementation must satisfy the stated arithmetic assumptions. Can AI help write an invariant? It may propose one, but check its initialization, preservation, exit implication and termination argument.
26. Sources, boundaries and next steps
Cornell’s loop-invariant lecture provides the background correctness method. The signed adjustment example, trace, defective variants, transfer and rubric are original fictional teaching constructions. No deployed software or empirical learning outcome is represented.
Continue by designing a procedure that counts entries satisfying a new condition. State the input contract and invariant, then identify a small failing input for an intentionally faulty guard. The transferable capability is proving a maintained relationship instead of mistaking one successful output for correctness.
References: Cornell computer science: loop invariants and correctness.
Related coursework: Recursion and Termination Lab · State Transition Lab · Proof and Counterexample Lab · Interface Contract Studio.
