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

Buy Me A Coffee

Found this article helpful? Please consider supporting!


I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *