Find the Factorial of a given number using Recursion


Factorial of a number is calculated by multiplying all the numbers from 1 till the number itself. For any given input number, we are required to calculate factorial, using recursion. Recursion is a technique in which a method calls itself in a loop until some breaking statement is met. This technique makes programming significantly simple and is used in complex computations to save memory.

        public static double ComputeFactorial(int n)
            if (n >= 1)
                var compute = n * ComputeFactorial(n - 1);
                return compute;
                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

Recursion Loops •  Added 2 months ago

We use cookies to provide you with a great user experience, analyze traffic and serve targeted promotions.   Learn More   Accept