Exercises

Fun Class Activities:

  1. Consider the loop below, and identify a correct loop invariant and justify it.
    sum = 0;
    for (i = 0; i < n; i++)
       sum += i;
  2. Given an array A, and a loop that swaps A[i] and A[n-1-i] for i = 0 to n/2, write a loop invariant and prove it informally.
  3. Write a pseudocode that multiplies two numbers a and b using repeated addition, and state a suitable loop invariant.
  4. In a loop that finds the maximum element in an array, what loop invariant should hold before and after each iteration?
  5. Analyze the loop invariant in this pseudocode. What does the invariant guarantee about product?
    product = 1;
    for (i = 1; i <= n; i++)
        product *= i;