C++ Program to find the factorial of a number using recursion

This program is an example to find the factorial of a non-negative integer (entered by the user) using recursion.

How can we calculate the factorial of a number?

The factorial of a number is the product of all integers from 1 to that number. Factorial is not defined for negative numbers, and the factorial of zero is one. An exclamation mark indicates the factorial of a number '!'.
n! =  1 * 2 * 3 * 4 *……..* n.
5! = 1*2 *3*4*5 = 120.

Recursion in C++

A function that calls itself is known as a recursive function. And, this technique is known as recursion.
The recursion continues until some condition is met.
To prevent infinite recursion, the if...else statement (or similar approach) can be used where one branch makes the recursive call and the other doesn't.

Working on Recursion in C++

void recurse()
{
    ... .. ...
    recurse();
    ... .. ...
}
int main()
{
    ... .. ...
    recurse();
    ... .. ...
}

C++ program to Calculate Factorial of a Number Using Recursion

Here the program takes a positive integer from the user to calculate the factorial of that number. 
Ask the user to enter a positive integer and read the number to the variable. Define a recursive function factorial ( ) to find the factorial of the number.
Pass the entered number to the factorial function.
int factorial(int n) 
 in this function, the number n is multiplied to the factorial of ( n – 1 ). For this, the number (n – 1) is passed again to the factorial () function. This continues until the value reaches 1 and the function returns 1. Now each function returns the value back to compute 1 * 2 * 3 * 4 * -----* n, which is returned to the main ( ) function.
if(n > 1)
    return n * factorial(n - 1);
  else
    return 1;

 

Algorithm
 

Step 1: Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Define a function factorial ( );
             n * factorial ( n – 1)  until n > 1;
             return the value  
             else return 1;

Step 4: Open the integer type main function; int main().

Step 5: Declare integer variables; n;

Step 6: Print a message to enter a positive integer not greater than 12.

Step 7: Read the value into the variable n;

Step 8: Call the function factorial(n);

Step 9: Exit;
 

C++ Source Code

                                          #include<iostream>
using namespace std;

int factorial(int n);

int main() {

  int n;

  cout << "Enter a positive integer less than 12: ";
  cin >> n;

  cout << "Factorial of " << n << " = " << factorial(n);

  return 0;
}

int factorial(int n) {
  if(n > 1)
    return n * factorial(n - 1);
  else
    return 1;
}
                                      

OUTPUT

Enter a positive integer less than 12: 6
Factorial of 6 = 720