int x=126,y=105;
do {
if(x>y) x=x-y;
else y=y-x;
} while(x!=y);
printf("%d",x);The output of the given C code segment is ________. (Answer in integer)
int x=126,y=105;
do {
if(x>y) x=x-y;
else y=y-x;
} while(x!=y);
printf("%d",x);The output of the given C code segment is ________. (Answer in integer)
ANSWER
The output printed is 21.
Official answer: 21Source: Official answer key, GATE 2025 CS2 (IIT Roorkee)
Since it is a do-while loop, the body runs once before the condition x!=y is checked.
Initial: x=126, y=105.
Iteration 1: x>y (126>105) is true, so x=x-y=126-105=21. Now x=21, y=105. Check x!=y: 21!=105 is true, so the loop continues.
Iteration 2: x>y (21>105) is false, so y=y-x=105-21=84. Now x=21, y=84. Check x!=y: true, continue.
Iteration 3: x>y (21>84) is false, so y=y-x=84-21=63. Now x=21, y=63. Check x!=y: true, continue.
Iteration 4: x>y (21>63) is false, so y=y-x=63-21=42. Now x=21, y=42. Check x!=y: true, continue.
Iteration 5: x>y (21>42) is false, so y=y-x=42-21=21. Now x=21, y=21. Check x!=y: 21!=21 is false, so the loop terminates.
The loop is the subtraction-based Euclidean algorithm, so the terminal value of x equals gcd(126,105).
gcd(126,105): 126=2·3²·7 and 105=3·5·7, so gcd=3·7=21 — matching the trace.
printf("%d",x) prints x=21, which is the required output.
KEY IDEA
This do-while loop is the subtraction-based (slow) Euclidean algorithm: it repeatedly replaces the larger of x, y by their difference until x equals y, at which point both variables hold gcd(x, y).
WATCH OUT FOR
Treating it as a while loop and skipping the first pass's guaranteed subtraction, or stopping the trace as soon as x first becomes 21 (after iteration 1) without continuing until x!=y actually turns false — x stays 21 throughout, but y still needs four more iterations to reach 21.
From the GATE 2025 CS2 paper. Every question of this paper · Download the full paper · All 7 C basics questions, with notes