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 variablesnum1
andnum2
using thescanf() function
. - Outside
main()
, thehcf function
is initialized which will takenum1
andnum2
as its parameters. - It will check if value of
num2
is not equal to 0 then calculate the modulus ofnum1
withnum2
in a recursive call. - When
num2
becomes equal to 0, the recursive calls end and the output is returned to themain()
which will print the GCD of the two numbers.