In this tutorial, we will learn the writing program in C to find the GCD of two numbers using recursion. In the previous tutorial, we have learnt to write the c program to calculate GCD without recursion.
Program in C to find GCD using recursion
#include <stdio.h>
int gcd(int num1, int num2)
{
if (num2 == 0)
return num1;
return gcd(num2, num1 % num2);
}
int main()
{
int num1, num2, maxNum;
printf("Find GCD or HCF of two numbers using recursion\n");
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
printf("GCD or HCF of numbers %d and %d is %d ", num1, num2, gcd(num1, num2));
return 0;
}
Output 1
Find GCD or HCF of two numbers using recursion
Enter the first number: 23
Enter the second number: 55
GCD or HCF of numbers 23 and 55 is 1
Output 2
Find GCD or HCF of two numbers using recursion
Enter the first number: 12
Enter the second number: 20
GCD or HCF of numbers 12 and 20 is 4
[wpusb]