Calculate G.C.D using Recursion in C

Exercise:

Write a C Program to find G.C.D using recursion.

Click Here to View the Solution!
#include <stdio.h>
int GCD(int num1, int num2);

int main() {
    int num1, num2;
    printf("Enter two positive integers: ");
    scanf("%d %d", &num1, &num2);
    printf("G.C.D of %d and %d is %d.", num1, num2, GCD(num1, num2));
    return 0;
}

int GCD (int num1, int num2) {
    if (num2 != 0)
        return GCD(num2, num1 % num2);
    else
        return num1;
}
Click Here to View the Output!
Enter two positive integers: 84 48
G.C.D of 84 and 48 is 12.
Click Here to View the Explanation!
  • This program is used to calculate the GCD of a number by using recursion.
  • A function hcf(int num1, int num2) is initially declared.
  • In main(), the program requests the user to enter two positive integers and stores it in the variables num1 and num2 using the scanf() function.
  • Outside main(), the hcf function is initialized which will take num1 and num2 as its parameters.
  • It will check if value of num2 is not equal to 0 then calculate the modulus of num1 with num2 in a recursive call.
  • When num2 becomes equal to 0, the recursive calls end and the output is returned to the main() which will print the GCD of the two numbers.
%d bloggers like this: