Peter Müller
August 26, 1998
Consider the following code fragment which calculates the sum of the first 10
whole numbers:
We will now show with pre- and postconditions that this loop really calculates the sum. However, I will only give and explain those conditions which are of interest here. Just before we enter the loop, the following precondition hold:
I use the notation to denote the sum over all numbers from 1
to n. Note that
is defined to be 0. (We use this in the
above loop precondition!)
Since the loop condition holds (in) we can enter the loop. Until now, we
have:
The next statement is the increment of s by the value of i. Using the precondition, this would yield to
This can be simplified to:
The next line increments i by 1. What does this mean to the current precondition? Well, just that the value of i has changed! As a consequence, every occurrence of i must be adopted to reflect this change, leading to the following postcondition of the i assignment:
The second part of this condition can be rewritten as:
Note that the first term (in) is exactly the loop condition. If this term
evaluates to true, the body is executed again. However, the conditions hold
each time the loop body is executed. They are invariant
regarding the execution.
Only if the second part is true, the loop terminates. So after the loop the following condition holds:
From this, we can conclude:
With the fact that n equals 10 we have shown, that the loop really do what we have expected.
Finally, the whole loop with all conditions is shown:
This document was generated using the LaTeX2HTML translator Version 97.1 (release) (July 13th, 1997)
Copyright © 1993, 1994, 1995, 1996, 1997, Nikos Drakos, Computer Based Learning Unit, University of Leeds.
The command line arguments were:
latex2html -html_version 3.0 -split +0 -show_section_numbers -no_navigation -t Pre- and Postconditions -antialias -toc_stars -local_icons -dir conditions main.tex.
The translation was initiated by P. Mueller on 8/26/1998