C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Functions in C

GCD using function

GCD (Greatest Common Divisor) is one of the most common and useful mathematical operations in C programming.

C Program: GCD using function

C

#include <stdio.h>

 

// Function declaration

int gcd(int a, int b);

 

int main() {

    int num1, num2, result;

 

    // Input two numbers

    printf("Enter two positive integers: ");

    scanf("%d %d", &num1, &num2);

 

    // Validate input

    if (num1 <= 0 || num2 <= 0) {

        printf("Please enter positive integers only.\n");

    } else {

        // Function call

        result = gcd(num1, num2);

        printf("GCD of %d and %d is %d\n", num1, num2, result);

    }

 

    return 0;

}

 

// Function definition using Euclidean algorithm

int gcd(int a, int b) {

    while (b != 0) {

        int temp = b;

        b = a % b;

        a = temp;

    }

    return a;

}

Output

 
OUTPUT 1 :
Enter two positive integers: 48 18
GCD of 48 and 18 is 6

OUTPUT 2 :

 

Explanation

  1. Function gcd(int a, int b)
    • Uses the Euclidean algorithm:

                     gcd(a, b) = gcd(b, a % b)

                     until b becomes 0.

  1. Loop process
    • Example: a = 48, b = 18

                  gcd(48, 18)

                   → gcd(18, 48 % 18) = gcd(18, 12)

                   → gcd(12, 18 % 12) = gcd(12, 6)

                   → gcd(6, 12 % 6) = gcd(6, 0)

                   → GCD = 6