C Program to Find G.C.D Using Recursion

This post helps to find G.C.D using recursion by C programming language.

C Program to Find G.C.D Using Recursion

#include<stdio.h>
int hcf(int a,int b);
int main()
{
    int c,d;
    printf("Enter the positive number:");
    scanf("%%d %%d", &c,&d);
    printf("G.C.D of %%d and %%d are:%%d",c,d,hcf(c,d));
    return 0;
}
//function calling and calculation process
int hcf(int a,int b)
{
    if(b!=0)
        return hcf(a,a%%b);   
    else
        return a;
}

Output

Explanation

In this C program, we find the G.C.D(greatest common divisor) value using recursion(repeats itself). The program starts with the main function where the user is allowed to enter the values for the variables initialized.

int main()
{
    int c,d;
    printf("Enter the positive number:");
    scanf("%%d %%d", &c,&d);
    printf("G.C.D of %%d and %%d are:%%d",c,d,hcf(c,d));
    return 0;
}

We here use the function named HCF, where this function is called to do the particular calculation. Using the if-else condition we do the calculation and the return the value needed in the variable namely “a”

//function calling and calculation process
int hcf(int a,int b)
{
    if(b!=0)
        return hcf(a,a%%b);   
    else
        return a;
}

Now after the calculation, we get our desired output.