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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include<iostream> using namespace std; int fact(int); int main() { int num; cout<<"Enter a number :"; cin>>num; /* Check if user entered a number less than 1 */ if(num < 1) { cout<<"Please enter a natural number"; return 0; } /* Print the result */ cout<<"Factorial is "<<fact(num); return 0; } /* Function to calculate factorial */ int fact(int n) { if(n == 1) { //factorial of 1 is 1 return 1; } else { //calling this function recursively return n * fact(n-1); } } |

Great information. Lucky me I came across your blog by chance