Factorial

// Factorial_function.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "iomanip"
using namespace std;
#define LENGTH 20
long double iterative_function(unsigned int n); //Iterative solution
long double recursive_function(unsigned int n); //Recursive solution
int _tmain(int argc, _TCHAR* argv[])
{
       unsigned int n;
       cout << fixed << setprecision(0);
       cout << setw(10) << " n " << setw(30) << " Factorial of n "
              << " (Iterative solution ) \n" << endl;
       for (n = 0; n <= LENGTH; ++n)
             cout << setw(10) << n << setw(30) << iterative_function(n) <<endl;
       cout << " Go on with ";
       cin.get();
       cout << setw(10) <<" n " << setw(30) << " Factorial of n" <<
             "(Recursive solution)\n" << endl;
       for(n = 0; n <=LENGTH; ++n)
             cout << setw(10) << n << setw(30) << recursive_function(n)<<endl;
       cout <<endl;
       system("pause");
       return 0;
}
  long double iterative_function(unsigned int n) // Iterative solution.
   {
     long double result = 1.0;
     for( unsigned int i = 2; i <= n; ++i)
       result *= i;
     return result;
   }
   long double recursive_function(unsigned int n) // Recursive solution.
   {
     if( n <= 1)
       return 1.0;
     else
       return recursive_function(n-1) * n;
   }
Share on Google Plus