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.
{
.
.
.
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.