int x = 126, y = 105; do { if (x > y) x = x - y; else y = y - x; } while (x !=…

2025

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)

Attempted by 230 students.

Show answer & explanation

Correct answer: 21

This code uses the subtraction form of the Euclidean algorithm to compute the greatest common divisor (GCD) of 126 and 105.

  • Initial values: x = 126, y = 105

  • Iteration 1: x > y, so x = x - y = 126 - 105 = 21. Now x = 21, y = 105.

  • Iteration 2: x < y, so y = y - x = 105 - 21 = 84. Now x = 21, y = 84.

  • Iteration 3: y = y - x = 84 - 21 = 63. Now x = 21, y = 63.

  • Iteration 4: y = y - x = 63 - 21 = 42. Now x = 21, y = 42.

  • Iteration 5: y = y - x = 42 - 21 = 21. Now x = 21, y = 21.

  • Loop ends because x == y.

Therefore the program prints 21. This is the GCD of 126 and 105.

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir