Signup/Sign In

C Program To Find GCD Of The Given Numbers Using Recursion

Learn C Language tutorial

Logic To Find GCD Of The Given Numbers Using Recursion:

  • Get the inputs from the user and store it in the variables x and y,
  • The function gcd() is used to find the gcd of the given variables,
  • The while loop is used to check the value of x is not equal to y, if so execute,
  • else returns the value of x, another if-else block is used to check the value of x is greater than y,
  • If the condition is true, returns two values, else executes another statement,
  • Prints the GCD of the given numbers.

Program To Find GCD Of The Given Numbers Using Recursion:

#include <stdio.h>
 
int gcd(int, int);
 
int main()
{
    int x, y, GCD;
 
    printf("Enter the two numbers to find their GCD: ");
    scanf("%d%d", &x, &y);
    GCD = gcd(x, y);
    printf("The GCD Of The Given Numbers is %d.\n",  GCD);
}
 
int gcd(int x, int y)
{
    while (x != y)
    {
        if (x > y)
        {
            return gcd(x - y, y);
        }
        else
        {
            return gcd(x, y - x);
        }
    }
    return x;
}

Output:

GCD