Software & Finance





Visual C++ - Factorial of a Number with out 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. Here is the program and its output for finding a factorial of a number with out using recursive function calls.


Source Code


#include <iostream>

#include <string>

 

int Factorial(int n)

{

    if( n <= 1)

        return 1;

    int result = 1;

    for(int i = 2; i <= n; i++)

    {

        result = result * i;

    }

    return result;

}

 

int main()

{

 

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

    {

        char buf[128];

        sprintf(buf, "\n%2d! = %d", i, Factorial(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