You are on page 1of 2

Assignment -3

1. Write a suitable contract for this loop such that the assertions on lines 9 and 10 are proved
as well as the contract of the loop.
void foo(){
int i ;
int x = 0 ;
for(i = 0 ; i < 20 ; ++i){
if(i == 19){
x++ ;
break ;
}
}
9: //@ assert x == 1 ;
10: //@ assert i == 19 ;
}

2. The program Div is supposed to compute the dividend of integers x by y; this


is defined to be the unique integer d such that there exists some integer r – the
remainder – with r < y and x = d · y + r. For example, if x = 15 and y = 6,
then d = 2 because 15 = 2 · 6 + 3, where r = 3 < 6. Let Div be given by:
r = x;
d = 0;
while (r >= y)
{
r = r - y;
d = d + 1;
}
Show that the partial correctness of the above code is valid with precondition: ¬(y = 0) and
post condition: (x = d · y + r) ∧ (r < y).

3. (for practice, need not to submit)


Show that the partial correctness of the following code
Pre condition: y ≥ 0
Post condition: z = x · y
a = 0;
z = 0;
while (a != y)
{
z = z + x;
a = a + 1;
}

4. Write a suitable invariant and variant for the following loop


int x = -20 ;
while(x < 0)
{
x += 4 ;
}
If your variant does not precisely state the number of remaining iteration, add a variable that
records exactly the number of remaining iterations and use it as a variant. You might need to
add an invariant.

You might also like