I've been reading C++ without fear 2nd edition. And I'm stuck on one the part about functions. The goal of the exercise is to create a program that calculates the factorial number in C++ using the for loop and I think a function. I'm so clueless I was wondering if anyone could explain to me the for loop more better and the functions. I'm some what familiar with the for loop but im clueless with functions and how they work. I found a source code for the program
# include <iostream.h>
int factorial (int);
int main()
{
int result;
cout << "Enter your number: ";
cin >> result;
cout << "Factorial of " << result << "is "<< factorial (result) << endl;
}
int factorial (int n)
{
int fact = 1;
if (n <= 1)
return 1;
else
fact = n * factorial (n - 1);
return fact;
}
Well that particular code uses a recursive function (a function that calls itself).
1 2 3 4 5
int factorial( int n )
{
if(n <= 1) return 1; // base condition
return n * factorial( n - 1 );
}
So when the function is called with a number, it'll continue calling itself (while decreasing 'n' by 1 each time it calls itself) until a base condition is met, in this case (n <= 1). Each function call than returns a number, which is going to be the product of (n * factorial( n - 1 )) since factorial() is a recursive function the multiplication doesn't actually happen until the base condition is met, so the first number is actually returned by the function (1 in this case).