RECURSION ! (No idea why it does this)

Ok so I was writing simple recursion problems to see how they work and the console output was not what I was expected, and I cant seem to understand the output actually, also I am aware I can use the debugger but I wasn't able to find any relevant source to the problem.
*The part I don't understand is the part where my code is starting to "return" after the number 0*


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

// Function prototype
void message(int);

int main()
{
   message(3);
   return 0;
}

void message(int times)
{
   cout << "Message " << times << ".\n";
   if (times > 0)
   {
	message(times - 1);
   }
   cout << "Message " << times << " is returning.\n";
}


This is a link to the screenshot of the code and console:
https://drive.google.com/file/d/0B5IgZ8NJ1zllLWFURWRpb0U5Qms/edit?usp=sharing


The console displays as follows:
Message 3
Message 2
Message 1
Message 0
Message 0 is returning
Message 1 is returning
Message 2 is returning
Message 3 is returning


Note: I am new to the forum and would like some feedback about this site, anything is greatly appreciated
Well, first the message() function prints the times value it was passed. If times is more than zero, the recursion continues, in the form of another call to message, with times decreased by one.
Once times is no longer larger than zero (once it reaches zero), the recursion stops, and the inner-most recursion can terminate, which, in turn, allows the next recursion to terminate, etc.
Last edited on
The part I don't understand is why is returning from 0 to 3, I know the function would print out the "message 0 is returning" but after that message I don't get why it would go up to 3 again
console:
Message 1 is returning
Message 2 is returning
Message 3 is returning
ooh ok, then I guess that's how they work, its a pretty neat illustration @jockX thank you !!
Topic archived. No new replies allowed.