// factorial calculator
#include <iostream>
usingnamespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
elsereturn (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
When they explained it I still didnt get it. Even after reading it like a thousand times. Please help me.
I'm not going to attempt to explain it, because ultimately I think you have to explain it to yourself. However, I do suggest adding some output statements to display which part of the code is executed and what the values are. For example like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
long factorial (long a)
{
cout << "a = " << a << endl;
if (a > 1)
{
long temp = factorial (a-1);
cout << a << " * " << temp << endl;
return a * temp;
}
else
{
cout << " done " << endl;
return (1);
}
}
Input 5.
Output:
1 2 3 4 5 6 7 8 9 10 11 12
Please type a number: 5
a = 5
a = 4
a = 3
a = 2
a = 1
done
2 * 1
3 * 2
4 * 6
5 * 24
5! = 120
Now the task is to understand the output. Left as an exercise for the reader...