i have a question how did the last line in my recursion function get executed when my recursive call comes after it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<iostream>
usingnamespace 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
}
To start with, you are trying to call your recursive function before you give x a value. The way the code is written right now, your program crashes as soon as it runs.
Secondly, with your actual issue, the reason why cout is called is because you have an if statement directly above your recursive call. If you have an if statement with brackets, it will check if the condition is true, and then run the line of code directly beneath the statement.
As your code stands, the only time you will call your recursive function is if the value of x inputted is equal to 9.
I'm not sure what you're trying to do here, so some details would be appreciated.
x=1. So you call recursion(1).
Line 12 calls recursion(2). This call has it's own 'x' variable, separate from the first call. In this call, x=2.
Line 12 calls recursion(3).
This continues: recursion(3) calls recursion(4) calls recursion(5)... calls recursion(8) calls recursion(9).
Finally, in recursion(9), line 11 is true and the function returns to recursion(8).
recursion(8) prints "The number you entered is 8" and returns to recursion(7)
recursion(7) prints "the number you entered is 7" and returns to recursion(6).
...