This method uses induction to prove that an algorithm always produces the correct answer, if it terminates. Proofs that the algorithm terminates are usually handled separately.
This method is represented by a flowchart on page 15 of The Art of Computer Programming.
We firstly break down the algorithm into steps. After each step, we make an assertion which must be true after this step. For simplicity, where multiple statements are made after a given step, we consider that as being grouped into a single assertion - for example ” and ” could be a single assertion.
Where the computation branches, the assertion made will depend on which branch is taken - for example, “if , assert odd, else assert even”. If we can prove that each assertion follows from the previous assertion in combination with the operation performed in between, then we know by induction that whenever the end of the computation is reached, the final assertion made is true. That assertion will state that the program has produced the correct answer - for example, in the Euclidean algorithm, it would be asserted that the output equals the greatest common divisor of the inputs.
The path we follow through the algorithm will be different depending on the inputs, due to branching. Nonetheless, we can produce a general proof by induction that accounts for this. Here is what such a proof would look like.
PROOF
Let be the total number of assertions in the algorithm, and be the total number of (not necessarily unique) assertions encountered during a particular running of the algorithm. Let be the set of assertions, and be the sequence of encountered assertions until the termination of the program. Let be the set of possible assertions that can follow after . So .
Firstly, prove that is true for any given input. Then prove that, for all , is proven by its corresponding operation in combination with . Assume is true for some integer . The assertion corresponds to some assertion , and is in . It has been proven that (and the operations that follow it) imply all assertions in . Therefore, using the operation preceding , implies for all integers . Thus, since has been proven to be true, all assertions are true by induction.
This general principle can be used to formulate a semantic definition of each operation in a programming language, as a logical rule that says exactly what assertions can be made after the operation, based on what operations are true beforehand. Reversing this (finding the “weakest precondition” that must be true before an operation, in order for a given assertion to be true afterward) can be used to discover new algorithms that are guaranteed to be correct.