Question

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)

Official answer and solution
Official answer
21
From
Official GATE 2025 answer key

Solution

Recognize the loop as Euclid's subtraction algorithm for gcd⁡(126,105)\gcd(126, 105).

The do-while loop repeatedly subtracts the smaller variable from the larger variable until x == y, which computes gcd⁡(126,105)\gcd(126, 105):

  • Start: (x,y)=(126,105)(x, y) = (126, 105)
  • Iteration 1: x=126−105=21  ⟹  (21,105)x = 126 - 105 = 21 \implies (21, 105)
  • Iterations 2 to 5: yy decreases by 2121 four times (105→84→63→42→21105 \rightarrow 84 \rightarrow 63 \rightarrow 42 \rightarrow 21).
  • Now x=y=21x = y = 21, the loop terminates, and printf outputs 21.
Final answer

21

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2025 Computer Science and Information Technology - Session 2 (CS2)
Question
33 of 65
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.