Monday, September 24, 2012

Recursive program for finding tha greatest common divisor.

greatest common divisor(GCD) or HCF highest common factor....

#include<iostream.h>
#include<conio.h>
#include<process.h>
void hcf(int,int);
void main()
{
int a,b,c;
clrscr();
cout<<"Enter two numbers\n";
cin>>a>>b;
hcf(a,b);
getch();
}
void hcf(int a,int b)
{
int rem;
if(b>0)
{
rem=a%b;
a=b;
b=rem;
hcf(a,b);  //recursive function call for greatest common factor
}
cout<<" The GCD is\t"<<a;
getch();
exit(0);
}

method 2
#include<iostream.h>
#include<conio.h>
int gcd(int,int);
void main()
{
int a,b,c;
clrscr();
cout<<"Enter two numbers\n";
cin>>a>>b;
c=gcd(a,b);
cout<<"The Greatest Common Divisor is \t"<<c;
getch();
}
int gcd(int n,int m)
{
if(n%m== 0)
{
 return m;
 }
 else
 return gcd(m,n%m);
 }

what is recursion in c++?

Recursion, in any programming language, refers to, most commonly, a call to a function inside that function, (i.e a function calling itself) .


No comments:

Post a Comment