Consider the following piece of C programming code:
int x = 128, y = 110 ;
do
{
if(x > y)
x = x - y
else
y = y - x;
} while(x! = y)
printf("%d",x);
Which one will be the output?
Solution
The correct answer is Option 2) 2
Given code (formatted)
int x = 128, y = 110;
do {
if (x > y)
x = x - y;
else
y = y - x;
} while (x != y);
printf("%d", x);
Key Points
- The loop implements the subtractive Euclidean algorithm for the greatest common divisor (GCD).
- At each step, the larger of
x and y is reduced by the smaller. This preserves gcd(x, y).
- The loop stops when
x == y; at that point both variables equal gcd(original x, original y).
do { ... } while (x != y); ensures the body executes at least once.
Step-by-step dry run
| Iteration |
x |
y |
Action |
| start |
128 |
110 |
x>y ⇒ x=x−y=18 |
| 1 |
18 |
110 |
y=y−x=92 |
| 2 |
18 |
92 |
y=74 |
| 3 |
18 |
74 |
y=56 |
| 4 |
18 |
56 |
y=38 |
| 5 |
18 |
38 |
y=20 |
| 6 |
18 |
20 |
y=2 |
| 7 |
18 |
2 |
x=16 |
| 8 |
16 |
2 |
x=14 |
| 9 |
14 |
2 |
x=12 |
| 10 |
12 |
2 |
x=10 |
| 11 |
10 |
2 |
x=8 |
| 12 |
8 |
2 |
x=6 |
| 13 |
6 |
2 |
x=4 |
| 14 |
4 |
2 |
x=2 |
| stop |
2 |
2 |
x==y ⇒ exit loop |
End of loop
- Now
x == y == 2, which equals gcd(128, 110).
printf("%d", x); prints 2.
Important notes
- Because
x and y stay positive and strictly decrease when unequal, the loop must terminate.
- Using repeated subtraction is equivalent to the usual Euclidean algorithm with modulo, just slower.