-
Mar 25th, 2007, 09:43 PM
#1
Thread Starter
Fanatic Member
Recursion
So I have this recursive function:
Code:
int test(int x, int y)
{
if (x==y)
return x;
else if (x > y)
return (x+y);
else
return test(x+1, y-1);
}
I tried to step through it...but I just can't wrap my brain around recursion, and when I run it....its only returning the y, such as for example, test(3, 9) it returns 8.
Why?
-
Mar 26th, 2007, 04:40 AM
#2
Frenzied Member
Re: Recursion
the code as is should return 6... i suggest putting code to report the values of x and y at the top of the function
-
Mar 26th, 2007, 05:12 AM
#3
Re: Recursion
That's a bad subject for recursion; a loop would suffice.
You should only use recursion when variables change with each iteration. The only time I ever use it is when iterating through tree structures: here, it's the perfect solution. You could do this with a straight loop, but maintaining your position would be tedious. With recursion, you don't have to deal with that.
-
Mar 26th, 2007, 07:35 AM
#4
Thread Starter
Fanatic Member
Re: Recursion
Originally Posted by dis1411
the code as is should return 6... i suggest putting code to report the values of x and y at the top of the function
If I do that, it only reports x and y one time...really weird...
And I thought it was supposed to be 6 also...but my program says 8...
Hmmm....
-
Mar 26th, 2007, 11:42 AM
#5
Frenzied Member
Re: Recursion
try
Code:
#include <iostream.h>
//using namespace std;
int test(int x, int y)
{
cout << x << " " << y << endl;
if (x==y)
return x;
else if (x > y)
return (x+y);
else
return test(x+1, y-1);
}
void main()
{
cout << test(3, 9) << endl;
}
-
Mar 26th, 2007, 09:28 PM
#6
Thread Starter
Fanatic Member
Re: Recursion
Originally Posted by dis1411
try
Code:
#include <iostream.h>
//using namespace std;
int test(int x, int y)
{
cout << x << " " << y << endl;
if (x==y)
return x;
else if (x > y)
return (x+y);
else
return test(x+1, y-1);
}
void main()
{
cout << test(3, 9) << endl;
}
Ahh yeah, me and my supervisor where I work helped me figure out my problem...I wasn't returning test(x +1, y-1) I was just calling it self again...
I hate recursion with a passion.
Btw, a few things wrong with your code, you commented out using namespace std, if you do that then you have to put std::cout instead of just cout. And you are using iostream.h which is old, it is suggested you use the new and highly improved 'iostream'.
-
Apr 13th, 2007, 01:22 AM
#7
Member
Re: Recursion
i agree!! u must include "using namespace std;"
(without using)= std::cout<<"hello";
(using)= cout<<"hello";
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|