Computer Science 241
Exercises on Loop Invariants

1. Carrano and Prichard: Page 41, Self-Test Exercises 1 and 2

a) What is the loop invariant for the following?

int index = 0;
int sum = item [0];
while (index < n)
{
      index ++;
      sum += item [index];
} // while loop

b) Write specifications for a method that computes the sum of the first five postitive integers in an array of N arbitrary integers.

2. Write a method to calculate x n for x any double and n an interger >= to 0.  Write the pre- and post-conditions for the method and the loop invariant.

3. Write a method to calculate x ! (the factorial function).  (See page 32 of the text.)  Then write the pre- and post-conditions and the loop invariant.