Double


Document last modified: 

ESC


Following doubles each value of array. 
 

class Double {

//@ pre A != null;
//@ post (\forall int j;
                          0 <= j && j < A.length;
                          A[j] ==2*\old(A[j]) );

   void dbl(int A[]) {

      int i=0;

      //@ loop_invariant
                  (\forall int j;
                             0<=j && j < i;
                             A[j] == 2 * \old( A[j] ));

         while(i < A.length) {

              A[i]=2*A[i];

              i = i + 1;
          }
   }
}

 

Question 2.8

  1. Does the postcondition:

        //@ post (\forall int j; 0 <= j && j < A.length; A[j] ==2*\old(A[j]) );

    hold when the loop is changed to:

    i=5;
    while(i < A.length) { ...

  2. Does the loop invariant still hold when changed to:

    //@ loop_invariant (\forall int j; 5<=j && j < i; A[j] == 2*\old(A[j]) );

  3. Does the loop invariant hold for:

    //@ loop_invariant (\forall int j; 0<=j && j < i ; j-1 <= i);

  4. Does the above loop invariant serve any useful purpose?
     

Example

    Same as above but uses a for and function to perform the multiplication.

class Double {

//@ pre A != null;
//@ post (\forall int j; 0 <= j && j < A.length; A[j] ==twice(\old(A[j])) );

   void dbl(int A[]) {

      int i=0;

      //@ loop_invariant (\forall int j; 0<=j && j < i; A[j] == twice(\old(A[j])) );

      for(i=0; i< A.length; i++)

          A[i]=twice(A[i]);
   }

//@ pre true;
//@ post \result == 2*x;

   int twice(int x) {
      return 2*x;
   }
}