GATE / CS ARCHIVE

GATE CSE 2017 SET 2 / QUESTION 37

GATE CSE 2017 Set 2 Q37

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2017 Set 2 paper

GATE 2017 Set 2, Q37 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 37, GATE 2017: Unsigned integers x,y,q,r are used for division by repeated subtraction: while(r>=y){r=r-y; q=q+1;}. Which initial condition guarantees termination and final x==y*q+r? A:(q==r)&&(r==0). B:(x>0)&&(r==x)&&(y>0). C:(q==0)&&(r==x)&&(y>0). D:(q==0)&&(y>0).
Tap to enlarge
Your answer
Answer & solution

Official answer: C

1. To preserve the intended division relation, use the invariant x=yq+r. Option C initializes q=0 and r=x, so the invariant holds before the loop. It also ensures y>0.

2. One iteration replaces r by r-y and q by q+1. Therefore y(q+1)+(r-y)=yq+r=x: the invariant is preserved. The guard r≥y prevents unsigned subtraction underflow.

3. Since y is positive, r decreases on every iteration and cannot decrease forever. At exit 0≤r<y, so q and r are the quotient and remainder. B leaves q unconstrained, D leaves r unconstrained, and A neither establishes the invariant for arbitrary x nor excludes y=0. C is the sufficient condition.

Original paper, page 14 · Answer key