public static double ComputeFactorial(int n)
{
if (n >= 1)
{
var compute = n * ComputeFactorial(n - 1);
return compute;
}
else
return 1;
}
How it works:
Assume we’re passing a number 5 to the function, it then checks if the number is not less than 1. Since 5 isn’t less than 1, the method returns product of the number passed (in this case 5) along with a call to itself passing number decreased by 1. And this continues till the number becomes 0, which is a breaker and then the total computation is returned.
******* Factorial Recursion *******
Enter input:5
1 calling out on 0 returns 1
2 calling out on 1 returns 2
3 calling out on 2 returns 6
4 calling out on 3 returns 24
5 calling out on 4 returns 120
5! = 120