Recursive Function Conundrum

Hi everyone,

I'm a novice to the world of C++ and I've a logical question. I'm working on a code to test recursive function and wondering how the function actually works.

In the following sample code I got, I declare & define 2 function prototypes to calculate factorial values. From my understanding computeFactorials function calls factorial function, but not sure how factorial function is correctly calculating the factorial value.

For example, for value of num=4, the factorial calculation will be 4x3x2x1=24, does the factorial function calls itself multiple times?

I tried to trace this program, for factorial function, for the value of 4, first if statement will be ignored, next statement translates to "factorial(3) * 4", that calls factorial function again to factorial(2) * 3" and so on. But how the value gets carried over to the very first iteration?

Please help me understand, thanks for your time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

//declare function prototypes
int computeFactorials(int, int);
int factorial(int n);

int main()
{
	computeFactorials(1,8);
	return 0;
}

//function definition
int computeFactorials(int num, int max)
{
	cout << "Factorial of " << num << " is : "; //statements to be executed
	cout << factorial(num) << endl; //statements to be executed
	num ++; // incrementer
	if (num > max) return 0; //conditional test to recall or exit // exit the loop
	else computeFactorials(num, max); // or call again
}

int factorial(int n)
{
	int result;
	if (n == 1) result = 1;
	else result = ( factorial (n-1) * n);
	return result;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
factorial(4)
if (4 == 1) // No
result = factorial(3) * 4
         if (3 == 1) // No
         result = factorial(2) * 3
                      if (2 == 1) // No
                      result = factorial(1) * 2
                                   if (1 == 1)
                                       result = 1
                                       return result
                      result = 1 * 2 = 2
                      return result
         result = 2 * 3 = 6
         return result
result = 6 * 4 = 24
return result


---24---

How does recursion work? http://www.cplusplus.com/forum/articles/2231/

I will now show brief contents of the stack as the functions are called

Before the function call -> []
After call 1 -> [4]
After call 2 -> [4 | 3]
After call 3 -> [4 | 3 | 2]
After call 3 returns -> [4 | 3 | 2]
After call 2 returns [4 | 6]
After call 1 returns [24]
After the function returns -> []
Topic archived. No new replies allowed.