Recursive factorial function in C++

0
195
McCarthy 91 function in C++
Overloading Addition operator in C++

Here we are going to define our recursive factorial function in C++:

#include <iostream>
  using namespace std;
  
  int factorial(int n)    // 1, 1, 2, 6, 24, 120, 720, …  
  {
    if (n == 0) return 1;
    return n * factorial(n–1);
  }
 
int  main()
  {
    int n;
   
    cout << “Enter a non-negative integer: “;
    cin >> n;
    cout << “Factorial of “ << n << ” is “ << factorial(n) << endl;  
    return 0;
  }

Here first of all we asked the user to enter a non-negative number, then we passed it to the recursive factorial function, where it checks the number that if is equal to zero then return 1, else recursively call the function with n-1 and multiplied by n and go on until the recursive factorial function call is complete, and  at the end our factorial is returned recursively to the main() and printed out.

McCarthy 91 function in C++
Overloading Addition operator in C++

Leave a Reply