Factorial Using Recursion in C++

Factorial Using Recursion in C++ | A function/method that contains a call to itself is called the recursive function/method. A technique of defining the recursive function/method is called recursion.

The recursive function/method allows us to divide the complex problem into identical single simple cases that can be handled easily. This is also a well-known computer programming technique: divide and conquer.

Factorial of a number n is given by 1 * 2 * … * (n-1) * n and it’s denoted by n!
Example Factorial of 5 = 5! = 5*4*3*2*1 or 1*2*3*4*5

Generally, Factorial of a number can be found using the for loop and while loop. But we can also use the recursion technique to find the factorial of a given integer number. Here the problem of finding n! divide them into smaller problem as n! = n * (n-1)!

We know that
4! = 4*3*2*1
We can write it as,
4! = 4 * 3!

Similarly, we can write
3! = 3 * 2!
2! = 2 * 1!
1! = 1 * 0!
0! = 1

So, in general, we can say that factorial of a positive integer n is the product of n and factorial of (n-1).

n! = n * (n-1)!
Now, the problem of finding out the factorial of (n-1) is similar to that of finding out the factorial of n, but it is smaller in size. So, we have defined the solution of the factorial problem in terms of itself. We know that the factorial of 0 is 1 and similarly factorial of 1 is 1. This can act as the terminating condition or the base case.

The base case for finding factorial,

factorial(0) = 1
Or,
factorial(1) = 1

General case for finding factorial,

factorial(n) = n * factorial(n-1)

Factorial Program using Recursion in C++

// C++ program to find factorial 
// of a number using recursion
#include<iostream>
using namespace std;
long findFactorial(int);
int main()
{
  // declare variables
  int num;

  // take input
  cout << "Enter a positive integer : ";
  cin >> num;

  // display result
  cout << "Factorial = " << findFactorial(num) << endl;

  return 0;
}

// C++ recursive function to 
// find factorial of a number
// using if-else statement
long findFactorial(int number) 
{
  if(number == 0) 
     return 1;
  else 
     return number*findFactorial(number-1);
}

Output for the different test-cases:-

Enter a positive integer: 5
Factorial = 120

Enter a positive integer: 10
Factorial = 3628800

In this program, we had used if-else statements but we can also use ternary operator or conditional operator. Using conditional/ternary operators the program can be written in one line.

// C++ recursive function to find factorial of a number
// using conditional operator
long findFactorial(int n)
{
return (n == 0) ? 1 : n*findFactorial(n-1);
}

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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