C Program to Find GCD of Two Numbers Using Functions

Here we will write a C program to find the GCD of two numbers using functions. Previously we have already created a program to find the GCD of two numbers without using functions.

The GCD (greatest common divisor), also called the greatest common factor, of two numbers, is the largest number that divides both of them. For example, 4 is the GCD of numbers 12 and 20.

In this program, we will define a function to find the GCD of two numbers. To find the GCD of two numbers, loops are needed to execute the same logic multiple times. Prerequisites for this program:- Introduction to Function in C, User-defined Functions in C, C Program Using Functions Example

C program to find GCD of two numbers using functions

Program description:- Write a C program to find GCD of two numbers by defining a user-defined function.

#include<stdio.h>
int gcd(int a, int b);

int main()
{
  int num1, num2;

  printf("Enter two numbers : ");
  scanf("%d %d",&num1, &num2);

  int result = gcd(num1, num2);
  printf("The GCD of %d and %d = %d", num1, num2, result);

  return 0;
}

// User-defined function to find gcd of two numbers
int gcd(int a, int b)
{
  int hcf;
  for(int i=1; i<=a && i<=b; i++)
  {
    if(a%i==0 && b%i==0)
    {
      hcf = i;
    }
  }
  return hcf;
}

Output for the different test-cases:-

Enter two numbers : 12 20
The GCD of 12 and 20 = 4

Enter two numbers: 20 100
The GCD of 20 and 100 = 20

The user-defined function gcd calculates the greatest common divisor of the two numbers. The iteration starts with the value i=1. The gcd must be less than or equal to both numbers, so the condition of for loop is, i<=a && i<=b. If the number (value of variable i) can divide both numbers a and b then, it is the hcf of the numbers.

Finally, the result is returned back to the caller function, and the result is displayed to the screen.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply