First of all, we need to understand the concept of recursion and factorial to write this program.

What is Recursion?

It is an essential concept in computer science. In computer science, recursion is a process in which a function calls itself directly or indirectly.

Recursion function must have the following two properties:

  1. There must be a specific criterion, called base criteria, for which the function does not call itself.
  2. Each time function calls itself; it must be closer to the base criteria.

What is Factorial?

Factorial is represented by an exclamation mark (!). Factorial of n number is the product of all integers greater than or equal to 1 but less than or equal to n.

To find factorial of a number, the number should be greater than or equal to 1. Factorial of 0 is defined as 1 and factorial of a negative number is impossible.

C++ code to Find Factorial of a Number using Recursion

Here is the source code of the program in C++ to Find Factorial of a Number using Recursion. This program is successfully compiled, and the output is also given below.

#include<iostream>

using namespace std;

int fact_Recursive(int num) {

  if (num == 0 || num == 1)

  {

    return 1;

  } else

  {

    return (num * fact_Recursive(num - 1));

  }

}

int main() {

  int num;

  cout << "Enter a number to find factorial: ";

  cin >> num;

  int result;

  if (num < 0)

  {

    cout << "\nFactorial of negative number is undefined please try again";

  } else

  {

    result = fact_Recursive(num);

    cout << "\nThe Factorial is :" << result;

  }

  return 0;

}

Output

Find Factorial of a Number using Recursion in C++

Program Explanation

C++ program starts execution from the main method. In the above program, a variable num is declared to take input from the user. After that, a variable result is declared to store the calculated value of factorial.

An ‘If-else’ statement is used, if the value of the num variable is less than zero, then the ‘if’ section will be executed. Otherwise, the ‘else’ statement will be executed. Inside the ‘else’ statement, the fact_Recursion function will be called by passing the num variable and the return value of the function will be stored in the result variable.

In fact_Recursion() function, an ‘if-else’ statement is used. The ‘if’ condition checks the num variable value if it is equal to 1 or 0 by using the logical OR operator. If the condition is true then this ‘if’ the section will be executed and fact_Recursion() function will return 1.

In the ‘else’ section, the value of the number variable is multiplied by fact_Recursion() value and then returns a value. Afterword the compiler will move back to the main and print the calculated value on the screen.

Related Articles

Last modified: May 6, 2019