All mock tests are FREE till 31 December — register to save your progress

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?

Pick an option to check yourself, or open the answer below.

Show answer & explanation

Correct answer: B. 2

Explanation

This is Euclid's subtraction method, so it prints gcd(128, 110). 128 − 110 = 18; then y reduces 110 → 92 → 74 → 56 → 38 → 20 → 2; then x reduces 18 → 16 → … → 2. When x = y = 2 the loop stops. Output: 2.

More Programming Languages and Computer Graphics questions