The GATE Grind

GATE 2017 CS (CS2) – Question 47

Programming and Data Structures · Programming in C · 2 marks · Multiple choice

The following fragment divides x by y using repeated subtraction. All variables x,y,q,r are unsigned int. Which precondition ensures termination with x == y*q + r?

while (r >= y) {
    r=r-y;
    q=q+1;
}
  1. (q == r) && (r == 0)
  2. (x > 0) && (r == x) && (y > 0)
  3. (q == 0) && (r == x) && (y > 0)
  4. (q == 0) && (y > 0)

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: (C) (q == 0) && (r == x) && (y > 0)

Explanation

Initialize q=0,r=x so x=yq+r holds. Each iteration subtracts y from r and adds one to q, preserving this invariant. Positive y makes r strictly decrease without underflow because the guard checks r≥y. Termination then gives 0≤r<y and the required quotient identity. All conditions are present only in C.

More Programming in C questions

All Programming in C questions →