• 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,
If the number is 0, then this function will return 1,
If the number is 1, then this function will return 1,
If the number is 2, then this function will return 2,
If the number is 3, then this function will return 6,
If the number is 4, then this function will return 24,
If the number is 5, then this function will return 120,
If the number is 6, then this function will return 720,
If the number is 7, then this function will return 5040,
If the number is 8, then this function will return 40320,
If the number is 9, then this function will return 362880.
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... ...................................
 
Top