Here is the code:
#include <iostream>
using namespace std;
void countdown(int n);
int main(){
countdown(4); // call the recursive function
return 0;
}
void countdown(int n){
cout << n << endl;
if (n > 0){
countdown(n-1); // function calls itself
}
cout << n << endl; // intended part of code
}
Simple run :
4
3
2
1
0
0
1
2
3
4
Question: why does this recursive function counts back up from 0 to 4 and do not stop at 0?
Because recursion function call is stored in stack. So, when one function call returns, it is popped out of stack and then it executes the next line of the function call.
void countdown(int n){
cout << n << endl; // This line calls 4 3 2 1 0
if (n > 0){
countdown(n-1); // function calls itself
}
cout << n << endl;; //This line print 0 1 2 3 4
}
Suppose the numbers before the line of the code are the line numbers:
1 void countdown(int n){
2 cout << n << endl; // This line calls 4 3 2 1 0
3 if (n > 0){
4 countdown(n-1); // function calls itself
5 }
6 cout << n << endl;; //This line print 0 1 2 3 4
7 }
Suppose countdown is called with n = 2,
Then, Your stack will initially contain function call with n = 2.
Because of line 2, 2 gets printed.
Because of line 4, function with n = 1 gets called. So, now stack has 1|2
Now because of line 2 again, 1 gets printed.
Because of line 4, function with n = 0 gets called. So Now stack is 0|1|2
Line 2 prints 0.
Line 3 condition fails and so line 4 is not executed.
Line 6 prints 0.
Line 7 tells that function execution is over and hence it will pop out of stack. Now stack is 1|2.
Now, function with n = 1 resumes its operation from line 5.
So, line 6 makes it print 1.
line 7 tells that function execution is over and hence it will pop out of stack. Now stack is 2.
So, function with n =2 resumes its operation from line 5.
line 6 makes it print 2.
line 7 tells function execution is over and hence it will pop out of stack. And now it will return to main.
You print n twice - before calling the function recursively, and then again after it returns. If you only want to print the number counting down, just print it once:
void countdown(int n) {
cout << n << endl;
if (n > 0){
countdown(n-1);
}
// Another cout call was removed here...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With