C Program to Find GCD Using Functions

Subject: PPS (Programming for Problem Solving)

Contributed By: Sanjay

Created At: February 3, 2025

Question:


Write a C Program to Find GCD Using Functions

Explanation Video:

Custom Image

Explanation:

 

  1. GCD (Greatest Common Divisor) is the largest number that divides two numbers without leaving a remainder.

  2. The recursive function gcd(a, b) follows Euclid's algorithm: gcd(a, b) = gcd(b, a % b).

  3. The base case is when b == 0, returning a.

Source Code:
#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 numbers: ");
    scanf("%d %d", &num1, &num2);
    printf("GCD of %d and %d is %d\n", num1, num2, gcd(num1, num2));
    return 0;
}
Input:
Enter two numbers: 24 36
Output:
GCD of 24 and 36 is 12
Share this Article & Support Us:
Status
printf('Loading...');