I have a problem dealing with Recursion can some one help

Jun 3, 2016 at 9:02am
I have printed the output from this code but I don't understand why I get such output. Why dont I get 1 only, because from my understanding that the function is called before the cout, so when x is 7 the cout is not excuted instead the function is called with num =6 till num is equal to 1 then the cout will be excuted


#include <iostream>
using namespace std;
void printNum (int num)
{


if ( num >1 )
{
printNum( num - 1 );


}
cout << num<<endl;

}

int main ()
{
printNum(7);

}

output
1
2
3
4
5
6
7
Jun 3, 2016 at 11:09am
when x is 7 the cout is not excuted instead the function is called with num =6 till num is equal to 1 then the cout will be excuted

The cout statement is outside the if statement so it will always be executed.

It would work the way you said if you placed the cout statement inside the else part of the if statement.
1
2
3
4
5
6
7
8
9
10
11
void printNum (int num)
{
	if ( num >1 )
	{
		printNum( num - 1 );
	}
	else
	{
		cout << num<<endl;
	}
}
Jun 3, 2016 at 5:05pm
Sorry I still don't understand. Why It goes to the else statement when the number is 7. I mean 7 is greater than one so it should go in if and the function calls itself again with number 6 without going to the else.
Jun 3, 2016 at 5:22pm
It doesn't. It only calls printNum(6). My modification was just to show you how the code would have to look like to get the expected behaviour you described in the first post.

When printNum(7) is called in your original code it first calls printNum(6) and then it will continue executing the function and print the number 7.
Last edited on Jun 3, 2016 at 5:27pm
Topic archived. No new replies allowed.