'A basic C++ recursion question I can't wrap my head around
I am learning the basics of CPP programming. I came across this basic recursion question which I'm unable to understand. The output is 1 2 3 4 5 but I don't understand why.
At the first iteration (f(5)), we get into the if condition and call f(5-1). Won't calling f(5-1) here (before cout) take us back to the f(int n) function and skip printing anything at all. Even if we do go to cout after f(5-1), won't cout display 5 instead of 1 for the first iteration? Here is the code. Thank you!
#include <iostream>
using namespace std;
void f(int n)
{
if (n > 0)
{
f(n - 1);
cout << n << " ";
}
}
int main()
{
f(5);
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|