Why does this output 5?

#include <iostream>
using namespace std;

int mystery( int x = 3 , int y= 0 )
{
if ( y == 0 )
return x;
else if ( y < 0 )
return mystery( x - 1, y + 1 );
else
return mystery( x + 1, y - 1 );
} // end function mystery What is the output of: cout << mystery( 3, 2 ) << endl;

int main()
{
cout << mystery(3,2) <<endl;
system("pause");
return 0;

}
The mystery function recursively calls itself, adding 1 to x and subtracting 1 from y until y = 0, at which point it returns x.

[Edit - the above is for the positive y case - for negative y it does the opposite, but the result is still ...]

Effectively it adds y to x and returns the result.

If you break it down to steps, writing down the values of x and y at each, and follow the code execution on paper, you'll see what's going on.

Cheers,

Jim
Last edited on
Topic archived. No new replies allowed.