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 ______.
Correct Answer :
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, and .
Initially, the variables are initialized as follows:
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 and .
We check the condition: if (x > y). Since 126 is greater than 105, this condition is true.
We update :
.
At the end of the iteration, we check the loop condition: while (x != y). Since and , they are not equal, so the loop continues.
Iteration 2:
We enter the loop with and .
We check the condition: if (x > y). Since 21 is not greater than 105, the else branch is executed.
We update :
.
We check the loop condition: while (x != y). Since and are not equal, the loop continues.
Iteration 3:
We enter the loop with and .
Since is not greater than , we update :
.
Since and are not equal, the loop continues.
Iteration 4:
We enter the loop with and .
Since is not greater than , we update :
.
Since and are not equal, the loop continues.
Iteration 5:
We enter the loop with and .
Since is not greater than , we update :
.
We check the loop condition: while (x != y). Since and are now equal, the loop terminates.
After exiting the loop, the program prints the value of using printf("%d", x);.
Since the final value of is 21, the output printed to the console is 21.
Access expert-curated educational resources and study materials—completely free.
Create, conduct, and manage professional online assessments with Mindyard. Perfect for teachers and institutes.
Copyright © 2026 Mindyard. All Rights Reserved.