Easy Tutorial
❮ C Standard Library String H C Examples Remove Characters String ❯

C Language Example - Finding the Greatest Common Divisor of Two Numbers

C Language Examples

The user inputs two numbers, and the program calculates the greatest common divisor of these two numbers.

Example - Using for and if

#include <stdio.h>

int main()
{
    int n1, n2, i, gcd;

    printf("Enter two positive integers separated by a space: ");
    scanf("%d %d", &n1, &n2);

    for(i=1; i <= n1 && i <= n2; ++i)
    {
        // Check if i is the greatest common divisor
        if(n1%i==0 && n2%i==0)
            gcd = i;
    }

    printf("The greatest common divisor of %d and %d is %d", n1, n2, gcd);

    return 0;
}

Running Result:

Enter two positive integers separated by a space: 81 153
The greatest common divisor of 81 and 153 is 9

Example - Using while and if

#include <stdio.h>
int main()
{
    int n1, n2;

    printf("Enter two numbers separated by a space: ");
    scanf("%d %d",&n1,&n2);

    while(n1!=n2)
    {
        if(n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }
    printf("GCD = %d",n1);

    return 0;
}

Running Result:

Enter two numbers separated by a space: 81 153
GCD = 9

Example - Applicable to Positive and Negative Numbers

#include <stdio.h>

int main()
{
    int n1, n2;

    printf("Enter two numbers separated by a space: ");
    scanf("%d %d",&n1,&n2);

    // Convert negative numbers to positive
    n1 = ( n1 > 0) ? n1 : -n1;
    n2 = ( n2 > 0) ? n2 : -n2;

    while(n1!=n2)
    {
        if(n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }
    printf("GCD = %d",n1);

    return 0;
}

Running Result:

Enter two numbers separated by a space: 81 -153
GCD = 9

Example - Using Recursion

#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
   int n1, n2;
   printf("Enter two positive integers: ");
   scanf("%d %d", &n1, &n2);

   printf("The greatest common divisor of %d and %d is %d", n1, n2, hcf(n1,n2));
   return 0;
}

int hcf(int n1, int n2)
{
    if (n2 != 0)
       return hcf(n2, n1%n2);
    else 
       return n1;
}

C Language Examples

❮ C Standard Library String H C Examples Remove Characters String ❯