Print GCD of Two Integers in C
Computations and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. So today we’re going to write a program to print GCD of Two Integers in C.
What’s The Approach?
- Let us consider
aandbto be the two Integers to find HCF of.
- Firstly we’ll find the gcd of these two numbers, i.e, by using a condition where if
abecomes zero we’ll returnband vice versa.
- However, if that’s not the case then we’ll simply recursively
return b % aif b is greater and vice versa if a is greater no. That way we’ll get a gcd as output.
Also Read: How To Print Hello World in C
C Program To Print GCD of Two Integers
Input:
a = 98, b = 56
Output:
GCD of 98 and 56 is 14
// C program to find HCF/GCD of two numbers
#include <stdio.h>
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// Driver program
int main()
{
int a = 98, b = 56;
printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
return 0;
}

