hey guys i have a question about recursion. ive been trying to learn it for a
while now and i got stuck in this codes i dont understand why when i run
this, the numbers is backward because my cout is after the recursive call.
and also lastly the most confusing for me is why does the return value of
my base case 9 is not 9 when i printed it out in the main function , instead
random numbers appear on the main I think its a memory location or a
random numbers etc.
1 2 3 4 5 6 7 8 9 10 11 12
int main()
{
cout<<"The number in the main : "<<recursion(1)<<endl;
}
int recursion(int x)
{
if(x == 9) return 9;
recursion(x+1);
cout<<"The number you entered is : "<<x<<endl;
}
why does the return value of my base case 9 is not 9 when i printed it out in the main function , instead random numbers appear on the main I think its a memory location or a random numbers etc.
Your function doesn't specify a return value for the case where the parameter x isn't 9.
Compare to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int recursion(int x);
int main()
{
cout<<"The number in the main : "<<recursion(1)<<endl;
}
int recursion(int x)
{
//printing before recursive step and before a return is encountered
cout<<"The number you entered is : "<<x<<endl;
if(x == 9) return 9;
return recursion(x+1); //returning something when x != 9
}
the numbers is backward because my cout is before the recursive call.
This is because you would keep calling the function until x = 9. then it would continue doing the series of couts from 9 to your beginning number.
my base case 9 is not 9 when i printed it out in the main function , instead
random numbers appear on the main I think its a memory location or a
random numbers etc.
Actually, the reason you are getting a weird number is because your function is stated to return an int, but there is no return within the function so instead it would just spit out a random number.