Quiz 5 -- The Quiz that Cares [tm]

Please write your name and lab section letter at the top of the page.

Consider the following iterative program that is supposed to compute the product of m and n using addition (no multiplications are allowed!)

  public int mpy(int m, int n) { // m and n must be nonnegative
     int i = 0;                      /* line 1 */
     int ans = ?  ;                  /* line 2 */
     while (i != n) {                /* line 3 */
        i = i + 1;
        ans =  ????  ;               /* line 4 */
     }
     return ans;
  }
  1. (10 pts) How should ans be initialized at line 1?
  2. (25 pts) How should ans be modified at line 4?
  3. (25 pts) What is the termination condition of the while loop at line 3? Your answer must be a predicate (Boolean-valued expression).
  4. (20 pts) If line 1 were changed to
         int i = 1;
    
    how would you initialize ans at line 2?
  5. (10 pts) What happens to the cost of running this method when n is much, much (much) greater than m?
  6. (10 pts) State a loop invariant that leads to a correctness argument that the above code computes the product of m and n.