-
recursion help
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.
-
Your problem has nothing to do with recursion. The cout is part of the if block, and is not executed if x != 1.
-
Code:
#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;
}
That should work the way you want.
-
Thanks for the replies.
But what I would like to understand is why the output is:
2
3
When I try to trace it on paper I can not get that output. I know it is right (obviously) but can someone explain it to me.
Can you take me step by step through the logic of the program.
Thanks for your time.