Cpp - Write program to create a function to calculate the factorial of a number

Requirements

The factorial n! of a positive integer n is defined as

n! = 1*2*3 . . . * (n-1) * n 

Where 0! = 1

Write a function to calculate the factorial of a number.

  • Argument: A number n of type unsigned int.
  • Returns: The factorial n! of type long double.

Create two versions of the function, where the factorial is

  • calculated using a loop
  • calculated recursively

Test both functions by outputting the factorials of the numbers 0 to 20.

Demo

#include <iostream> 
#include <iomanip> 
using namespace std; 

#define N_MAX   20 /*  ww w.  j  av  a2s.c o  m*/

long double fact1(unsigned int n);  // Iterative solution 
long double fact2(unsigned int n);  // Recursive solution 

int main() 
{ 
    unsigned int n; 

   // Outputs floating-point values without 
   // decimal places: 
    cout << fixed << setprecision(0); 
   //  ---  Iterative computation of factorial  --- 

   cout << setw(10) << "n" << setw(30) << "Factorial of n" 
         << "           (Iterative solution)\n" 
         << endl; 

   for( n = 0; n <= N_MAX;  ++n) 
       cout << setw(10) << n << setw(30) << fact1(n) 
             << endl; 

   cout << "\nGo on with <return>"; 
   cin.get(); 

   //  ---  Recursive computation of factorial  ---- 

   cout << setw(10) << "n" << setw(30) << "Factorial of n" 
         << "           (Recursive solution)\n" 
         << endl; 

   for( n = 0; n <= N_MAX;  ++n) 
       cout << setw(10) << n << setw(30) << fact2(n) 
             << endl; 

   cout << endl; 

   return 0; 
} 

long double fact1(unsigned int n)       // Iterative 
{                                       // solution. 
   long double result = 1.0; 
   for( unsigned int i = 2; i <= n; ++i) 
        result *= i; 

   return result; 
} 

long double fact2(unsigned int n)       // Recursive 
{                                       // solution. 
   if( n <= 1) 
       return 1.0; 
   else 
       return fact2(n-1) * n; 
}

Result