If I keep my hand on each line of code as we go through, then when we hit a function call, my hand goes to the function which is called and that function begins to execute, after that my hand returns back to the line where the function was called.
Now when it comes to recursion, when I keep calling the same function, how does the hand behave? Is there a new hand for each function call? I don't understand how the code "goes back up a tree of recursive calls". I understand there is a stack. I have seen all those videos explaining it.
What I don't understand is that if I write cout statements, one above and one under the recursive call, then I understand why the cout statement above the recursive call executes as many times as the recursive function is being called, but then how does the cout statement below the recursive call also get executed those many times?
Here's an example
int Factorial(int n)
{
cout<<"first cout statement before the recursive call";
if( n == 0 )
return 1;
int F = n*Factorial(n-1);
cout<<"second cout statement after the recursive call";
return F;
}
int main()
{
int n;
cin>>n;
int result = Factorial(n);
cout<<result;
}
This the output below.
first cout statement before the recursive call
first cout statement before the recursive call
first cout statement before the recursive call
first cout statement before the recursive call
first cout statement before the recursive call
first cout statement before the recursive call
second cout statement after the recursive call //Notice these
second cout statement after the recursive call
second cout statement after the recursive call
second cout statement after the recursive call
second cout statement after the recursive call
120