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;
}
|