Prerequisites
Sequential program semantics, mathematical induction, logic and reasoning with unbounded integers.
Learn first
Programs follow precise instructions
A program is a set of instructions. A variable stores a value. A condition chooses between paths. A loop repeats steps. Output is the result produced.
How to work it out Trace one instruction at a time. Keep a record of values and check exactly when a condition or repeated step is evaluated.
A separate example In a separate trace, start with n = 2, add 3, then double n. The two instructions happen in order: 5 is an intermediate value before the final result.
Use mathematical integers and sequential assignments: SET x TO x + 2; SET y TO 3 * x. Desired final condition is y >= 12. A weakest precondition is the least restrictive condition on the initial state guaranteeing that outcome. Substitute assigned expressions backward in reverse execution order.
Worked example
First replace y by 3x to obtain 3x >= 12, so the intermediate x >= 4. Then replace x by x + 2 to obtain initial x + 2 >= 4, hence initial x >= 2. These finite assignments always terminate in this model.
Further inquiry
Derive the weakest precondition by substitution, prove both sufficiency and minimality, and distinguish it from stronger sufficient conditions. Extend the discussion to a loop: explain why a partial-correctness invariant alone does not establish termination, and give a decreasing integer variant for a suitable example.
Review criteria
- State the execution model and the domain of every input.
- Justify each implication, update order and boundary case rather than only checking examples.
- Distinguish correctness on termination from an argument that termination occurs.