Question Details

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 ______.

Show Answer

Correct Answer :

21

Solution :

The correct answer is 21.

Let's trace the execution of this C code segment step-by-step to understand why the output is 21.

The given code implements the subtraction-based version of Euclid's algorithm for finding the Greatest Common Divisor (GCD) of two integers, x and y.

Initially, the variables are initialized as follows:
x=126
y=105

The code uses a do-while loop, which will execute the body first and then check the condition while (x != y).

Iteration 1:
We enter the loop with x=126 and y=105.
We check the condition: if (x > y). Since 126 is greater than 105, this condition is true.
We update x:
x=x-y=126-105=21.
At the end of the iteration, we check the loop condition: while (x != y). Since x=21 and y=105, they are not equal, so the loop continues.

Iteration 2:
We enter the loop with x=21 and y=105.
We check the condition: if (x > y). Since 21 is not greater than 105, the else branch is executed.
We update y:
y=y-x=105-21=84.
We check the loop condition: while (x != y). Since x=21 and y=84 are not equal, the loop continues.

Iteration 3:
We enter the loop with x=21 and y=84.
Since x is not greater than y, we update y:
y=y-x=84-21=63.
Since x=21 and y=63 are not equal, the loop continues.

Iteration 4:
We enter the loop with x=21 and y=63.
Since x is not greater than y, we update y:
y=y-x=63-21=42.
Since x=21 and y=42 are not equal, the loop continues.

Iteration 5:
We enter the loop with x=21 and y=42.
Since x is not greater than y, we update y:
y=y-x=42-21=21.
We check the loop condition: while (x != y). Since x=21 and y=21 are now equal, the loop terminates.

After exiting the loop, the program prints the value of x using printf("%d", x);.
Since the final value of x is 21, the output printed to the console is 21.

Unlock Our Free Library

Access expert-curated educational resources and study materials—completely free.

Ask AI Tutor
5 left
Q1 View Question & Options
AI Tutor is solving this question...
Reading question context & options...