1. Carrano and Prichard: Page 41, Self-Test Exercises 1 and 2
a) What is the loop invariant for the following?
// precondition: n >= 0, loop invariant: sum = item [0] + item [1] +
… + item [index]
int index = 0;
int sum = item [0];
while (index < n)
{
index ++;
// index <= n and sum = item [0]
+ … item [index – 1]
sum += item [index];
// index <= n and sum = item [0]
+ … 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.
public void sumFivePositives ()
{
// Number of positive entries in array,
item, is >= 5. sum = sum of first 5 entries > 0.
int [] item = {0, -1, 1, -2, 2, -3,
3, -4, 4, -5, 5, -6, 6};
int N = 13;
int sum = 0, index = 0, count = 0;
while ((count < 5) && (index
< N))
{
if (item
[index] > 0)
{
sum += item [index];
count ++;
}
index
++;
}
if (count < 5) System.out.println
("Too few positive entries.");
else System.out.println ("Sum: " + sum);
} // sumFivePositives
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.
// precondition: (n >= 0), loop invariant is product = x count
public double power ( double x, int n)
{
int count = 0; double product = 1;
// product = x n
while (count < n) do
{
// (count <
n) and (product = x n)
product = x * product;
// (count <
n) and (product = x (n+1))
count ++;
// (count <= n) and (product
= x n)
}
// (count = n) and (product = x n)
return product;
} // method power
// postcondition: x n returned
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.
// pre-condition: n >= 1, loop invariant: product = 1 * 2 * … * count.
public int factorial (int n)
{
int product = 1, count = 1;
while (count < n)
{
count ++;
product *= count;
}
return product;
} // method factorial
// post-condition: count = n, product = 1 * 2 * … * n