Software & Finance





Visual C++ - Factorial of a Number using Recursion





We can write a program to find the factorial of a given number using recursion and with out using recursion.

4! means = 1 * 2 * 3 * 4 = 24
5! means = 1 * 2 * 3 * 4 * 5 = 120  or (5 * 4!)
6! means = 1 * 2 * 3 * 4 * 5 * 6 = 720 or (6 * 5!)

Recursion meaning the function calls itself.

 


Source Code


#include <iostream>
#include <string>


int
Fact(int n)

{

    if( n <= 1)

        return 1;

    return n * Fact(n - 1);

}

int main()

{

 

    for(int i = 0; i <= 10; i++)

    {

        char buf[128];

        sprintf(buf, "\n%2d! = %d", i, Fact(i));

        std::cout  << buf;

    }

 

    std::cout << "\n\n";

 

    return 0;

}

Output


 0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800