Program verification involves formally proving that a program satisfies certain properties, such as having no defects, by establishing that the program meets its specification. This is done by defining preconditions and postconditions and using weakest preconditions to reason about how the program transforms states. Testing involves running a program with sample inputs and checking that the outputs are as expected to find defects empirically.
22. P: (x = y - 2)
S: x := x + 2
Q: (x = y)
le
Examp
23. {P} S1 {Q} , {Q} S2 {R}
Sequence
{P} S1;S2 {R}
{P∧B} S1 {Q} , {P∧¬B} S2 {Q}
Conditional
{P} if B then S1 else S2 {Q}
24. P I ∧ ({I∧B} S {I}) , (I ∧ ¬B Q)
While loop
{P} while B do S end {Q}
25. P I ∧ ({I∧B} S {I}) , (I ∧ ¬B Q)
While loop
{P} while B do S end {Q}
Loop invariant I
I = property which stays true before and after every loop
0. initial condition: P I;
1. iterative (inductive) condition: {I ∧ B} s {I};
2. final condition: I ∧ ¬B Q
26. P: (x ≥ 0) ∧ (y > 0)
S: quo := 0;
rem := x;
while (y ≤ rem) do
rem = rem − y;
quo = quo + 1
end
Q: (quo ∗ y + rem = x) ∧
(0 ≤ rem < y) :
E xample inder
n d rema s
Qu otient a 2 integer
ng
o f dividi
27. while (lo < hi) {
m = (lo + hi) / 2;
if (n > m)
lo = m + 1;
else
hi = m;
}
n = lo;
ch
: bina ry sear
E xample
28. I: lo <= n ∧ n <= hi
while (lo < hi) { lo <= n ∧ n <= hi*/
/*I:
m = (lo + hi) / 2;
if (n > m) /*
in both cases: lo <= n ∧ n <= hi */
lo = m + 1; /* n > m => n >= m+1 => n >= lo */
else
hi = m; /* !(n < m) => n <= m => n <= hi */
} /* I stays true */
n = lo; /*
lo<=n ∧ n<=hi ∧
!(lo<hi) => lo==n ∧ n==hi */
ch
: bina ry sear
E xample
43. While loop
L = while (B) do S end
wp(L,Q) I ∧
=
∀y, ((B ∧ I) wp(S, I ∧ x < y))
∀y, ((¬B ∧ I) Q)
44. While loop
L = while (B) do S end
wp(L,Q) I ∧
=
∀y, ((B ∧ I) wp(S, I ∧ x < y))
∀y, ((¬B ∧ I) Q)
Loop verification
I = property which stays true before and after every loop
0. P I;
1. I∧B wp(s, I);
2. I∧¬B Q.
45. P: (x≥0) ∧ (y>0)
S: quo := 0;
rem := x;
while (y ≤ rem) do
rem = rem − y;
quo = quo + 1
end
Q: (quo∗y+rem=x) ∧ (0≤rem<y)
:
E xample inder
n d rema s
Qu otient a 2 integer
ng
o f dividi
46. P: (x≥0) ∧ (y>0)
S: quo := 0;
rem := x;
I: (quo∗y+rem=x) ∧ (rem≥0) ∧ (y>0) ∧ (x≥0)
while (y ≤ rem) do
rem = rem − y;
quo = quo + 1
end
Q: (quo∗y+rem=x) ∧ (0≤rem<y)
:
E xample inder
n d rema s
Qu otient a 2 integer
ng
o f dividi
47. P: (x≥0) ∧ (y>0)
I: (quo∗y+rem=x) ∧ (rem≥0) ∧ (y>0) ∧ (x≥0)
Q: (quo∗y+rem=x) ∧ (0≤rem<y)
(x ≥ 0) ∧ (y > 0)
(x = x) ∧ (x ≥ 0) ∧ (x ≥ 0) ∧ (y > 0)
(x=rem+y∗quo) ∧ (x≥0) ∧ (rem≥0) ∧ (y>0) ∧ (y≤rem)
(x = (rem − y) + y ∗ (quo + 1)) ∧
x ≥ 0 ∧ rem − y ≥ 0 ∧ y > 0
(x=rem+y∗quo) ∧ (x≥0) ∧ (rem≥0) ∧ (y>0) ∧ (y>rem)
(x = rem + y ∗ quo) ∧ (0 ≤ rem < y)
:
E xample tions
n condi
ve rificatio