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: Writing Correct Programs; Finding Invariants CS 536 Notes, Lecture 10, Mon Nov 8, 2010 A. Why It is easier to write good programs and check them for defects than to write bad programs and then fix them. The hardest part of programming is finding good loop invariants. There are heuristics for finding them but no algorithms that work in all cases. B. Outcomes After this lecture, you should Know how to generate possible invariants using the techniques replace a constant by a variable and deleting a conjunct. C. Writing Correct Programs It is easier to write good programs and check them for defects than to write bad programs and then fix them. Know what specifications we need to meet. Use the Hoare logic rules and wp to help write correct programs in a goaloriented way (backwards from postconditions). Write statements only when we know how theyll help us. For while loops, take the loop { P } S ; { inv P } { bd t } while B do S od { R }. There are five things we need to know to verify that a loop does what its supposed to: 1. { P } S { P } Initialization establishes the loop invariant. 2. { P B } S { P } The loop body preserves the loop invariant. 3. P B R Upon exit, the loop achieves the postcondition. 4. P t The bound function t has a lower bound. 5. { P B t = z } S { t < z } Executing the loop body makes progress towards termination. So to write a loop, we need to find an invariant, loop test, initialization, loop body, and bound function. We need to find an invariant and loop test that establishes the desired postcondition. { inv P } while B do ??? od { P B } { R } The invariant should be easy to establish with some easy initialization code S . { P } S { P } The body of the loop needs to make progress toward termination by executing some code S b to decrease the bound function. We may need some other code S to take the state from P B to wp ( S b , P ). Illinois Institute of Technology Notes for Lecture 10 CS 536: Science of Programming  1 of 10  James Sasaki, 2010 ... while do { P B } { wp ( S ; S b , P )} S ; { wp ( S b , P )} S b { P } od ... E.g., take this version of the summation loop: { inv P }{ bd ni } while i n do { P i n } { P } s := s+i+1; { P } i := i+1 { P } od , where P i n s = sum(0, i) , P i+1 n s = sum(0, i +1) , and P i+1 n s+i+1 = sum(0, i+1) . Note ( P i n R ), so we know the loop is correct. There are other ways to write the loop body, of course. If P B doesnt imply wp ( S b , P ), we can strengthen it by using an if B where P B B wp ( S b , P )....
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