• Welcome to ForumKorner!
    Join today and become a part of the community.

[Tutorial][C++] Factorial through recursion

hotspice

Member
Reputation
0
Factorial through recursion
factorialRecursive() calculates the factorial of a number recursively.

For example,
Code of factorialRecursive()

unsigned long factorialRecursive( unsigned long number )
{
if ( number == 0 || number == 1 )
return 1;
else
return number * factorialRecursive( number - 1 );
}

Summary of factorialRecursive()
factorialRecursive() is a recursive function with 2 parts;
first part is the base case – if the number is equal to 0 or 1, then this function will return
1.
factorialRecursive ( 0 ) = 1
factorialRecursive ( 1 ) = 1
Second part consists of recursive calls as mentioned below:
number * factorialRecursive( number - 1 )
Example (C++)
Code:
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

unsigned long factorialRecursive( unsigned long number )
{
      if ( number == 0 || number == 1 )
            return 1;
      else
            return number * factorialRecursive( number - 1 );
}

int main()
{
      for( unsigned long i = 0; i < 10; i++  )
            cout << i << "!" << factorialRecursive( i ) << endl;
      cout << endl;

      _getche();
      return 0;
}
Output
0!1
1!1
2!2
3!6
4!24
5!120
6!720
7!5040
8!40320
9!362880

Whoops. Not sure if its in the right section... ...................................