Loop Invariance Worksheet #1

In problems 1 - 4, decide which answer best describes the loop invariant.

 1. ``` int count = 0; temp = 1; while (count < number) {   count++;     temp = temp * base; } ``` A. count < number B. temp equals base^(count - 1) C. temp equals count + 1 D. temp equals base^count E. temp equals base^(count + 1) 2. ``` int count = 1; int temp = number; while (temp >= 10) {   count ++;     temp = temp / 10; } ``` A. temp equals number B. number equals count` x` temp C. count equals number / temp D. temp >= 10 E. (numdigits in number) - (numdigits in temp) + 1 equals count 3. ``` int Mystery(int num, int max) {   int temp = 0, index = 0;     while (index < max)     {   index++;       temp += num;     }     return temp; } ``` A. temp equals index ` x` num B. temp equals (index - 1) ` x` num C. temp equals (index + 1) ` x` num D. temp equals index - 1 E. temp equals index 4. ``` const MAX = int place = 0; apvector items (MAX);       : int sum = items[0]; while (place < MAX - 1) {   place++;     sum = sum + items[place]; } ``` A. sum contains the value in items[0] B. sum contains the sum of the values in items[1] to items[place] C. sum contains the sum of the values in items[0] to items[MAX] D. sum contains the sum of the values in items[0] to items[place] E. place < MAX
5. Use the given loop invariant to help you fill in the blanks in the code below:

```	int Power(int base, int exp)
//  calculates base to the exp power
{
int i = _____;
int j = _____;
int k = _____;
while (____________________)
// invariant:  i * j^k = base^ exp
{
_____________________;	// gets closer
_____________________;	// restore invariant
}
return __________;
}
```

Continue to:  Unit 4  / Prev  / Next