GATE / CS ARCHIVE

GATE CSE 2015 SET 1 / QUESTION 65

GATE CSE 2015 Set 1 Q65

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2015 Set 1 paper

GATE 2015 Set 1, Q65 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 65, GATE 2015: For positive integers x,y: q:=0; r:=x; while r≥y do {r:=r−y; q:=q+1}. Which postcondition holds? A r=qx+y and r<y; B x=qy+r and r<y; C y=qx+r and 0<r<y; D q+1<r−y and y>0.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Prove the invariant x=qy+r by initialization and preservation: (q+1)y+(r−y)=qy+r. The guard ensures subtracting y never makes r negative. Since positive y decreases r at every step, the loop terminates and the false guard gives r<y. Therefore q is the integer quotient and r the remainder with 0≤r<y. A remainder may be zero, so a strict lower bound such as that in C would be wrong.

Solution: Initially q=0, r=x, so x=qy+r. Each iteration replaces r by r−y and q by q+1, preserving that invariant. Positive y decreases nonnegative r on every iteration; termination gives 0≤r<y. Hence the listed postcondition x=qy+r and r<y is B; the full invariant also supplies the nonnegative lower bound.

Original paper, page 25 · Answer key