What is factorial of a number ?

Suppose N is a number. If we want to find factorial of N, then we must multiply all the numbers up to N including the number N.

Let factorial of N be F, then:

F = N \times (N-1) \times (N-2) \times ... \times 1

Usually, factorial program uses recursion. In recursion, a function call itself until the problem is solved.

This program for factorial does not use a recursion.

This program is a simple computation of factorial value, hence, it is suitable for beginner learners of C++ programming.

We used Dev-C++ compiler version 4.9.9.2 installed on a windows 7 64-bit system to write the source code. If you use a different compiler the source code may change.

Let us define the program and how it solve the problem of computing factorial without recursion.

Problem Definition

The program requires user input – a positive integer value and computes the factorial of than number.

For example,

Suppose you entered number 6 , then the factorial of this number would be

F = 1 \times 2 \times 3  \times  4  \times  5  \times 6 = 720

In mathematical terms, if n is a positive integer value, the factorial of N is denoted by N! You can go through the flowchart to understand the logic of factorial applied for program.

Flowchart – Factorial without Recursion

Flowchart - Factorial without Recursion
Flowchart – Factorial without Recursion

Program Code – Factorial without Recursion

// Program to compute factorial of n numbers

#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{

    int fact,i;

    int n;

//Read the value of N

    cout << "Enter value of N:" ; cin >> n;

//Initialize Factorial to 1 and i to 1

    fact = 1;

    i = 1;

    while(i<=n)
    {

        fact = fact * i;

        i++;

    }

// Print the value of factorial

    for(i=0;i < 30;i++)
    cout << "_";cout << "\n\n";

    cout << "Factorial of N:" << "\t" << fact << endl;

    for(i=0;i << 30;i++)
    cout << "_";cout << "\n\n";

    system("PAUSE");

    return 0;

}

To compute factorial, we start by assigning number 1 to variable fact inside a loop.

fact = i; //initial value of fact is 1

Then, the new value of fact is computed by multiplying latest value of i with previous value of fact.

Fact = Fact * i; //Value of i is incremented by 1 using loop.

When loop is exited, Fact contains the value equal to factorial of N.

Output

Enter value of N:6
_____________________________
Factorial of N: 720
_____________________________