Monday, September 12, 2011

GCD or HCF of two numbers

Q. Write a C program for finding GCD of two given numbers.

Ans.

 /*c program for finding GCD/HCF of two numbers*/
 #include<stdio.h>
 #include<conio.h>
 int main()
 {
  int n1,n2,rem;
  printf("Enter first number : ");
  scanf("%d",&n1);
  printf("Enter second number : ");
  scanf("%d",&n2);
  if(n2>n1)
  {
    n1=n1+n2;
    n2=n1-n2;
    n1=n1-n2;
  }
  do{
      rem=n1%n2;
      n1=n2;
      n2=rem;
    }while(rem!=0);
  printf("\nGCD of two number is %d",n1);
  getch();
  return 0;
 }

/************** OUTPUT ***************
Enter first number : 65
Enter second number : 45


GCD of two number is 5
**********************************/

No comments:

Post a Comment