Factorial
A factorial is :
n! = 1 * 2 * 3 * ... * n
0! = 1
1! = 1
fact(n) = 1 * 2 * 3 * ... * (n - 1) * n
fact(n) = if n > 0 fact(n - 1) * n
if n = 0 1
int fact(int n) {
if (n == 0)
return(1);
else
return fact(n - 1) * n;
}
Writing a recursive function is indeed easy when you have figured out the equation, you can directly write a formula into a function.
If you input a negative input, it will go into infinite recursion and get into a stack overflow. To prevent that, you can introduce a stop condition if the number is negative.