Skip to content
Official PYQ · 2017

GATE CS 2017 Set 2 Q37 — Programming in C

Explain with AI

Consider the C program fragment below which is meant to divide xx by yy using repeated subtractions. The variables xx, yy, qq and rr are all unsigned int.

while (r >= y) {
    r=r-y;
    q=q+1;
}

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

Choose one option
View worked solution

Answer: C

To ensure that the loop terminates in a state satisfying the relation x==y⋅q+rx == y \cdot q + r, we can use the concept of loop invariants.

Let us define the loop invariant as I:x==y⋅q+rI: x == y \cdot q + r.

  1. Initialization: For the invariant to hold before the loop starts, we must initialize the variables such that x==y⋅q+rx == y \cdot q + r. If we set q=0q = 0 and r=xr = x, the relation becomes: y⋅0+x=xy \cdot 0 + x = x which is always true.
  2. Maintenance: During each iteration of the loop, let the new values of qq and rr be q′q' and r′r' respectively, where q′=q+1q' = q + 1 and r′=r−yr' = r - y. Substituting these into the invariant expression: y⋅q′+r′=y(q+1)+(r−y)=y⋅q+y+r−y=y⋅q+ry \cdot q' + r' = y(q + 1) + (r - y) = y \cdot q + y + r - y = y \cdot q + r Since the invariant holds before the iteration (y⋅q+r==xy \cdot q + r == x), it also holds after the iteration (y⋅q′+r′==xy \cdot q' + r' == x).
  3. Termination: For the loop to terminate, the loop condition r≥yr \ge y must eventually become false. Since rr is decremented by yy in each step, we must have y>0y > 0 to ensure rr strictly decreases and the loop terminates. If y=0y = 0, the loop would run infinitely.

Combining these requirements, we need (q==0) && (r==x) && (y>0)(q == 0) \ \&\& \ (r == x) \ \&\& \ (y > 0) before the execution of the loop.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions