Name ________________________

 

Program Specification and Verification Worksheet

Submit this for up to 15 points

  1. Assuming that n is the input variable and s is the output variable, both declared as int, give a reasonable specification, using input and output assertions, for what the following program does. Consider doing this in both summation form and in closed form.
  2. 
    
    s = 0;
    int k = 0;
    while( k <= n )
      {
      s = s + k;
      k = k + 1;
      }
    
    
    
    
    

  3. What is the loop invariant which can be used to show that the above program is partially correct? Again, consider doing this in both summation form and in closed form.
  4. 
    

     

  5. Construct a program which is partially correct with respect to the following assertions, such that the program uses only addition, not multiplication. (Hint: look at the summation 1 + 3 + 5 + 7 + …)

  6. Input Assertion: n >= 0 Output Assertion: s == n*n

     

     

     

     

     

  7. For your program in the previous problem, what is the loop invariant?




  8. What are the verification conditions in the program above?


  9.  






  10. The following program is supposed to compute n! (n factorial) where n is any non-negative natural number. Give the input and output assertions and loop invariant, then prove the verification conditions.
  11. 
    k = n;
    f = 1;
    while( k > 0 )
      {
      f = f * k;
      k = k - 1;
      }

     

     

     

     

  12. The following program is supposed to swap the values in variables x and y. Give input and output assertions and appropriate intermediate assertions which show this is the case:
  13. 
    x = x + y;
    
    y = x - y;
    
    x = x - y;

     

     

  14. The following program is supposed to find the location of the minimum value in an array a[0..n-1] of 1 or more float elements. Give appropriate input and output specifications which state that this is what it does:
  15. 
    int minloc = 0;
    
    for( int i = 1; i < n; i++ )
      {
      if( a[i] < a[minloc] )
        {
        minloc = i;
        }
      }

     

     

     

  16. For the previous problem, give the verification conditions.
  17.  

     

     

    
    

     

  18. How would the verification conditions change if we used the following program instead of the previous?
  19. 
    int minloc = 0;
    
    for( int i = 1; i < n; i++ )
      {
      minloc = (a[i] < a[minloc]) ? i : minloc;
      }

     

     

     

     

     

  20. Specify and prove that the following program sorts array a[0..n-1] in ascending order
for( j = 0; j < n; j++ )
  {
            int minloc = j;

  for( int i = j+1; i < n; i++ )
    {
    minloc = (a[i] < a[minloc]) ? i : minloc;
    }

  temp = a[j];

  a[j] = a[minloc];

  a[minloc] = temp;
  }