Consider the following program fragment for reversing the digits in a given integer to obtain a new integer.
Let .
int n, rev;
rev = 0;
while(n > 0) {
rev = rev * 10 + n%10;
n = n/10;
}
The loop invariant condition at the end of the iteration is:
View worked solution
Answer: A
A loop invariant is a condition that holds true before and after each iteration of a loop.
Let the initial value of be represented as a sequence of digits: .
Let us trace the values of and at the end of the first few iterations:
- Before the loop starts ():
- At the end of the iteration ():
- At the end of the iteration ():
By induction, at the end of the iteration:
- The remaining number has its last digits removed:
- The variable contains the last digits of the original number in reverse order:
Both of these conditions must hold simultaneously (connected by an and operator).
Thus, the loop invariant at the end of the iteration is:
This matches Option A.
Free practice · Your answers on this page are not saved.
