Before
4
Before
3
Before
2
Before
1
After
After
After
After
My doubt is why does the cout<<"After\n"; gets displayed 4 times.I am assuming that the control is out of the loop and cout<<"After\n"; can only be displayed once.I am new to recursion and also confused.
Thank you for reading.
look at Line 18: cout<<"After\n";
It is part of myFunction. so for each call of myFunction it should be execute.
how the code above works:
0: myFunction(4) called for first time by main function
1: first-call runs to line 17 where it calls anoter myFunction and waits for cpu. it calls myFunction(3)
2: second-call runs to line 17 where it calls anoter myFunction and waits for cpu. It calls myFunction(2)
3: third-call runs to line 17 where it calls anoter myFunction and waits for cpu. It calls myfunc(1)
4:forth-call runs to line 17 where it calls anoter myFunction and waits for cpu. it calls myfunc(0)
5: fifth-call terminate at beginning
6: forth-call receives cpu and continues to end (include line 18)
7: third-call receives cpu and continues to end (include line 18)
8: socond-call receives cpu and continues to end (include line 18)
9: first-call receives cpu and continues to end (include line 18)
I never realized there would be a queue of function calls in recursion
I'm glad you learned this. It's actually a stack of function calls, not a queue. And this stack of function calls is actually the whole point of recursion.
Recursion does not always require a stack of function calls and it is obviously not the whole point of recursion. It's just another way of looping that is very convenient for some use cases.