The following function computes for positive integers and .
int exp (int X, int Y) {
int res =1, a = X, b = Y;
while (b != 0) {
if (b % 2 == 0) {a = a * a; b = b/2; }
else {res = res * a; b = b - 1; }
}
return res;
}
Which one of the following conditions is TRUE before every iteration of the loop?
View worked solution
Answer: C
A loop invariant is a condition that remains true before and after each iteration of a loop. Let us verify the condition :
- Initialization: Before the first iteration, , , and . Substituting these values into the expression: The condition holds true initially.
- Maintenance: Assume the condition holds before an iteration. Let , , and be the values after the iteration:
- Case 1 ( is even): , , and .
- Case 2 ( is odd): , , and .
- Termination: When the loop terminates, . The invariant gives: This correctly yields the final computed value of .
Thus, the correct loop invariant is .
Free practice · Your answers on this page are not saved.
