Hi
Say we enter 4 at the prompt, factorial function is called with 4 as the argument. Now 4*factorial(4-1). The function calls itself now. So what happens at this point?
1.Does it return anything to main or does it call the function again from within?
2. Where would it hold the 4, the 3, and the 2 to multiply it to get 24? In other words, what is the step by step procedure to get 24?
Thanks a lot.
Say we enter 4 at the prompt, factorial function is called with 4 as the argument. Now 4*factorial(4-1). The function calls itself now. So what happens at this point?
1.Does it return anything to main or does it call the function again from within?
2. Where would it hold the 4, the 3, and the 2 to multiply it to get 24? In other words, what is the step by step procedure to get 24?
Thanks a lot.
Code:
#include <iostream>
using namespace std;
long factorial (long x)
{
if (x > 1)
return (x * factorial (x-1)); //calling the function from within the function.
else
return (1);
}
int main ()
{
long num;
cout << "Enter a number: ";
cin >> num;
cout << num << "! = " << factorial (num);
return 0;
}
Comment