Calculates factorials using recursion - C++ Function

C++ examples for Function:Recursive Function

Description

Calculates factorials using recursion

Demo Code

#include <iostream>
using namespace std;
unsigned long factfunc(unsigned long);  //declaration
int main()/* ww  w . j  av  a 2 s . c om*/
{
   int n;                //number entered by user
   unsigned long fact;   //factorial
   cout << "Enter an integer: ";
   cin >> n;
   fact = factfunc(n);
   cout << "Factorial of " << n << " is " << fact << endl;
   return 0;
}
// calls itself to calculate factorials
unsigned long factfunc(unsigned long n)
{
   if(n > 1)
      return n * factfunc(n-1);  //self call
   else
      return 1;
}

Result


Related Tutorials