The Factorial operation using recursive function C++ code sample

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Doing the Factorial operation using recursive function in C++ programming

To show: How to declare and define the recursive function, function that call itself in C++ programming

 

 

 

// demonstrates the recursive function, the recursive factorial function the formula is, n! = n*(n-1)!

#include <iostream>

using namespace std;

 

// function prototype, receives long returns long type

long factor(long);

 

int main(void)

{

int p;

 

cout<<"Calculating factorial using recursive function"<<endl;

cout<<" Calling itself!!!"<<endl;

cout<<"----------------------------------------------\n"<<endl;

 

// Let do some looping for 10 numbers

for(p = 1; p<10; p++)

cout<<p<<"! = "<<p<<"*("<<(p-1)<<")!"<<" = "<<factor(p)<<"\n";

 

return 0;

}

 

// recursive function definition

long factor(long number)

{

// for starting number, that <= 1, factorial = 1

if(number <= 1)

return 1;

// number > 1

else

// return and call itself

return (number * factor(number-1));

}

 

Output example:

 

Calculating factorial using recursive function

Calling itself!!!

----------------------------------------------

1! = 1*(0)! = 1

2! = 2*(1)! = 2

3! = 3*(2)! = 6

4! = 4*(3)! = 24

5! = 5*(4)! = 120

6! = 6*(5)! = 720

7! = 7*(6)! = 5040

8! = 8*(7)! = 40320

9! = 9*(8)! = 362880

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index