Monday, 27 November 2017

C Program to find GCD

Write a C program to find GCD / HCF of two numbers.

#include<stdio.h>
int main()
{
    int gcd=1,min,a,b,i;
    printf("Enter Two Numbers: ");
    scanf("%d%d",&a,&b);
    min=(a<b)?a:b;
    for(i=1;i<=min;i++)
    {
        if(a%i==0 && b%i==0)
            gcd=i;
    }
    printf("%d",gcd);
}


Output: Enter Two Numbers: 4  10 ↵
              2

/* Explaination*/
/* Here we are using "min=(a<b)?a:b;" to choose the minimum of both the number entered and assigned it to min variable and then we will start from 1 and go to  the highest factor of both the number. The Highest factor will be GCD of both the number. */

No comments:

Post a Comment

Featured Post

TCS Latest Test Patern ( For On-Campus Drives )

Tata Consultancy Services is software services consulting company whose  headquarter is situated in Mumbai, India. It is the Asia’s larges...