12BSC203 Verifying Algorithms
12BSC203 Verifying Algorithms
Verifying Algorithms
7
This code is correct. The variable m acts as an upper limit for
the iteration counter i. It is initialized to the value of n, but if
an entry equal to the search target is found, m is assigned the
current value of the iteration counter, and the loop terminates.
If no entry equal to x is found, the loop terminates with i
equal to the initial value of m.
8
Correctness of Code
• These examples, though small, have shown that it is
very difficult to be sure whether the code is correct,
particularly when the programmer has used an
unfamiliar code style or has tried to write very
efficient code.
• We will discuss how to support sound reasoning
about a program behavior.
Correctness Statement
OR P {C} Q
10
Correctness Statement vs. Assertions
• A correctness statement is either true(valid) or false
(invalid) independent of any particular state of
computation.
Example:
13
Simple Assignment Statement
14
Hoare’s Axiom scheme for Assignment
• C.A.R. Hoare:
15
Hoare’s Axiom scheme for Assignment
16
Check-in
• What should pre-condition P be in each of the
following correctness statements for the statement to
be an instance of Hoare’s axiom scheme? All
variables are of type int.
1. P { x = x+1;} x>0
2. P { x = x+1;} x==y
3. P { x = x-1;} x == y-1
Solution
1. x+1> 0 {x = x+1} x>0 Or x >-1 { x = x+1;} x>0
2. x+1== y {x = x+1} x==y Or x== y-1 { x = x+1;} x==y
3. x-1 == y-1 {x=x-1} x==y-1 Or x==y { x = x-1;} x == y-
1
Substitution into Assertion
• If Q is an assertion, I is an identifier, and E is an
expression, we use the notation [Q](I->E) to denote
the assertion that is Q, except that E has been
substituted for every occurrence of I
Solution:
ForAll(k) x>k
Using Mathematical Facts
We may validate the correctness statement
n-l >= 0 { n = n-1; } n >= 0 by using Hoare's axiom scheme. To verify
n>0 { n = n-l; } n >= 0
we note that the assertion:
n>0 implies n-l >= 0
is true in every state; that is, it is a mathematical fact independent of
the computational state, provided that n is of type int. This justifies
the validity of:
ASSERT(n>0)
ASSERT(n-l >= 0)
n = n-l;
ASSERT(n >= 0)
• An inference rule allows the derivation of the statement below the horizontal
line if the premises above the horizontal line may be proved.
• It will not always be as easy as in the example to determine the intermediate assertions;
often it will be necessary to use mathematical facts to strengthen pre-conditions or weaken
post-conditions appropriately.
Check-in
Verify the validity of
• Pre-condition: true
• Post-condition: m>= x && m>=y && (m==x || m==y)
Assert(true) P
If(x>y) B
m=x; C0
else
m=y; C1
Assert(m>=x && m>=y && (m==x || m==y) ) Q
If-statement
We will start to verify the first statement C0
Assert(true&&x>y)
m=x;
Assert(m>=x && m>=y && (m==x || m==y))
Check-in
• Complete the verification of the if-statement by
verifying the correctness statement of C1 (else)