recursion problem

I have a simple program using recursion function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
void myFunction(int);
using namespace std;
int main() {
   myFunction(4);
   return 0;
}

void myFunction( int counter)
{
if(counter == 0)
     return;
else
       {
       cout<<"Before \n";
       cout <<counter<<endl;
       myFunction(--counter);
       cout<<"After\n";
       return;
       }
}


The output is this


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.
Last edited on
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)
thanks very much calcushtag,I never realized there would be a queue of function calls in recursion thanks again

also tried
1
2
cout<<"After";
cout<<counter;


to understand better
Last edited on
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.
Topic archived. No new replies allowed.