Hi, I am trying to learn some recursion and I am having trouble following this simple program:
#include <iostream>
#include <stdlib.h>
using namespace std;
void fun(int x);
int main(void)
{
fun(3);
}
void fun(int x)
{
if (x != 1) {
fun(x - 1); // fun calls fun
cout << x << endl;
}
}
The output is:
2
3
This is my understanding:
x=3: so is 3 !=1 true so fun(3-1) or fun(2)
so is 2 !=1 true so fun(2-1) or fun(1)
so is 1 !=1 false
cout x (doesn't x=1 ??)
and why are two numbers printed?
I'm sure this is simple for many of you, but I am simple, and if you could break it down for me I would be grateful.