Loop · Programming in C
17 questions · asked in 12 of 27 years (2000–2026)
MCQ 13 · MSQ 1 · NAT 31-mark 7 · 2-mark 10
2000Questions per year2026
Questions 16–17 of 17
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: Answer: (A)
Take , for example with . Each pass moves the last digit of to the end of and removes it from .
After iteration 1: and .
After iteration 2: and .
In general, after iterations, and . For this gives the starting values and (no digits yet), and for it gives and . So this condition holds before the loop, after every iteration and at the end.
Why the others fail:
(B) puts the digits of in the wrong order: holds first, not , and its first part does not say what is.
(D) is true only at the start ( is the full number) or at the end ( is the full reversal); after iteration 1 of , and , so neither part holds.
(C) says nothing about the digits, and it fails too: for , after iteration 1, .
Answer: (A)
After iteration 1: and .
After iteration 2: and .
In general, after iterations, and . For this gives the starting values and (no digits yet), and for it gives and . So this condition holds before the loop, after every iteration and at the end.
Why the others fail:
(B) puts the digits of in the wrong order: holds first, not , and its first part does not say what is.
(D) is true only at the start ( is the full number) or at the end ( is the full reversal); after iteration 1 of , and , so neither part holds.
(C) says nothing about the digits, and it fails too: for , after iteration 1, .
Answer: (A)
Consider the following C function.
float f(float x, int y)
{
float p, s; int i;
for (s=1, p=1, i=1; i < y; i ++)
{
p*= x/i;
s+=p;
}
return s;
} For large values of y, the return value of the function f best approximatesAnswer: (B)
Here is a simpler form of the given program:
float f(float x, int y) {
float p=1, s=1;
int i;
for (i=1; i<y; i++) {
p = p * (x/i);
s = s + p;
}
return s;
}
We can move the initialization out of the for loop, because the loop does not check any condition on .
So, option B is the answer.
Keep practising