Thursday, April 2, 2020

c program to calculate the gcd of two numbers

C program to calculate the gcd of two numbers

  • The HCF or GCD  of two integers is the largest integer that can exactly divided both numbers.
  • There are many ways to find the greatest common divisor in C program.
#include 
int main()
{
    int n1, n2, i, gcd; // integer variables

    printf("Enter two integers: "); // User enter two integers 
    scanf("%d %d", &n1, &n2); // storing integer variables

    for(i=1; i <= n1 && i <= n2; ++i) // for loop 
    {
        // Checks if i is factor of both integers
        if(n1%i==0 && n2%i==0)
            gcd = i;
    }

    printf("G.C.D of %d and %d is %d", n1, n2, gcd); // final result display

    return 0;
}
Output

Enter two integer = 81 -153
GCD = 9 
  • In this program, two integer is entered by the user are stored in variable n1 and  n2 . Then, for loop is iterated until i is less than n1 and n2. 
  • In each iterated,  if both n1 and n2  are exactly divided by i the value of i is assigned to GCD

Happy Coding  

Location: Pakistan

0 comments:

Post a Comment

Recent Posts