edited by
14,024 views
36 votes
36 votes

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+1;
}

Which of the following conditions on the variables $x, y, q$ and $r$ before the execution of the fragment will ensure that the loop terminated in a state satisfying the condition $x==(y*q + r)$?

  1. $(q==r) \ \&\& \ (r==0)$
  2. $(x>0) \ \&\&  \ (r==x) \ \&\& \ (y>0)$
  3. $(q==0) \ \&\& \ (r==x) \ \&\& \ (y >0)$
  4. $(q==0) \ \&\& \ (y>0)$
edited by

6 Answers

Best answer
52 votes
52 votes

Here, $x == ( y*q + r )$ says $q =$ quotient and $r =$  remainder.

To divide a number with repeated subtraction, quotient should be initialized to $0$ and should be incremented for each subtraction.

Initially $q=0 \Rightarrow r = x$.

$\therefore$ Initial conditions should be C] $(q == 0) \ \&\& \ (r == x) \ \&\& \ (y > 0)$.

edited by
4 votes
4 votes

$ x==(y∗q+r)$

I don't think it is hard to make an intuitive guess here that

x = number to be divided.

y = divisor.

q = quotient.

r = remainder.

 

Option A says set quotient == remainder in the beginning. It doesn't serve any good to division.


Option B says x > 0. Why? We can legally divide 0 by anything. So, if x === 0, division should have no issues.


Option C says set quotient == 0, remainder == number to be divided, and divisor > 0.

So far so good.

Trace out the code. (Keep $451 == 10 * 45 + 1$ in mind)

  • In each subtraction, we're reducing the size of remainder by divisor. That's technically what happens with each division.
     
  • Every time we successfully subtract, quotient increments. Good.

This Option is correct.


Option D doesn't specify for remainder == number to be divided in the beginning of the program, but division by repeated subtraction wants that.

3 votes
3 votes
option c
Answer:

Related questions