-
Consider the C program fragment below which is meant to divide x by y using repeated subtractions. The variables x, y, q and r are all unsigned int.
while (r > = y) {
r = r – y;
q = q + I;
}
Which of the following conditions on the variables x, y, q and r before the execution of the fragment will ensure that the loop terminates in a state satisfying the condition x == (y q + r) *?
-
- (q == r) && (r == 0)
- (x > 0) && (r == x) && (y > 0)
- (q == 0) && (r == x)&& (y > 0)
- (q == 0) && {y > 0)
- (q == r) && (r == 0)
Correct Option: C
The given programe is:
While (r > = y)
{
r = r – y; (/*statement 1*/)
q = q + 1; (/* statement 2*/)
}
Condition given
X = (Y*q + r)
Let q = quotient and r = remainder.
So to divide a number with repeated subtraction, quotient should be initialized to zero and should be incremented for each subtraction.
So, initially q = 0, then
X = (Y*0 + r)
(r = X)
Since y is subtracted from reach time in given code. In, statement one and q incremented by 1, to avoid undefined behavior. In statement two and the value of y should be greater than zero.
Therefore (q = = 0) & & (r = = X) & & (y > 0).
Hence, option (c) is correct.