recursion problems i need

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;
	
}

and also how did it able for the computer to print out x when my recursive call comes before cout<<"The number you entered is : "<<x<<endl; how did this line get executed?
Your compiler should say something like:
In function 'int recursion(int)': warning: control reaches end of non-void function


You call the function with value 1. Lets pseudo-expand that code:
1
2
3
if (1 == 9) return 9;
recursion( 1+1 );
cout<<"The number you entered is : "<<1<<endl;

Lets expand that second call too:
1
2
3
4
5
if (1 == 9) return 9;
  if (2 == 9) return 9;
  recursion( 2+1 );
  cout<<"The number you entered is : "<<2<<endl;
cout<<"The number you entered is : "<<1<<endl;

One more time:
1
2
3
4
5
6
7
if (1 == 9) return 9;
  if (2 == 9) return 9;
    if (3 == 9) return 9;
    recursion( 3+1 );
    cout<<"The number you entered is : "<<3<<endl;
  cout<<"The number you entered is : "<<2<<endl;
cout<<"The number you entered is : "<<1<<endl;

You could continue that all the way.

The last call of the function (x==9) returns a number to the second to last call, but no other call has a return.
what do you mean when you said
//
The last call of the function (x==9) returns a number to the second to last call, but no other call has a return.//

is it prerequisite to have 2 return values in a recursive function?
Last edited on
No. Consistency is required.

Your function -- if we call it with value 9, it does the same thing as this:
1
2
3
int foo( int ) {
  return 9;
}

However, if we call with anything else, the function does this:
1
2
3
4
void bar( int x ) {
  bar( x+1 );
  cout << "The number you entered is : " << x << endl;
}

It doesn't return any value.

I'll write your function again, more explicitly:
1
2
3
4
5
6
7
8
9
10
11
12
int recursion( int x )
{
  if ( x == 9 )
  { // branch A
    return 9;
  }
  else
  { // branch B
    recursion( x+1 );
    cout << "The number you entered is : " << x << endl;
  }
}

The branch A does return a value, but the branch B does not. The function should return an int, so the branch B must return an int. What value should the branch B return?


Bonus question: What will happen on recursion( 10 );?
Topic archived. No new replies allowed.