Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple recursive C++ program

Status
Not open for further replies.

Jedd24

Programmer
Apr 9, 2005
1
US
Hi, I'm working on a simple recursive C++ program to find the GCD (greatest common denominator) of two numbers. Its a really basic program, but then again I'm new to programming so I'm trying to learn the begginer concepts. Here is the problem I'm having. In the recursive function I have three IF statements. The first one will work correctly, however it will read both the second and the third, even if one does not apply. Here is a clip of the code to better explain it:
{
.
.
.
cout << "Enter first number";
cin >> x;
cout << "Enter second number";
cin >> y;

gcd(x, y);

return 0;

}

void gcd(int x, int y)
{
if ((x == 0 && y == 0) || (x < 0 || y < 0))
{
return;
}
if (y == 0)
{
cout << "The GCD is: " << x;
return;
}
if ((y > 0) && (x >= 0))
{
x = (x % y);
gcd(y, x);
cout << "The GCD is: " << x;
return;
}
}
What happens is, if y == 0, it will enter the second IF statement like it should. However, it will also enter the third IF statement and output that aswell. Same thing happens if the input applys to the third IF statement, it will still go through the second, even if y != 0. Ive tried quite a few things and nothing seems to work. Any info would be appreciated. Thank you.











 
You should try your program by hand, with a pen and paper, using two simple numbers, and see what happens. Then you will see why it does not give what you want it to give.

For example:

x=4, y=2
go in 3rd if
x=0 now
call GDC(2,0)
go to 2nd if
print as in 2nd if
return
print as in 3rd if
return

So, it does go in the 2nd if, but only in a further iteration.

Good luck!

Vincent
 
I would create a recursive function that returned the GCD of two numbers and then output that in the calling function.
That way the GCD function can be re-used if you want to use the GCD for something other than display.

eg
Code:
{
.
.
.
cout << "Enter first number";
cin >> x;
cout << "Enter second number";
cin >> y;

cout << cout << "The GCD is: " << GCD(x,y);
return 0;
}

int GCD(int x, int y)
{
    int nRetVal = 0//this can indicate an error somewhere
                   //as 0 can't be a factor of any number

    //do your tests and calculations

    else
        nRetval = GCD(y,x)
	
    return nRetVal
}

"If it could have gone wrong earlier and it didn't, it ultimately would have been beneficial for it to have." : Murphy's Ultimate Corollary
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top