The GATE Grind

GATE 2025 CS (CS2) – Question 33

Programming and Data Structures · Programming in C · 1 mark · Numerical answer

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)

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 21

Explanation

This is the subtractive Euclidean algorithm for the gcd.

xyaction
126105$x>y$: $x=21$
21105$y>x$: $y=84$
2184$y=63$
2163$y=42$
2142$y=21$
2121$x=y$: stop

It prints $x=\gcd(126,105)=\mathbf{21}$.

More Programming in C questions

All Programming in C questions →