problem please

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;
int recursion(int x);
int main()
{
	int x=1;
	cout<<"The number in the main    : "<<recursion(x)<<endl;
}
int recursion(int x)
{
	if(x == 9) return 9;
	recursion(x+1);
	cout<<"The number you entered is : "<<x<<endl; // how did this get printed out when theres a recursive function before it
	
}

and also why does the return value of my base case which is 9 , is not 9 when i printed it out in my main function
well, I can answer the last bit. The reason you're outputting some weird number in main, is because you are failing to provide a return value when x != 9.
Last edited on
recursion(x+1); has been called 8 times.
then the unfinished work is done:
cout<<"The number you entered is : " 8 times.
also, it only recurses until x == 9. at which point the 9th instance returns, and proceedes with the line following the function call in the 8th instance, which is the first cout << "the number you entered... " After which that call returns to the 7th instance which does the same. then the 6th.

if you add return x; at line 14, your main function will get 1. (not other values 2, 3, .... 9 )
thanks for helping guys
Topic archived. No new replies allowed.