This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: More Loops; Termination CS 536 Notes, Lecture 9, Mon Nov 1, 2010 A. Why Loops are ubiquitous, so its useful to see examples of proving them correct. Diverging programs arent useful, so its useful to know how to show that loops terminate. B. Outcomes After this lecture, you should Be familiar with proof outlines for loops with conditionals in their body. Be familiar with the loop bound method of ensuring termination. Be familiar with the extra obligations required to prove that a partially correct program is totally correct. C. Example: Some Variants of Summation Weve looked at the simple summation loop { n } i := 0; s := 0; { inv P } while i < n do i := i+1; s := s+i od { s = sum(0, n) } where P is i n s = sum(0, i) Weve seen how modifying the initialization causes changes to the initial condition (and invariant) 1 { n 1 } i := 1; s := 1; { inv 1 i n s = sum(0, i) } ... But we can have other variations too. E.g., { n 1 } i := 1; s := 0; { inv 1 i n s = sum(0, i1) } while i1 n ... { n 1 } i := 0; s := 1; { inv i+1 n s = sum(0, i+1) } while i+1 n ... There are the downgoing loops too. Given that the postcondition is s = sum(0, n) , we could get an invariant by generalizing from to a variable j that decreases from n to . { n } j := n; s := n; { inv j n s = sum(j, n) } while j do s := s+j1; j := j1 od { s = sum(0, n) } D. Example: Iterative GCD For x , y , x , y > , gcd ( x , y ) is the largest value that divides both x and y evenly (without remainder). E.g., gcd (300, 180) = gcd (2 * 3 * 5, 2 * 3 * 5) = 2 * 3 * 5 = 60. Illinois Institute of Technology Notes for Lecture 9 CS 536: Science of Programming  1 of 9  James Sasaki, 2010 1 Technically we dont need to modify the invariant, but as i will never = 0 , we might as well. Useful gcd property: Case 1 ( x > y ): gcd ( x , y ) = gcd ( x y , y ) Case 2 ( y > x ): gcd ( x , y ) = gcd ( x , y x ) Case 3 ( x = y ): gcd ( x , y ) = x = y E.g., gcd (300, 180) = gcd (120, 180), gcd (120, 60) = gcd (60, 60) = 60. Heres an iterative gcdcalculating loop: { x > 0 y > 0 x = x y = y } // x and y are the initial values of x and y { inv P } // where P is x > 0 y > 0 gcd ( x , y ) = gcd ( x , y ) while x y do if x > y then x := x  y else y := y  x fi od { x = gcd ( x , y )} A full annotation: { x > 0 y > 0 x = x y = y } { inv P } while x y do { P x y } // where P is x > 0 y > 0 gcd ( x , y ) = gcd ( x , y ) if x > y then { P x y x > y } { P [ x  y/x ]} x := x  y { P } else { P x y x y } { P [ y  x/y ]} y := y  x { P } fi { P } od { P x = y } { x = gcd ( x , y )} The substitutions are P [ x  y/x ] is xy > 0 y > 0 gcd ( x ,...
View
Full
Document
This note was uploaded on 04/17/2011 for the course CS 536 taught by Professor Cs536 during the Fall '08 term at Illinois Tech.
 Fall '08
 cs536

Click to edit the document details