Download presentation
Presentation is loading. Please wait.
1
Loop Invariants CSC 171 FALL 2001 LECTURE 6
2
History: Herman Hollerith
Herman is said to have been a bright and able child at school, but had an inability to learn spelling easily. His determined teacher made his life miserable to the extent that he used to avoid school whenever possible and run away when his teacher showed renewed effort to improve his spelling.
3
History: Herman Tabulating
Herman Hollerith won the competition for the processing equipment to assist in the 1890 US Census The Hollerith Tabulating Company, eventually became the Calculating-Tabulating-Recording (C-T-R) company in 1914, and eventually was renamed IBM in 1924.
4
Loop invariants In order to verify loops we often establish an assertion (boolean expression) that is true each time we reach a specific point in the loop. We call this assertion, a loop invariant
5
Assertions When ever the program reaches the top of the while loop, the assertion is true INIT BODY INVARIANT TEST
6
Example Write a method to compute an
public static int power(int a , int n) You have 5 minutes
7
Possible solution public static double power(int a, int n) {
double r = 1; double b = a; int i = n ; while (i>0){ if (i%2 == 0) { b = b * b; i = i / 2;} else { r = r * b; i--; } return r; }
8
Does it work? b i r a 100 1 a2 50 a4 25 24 a8 12 a16 6 a32 3 2 a36 a64
a100 Does it work? SURE! TRUST ME! Well, look at a100 if you don’t believe me! Note, less loops! Can you “prove” that it works?
9
What is the loop invariant?
At the top of the while loop, it is true that r*bi = an It is? Well, at the top of the first loop r==1 b==a i==n
10
So, if it’s true at the start
Even case rnew= rold bnew == (bold)2 inew==(iold)/2 Therefore, rnew * (bnew)i-new == rold * ((bold)2)i-old/2 == rold * ((bold)2)i-old == an
11
So, if it’s true at the start II
Odd case rnew= rold*bold bnew == bold inew==iold-1 Therefore, rnew * (bnew)i-new == rold *bold* (bold)i-old-1 == rold * (bold)i-old == an
12
r*bi = an So, If it’s true at the start
And every time in the loop, it remains true Then, it is true at the end r*bi = an And, i == 0 ( the loop ended) What do we know?
13
Correctness Proofs Proof are more valuable than testing
Tests demonstrate limited correctness Proofs demonstrate correctness for all inputs For some time, people hoped that all formal logic would replace programming The naïve idea that “programming is a form of math” proved to be an oversimplification
14
Correctness Proofs Unfortunately, in practice, these methods never worked very well. Instead of buggy programs, people wrote buggy logic Nonetheless, the approach is useful for program analysis
15
The take away message? In the end, engineering and (process) management are at least as important as mathematics and logic for the successful completion of large software projects
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.