Factorial using Recursion in C++

In the previous post, i explained how to write a program to find factorial of a number. Now i’ll explain how to do the same task using a different way, i.e, using recursion.


Recursion is nothing but a function calling itself. To do this program using recursion, we use few mathematical equations : 
factorial of 1 = 1
factorial of n = n * factorial of (n – 1)

(For example 4! = 4 * 3! = 4 * 3 * 2! = 4 * 3 * 2 * 1! = 4 * 3 * 2 * 1 = 24)

That’s it! We create a function to find factorial. If the input is 1 it returns 1, else it returns n * fact(n-1). Now when you invoke the function, it keeps on calling itself until n=1.  Thus to find a factorial of number n, this function will be invoked n times.

This function doesn’t check whether the input is less than 1, which causes an infinite function call. For now, we check it soon after user inputs the number.

Here is the full program:

1 comment

Leave a Reply

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