GATE / CS ARCHIVE

GATE CSE 2025 SET 2 / QUESTION 33

GATE CSE 2025 Set 2 Q33

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

GATE 2025 Set 2, Q33 1 mark · NAT
Report issue

Control Flow & Loop Tracing

Question 33, GATE 2025: Find the integer printed by this C fragment:
int x=126,y=105;
do { if(x>y) x=x-y; else y=y-x; } while(x!=y);
printf("%d",x);
Tap to enlarge
Answer & solution

Official answer: 21

Step through it (21 steps)

Trace the pair (x,y) after each execution of the body:
(126,105) → (21,105) → (21,84) → (21,63) → (21,42) → (21,21).
At the first step x>y, so only x changes. Thereafter y>x until equality is reached, so y is reduced repeatedly by 21. The loop test sees x==y after the fifth iteration and stops. The printed x is 21.

This is the subtraction version of Euclid's algorithm. Replacing a larger positive integer by its difference with the smaller preserves the set of common divisors, and hence the gcd. At termination the two equal positive values must equal gcd(126,105)=21. Remember that a do-while executes the body before testing its condition; here the initial values differ, so that distinction does not alter the trace. Answer: 21.

Original paper, page 26 · Answer key