Learn how to write a C program to calculate the Greatest Common Divisor (GCD) of two numbers. This tutorial covers recursive approach using Euclidean algorithm for finding the GCD, providing clear examples and explanations. Perfect for those new to C programming and looking to grasp fundamental mathematical algorithms.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
int main() {
int num1, num2;
printf("Enter two positive integers: ");
scanf("%d %d", &num1, &num2);
printf("GCD of %d and %d is %d.\n", num1, num2, gcd(num1, num2));
return 0;
}
Inside the gcd function:
- Recursive implementation of Euclidean algorithm to find the GCD of two numbers.
Inside the main() function:
- Two integer variables num1 and num2 are declared to store the input numbers.
- The user is prompted to enter two positive integers.
- The gcd function is called with the two numbers as arguments, and the result is printed.