i have nothing to do,i just scanning every tutorials i learnt but i just notice i find it confusing about the simulation of this code
why this code the function factorial call himself inside?
can you explain the simulation of this?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
elsereturn 1;
}
int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
}
We could be more general and write it for any positive integer n
n! = n × (n - 1)!
Notice how we have used factorial to define what factorial means. There is only one thing missing. We need to define the special case 1! (or 0!), otherwise the calculation would go on for ever. That's why you have the if statement in your code.
Factorial is often used to demonstrate recursive functions (functions that calls themselves). Recursion is one way of doing it. Another way is to use a loop.
>There is only one thing missing
it is okay. on my compiler it isn't computing negative numbers it stops in 0.
I didn't mean something is missing from your code. I just meant that if factorial is defined as simply n! = n × (n - 1)! then there is something missing.