Skip to content
Official PYQ · 2025

GATE CS 2025 Set 2 Q23 — Programming in C

Explain with AI
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)

View worked solution

Answer: 21:21

The given C code segment implements the subtraction-based Euclidean algorithm to compute the Greatest Common Divisor (GCD) of two positive integers xx and yy.

Let's trace the execution of the do-while loop step-by-step with initial values x=126x = 126 and y=105y = 105:

  1. Iteration 1:
    • Since x>yx > y (126>105126 > 105), we update x=x−y=126−105=21x = x - y = 126 - 105 = 21.
    • Now, x=21x = 21 and y=105y = 105.
    • Loop condition check: x≠yx \neq y (21≠10521 \neq 105) is true. Loop continues.
  2. Iteration 2:
    • Since x>yx > y (21>10521 > 105) is false, we update y=y−x=105−21=84y = y - x = 105 - 21 = 84.
    • Now, x=21x = 21 and y=84y = 84.
    • Loop condition check: x≠yx \neq y (21≠8421 \neq 84) is true. Loop continues.
  3. Iteration 3:
    • Since x>yx > y (21>8421 > 84) is false, we update y=y−x=84−21=63y = y - x = 84 - 21 = 63.
    • Now, x=21x = 21 and y=63y = 63.
    • Loop condition check: x≠yx \neq y (21≠6321 \neq 63) is true. Loop continues.
  4. Iteration 4:
    • Since x>yx > y (21>6321 > 63) is false, we update y=y−x=63−21=42y = y - x = 63 - 21 = 42.
    • Now, x=21x = 21 and y=42y = 42.
    • Loop condition check: x≠yx \neq y (21≠4221 \neq 42) is true. Loop continues.
  5. Iteration 5:
    • Since x>yx > y (21>4221 > 42) is false, we update y=y−x=42−21=21y = y - x = 42 - 21 = 21.
    • Now, x=21x = 21 and y=21y = 21.
    • Loop condition check: x≠yx \neq y (21≠2121 \neq 21) is false. The loop terminates.

After the loop terminates, the printf statement prints the value of xx, which is 21 (which is indeed GCD(126,105)\text{GCD}(126, 105)).

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions