Factorial of a Number in C++ using do-while Loop

Before going to the program first let us understand what is a Factorial of a Number?

Factorial of a Number:

                     The factorial of a Number n, denoted by n!, is the product of all positive integers less than or equal to n.

The value of 0! is 1 according to the convention for an empty product.

For example,

5 ! = 5 * 4 * 3 * 2 * 1 = 120

Program code for Factorial of a Number in C++:

#include<iostream.h>
#include<conio.h>

void main()
{
    int n,f=1,i=1;
    clrscr();
    
    cout<<"\n Enter The Number:";
    cin>>n;
    
    //LOOP TO CALCULATE THE FACTORIAL OF A NUMBER
    do
    {
        f=f*i;
        i++;
    }while(i<=n);
    
    cout<<"\n The Factorial of "<<n<<" is "<<f;
    getch();
}

Related: Factorial of a Number in C using do-while Loop

Working:

  • First the computer reads the number to find the factorial of the number from the user.
  • Then using do-while loop the value of ‘i’ is multiplied with the value of ‘f’.
  • The loop continues till the value of ‘i’ is less than or equal to ‘n’.Finally the factorial value of the given number is printed.

Step by Step working of the above Program Code:

Let us assume that the number entered by the user is 5.

  1. It assigns the value of n=5 , i=1 , f=1
  2. Then the loop continues till the condition of the do-while loop is true.

2.1.   do

f=f*i    (f=1*1)    So  f=1

i++      (i=i+1)    So  i=2

i<=n    (2<=5) , do-while loop condition is true.

2.2.   do

f=f*i    (f=1*2)    So  f=2

i++      (i=i+1)    So  i=3

i<=n    (3<=5) , do-while loop condition is true.

2.3.   do

f=f*i    (f=2*3)    So  f=6

i++      (i=i+1)    So  i=4

i<=n    (4<=5) , do-while loop condition is true.

2.4.   do

f=f*i    (f=6*4)    So  f=24

i++       (i=i+1)    So  i=5

i<=n    (5<=5) , do-while loop condition is true.

2.5.   do

f=f*i    (f=24*5)    So  f=120

i++       (i=i+1)    So  i=6

i<=n    (6<=5) , do-while loop condition is false.

2.6.   It comes out of the do-while loop.

  1. Finally it prints as given below

The Factorial of 5 is 120

  1. Thus the program execution is completed.

Output:

factorial of a number

factorial of a number

TO DOWNLOAD THE PROGRAM CODE : CLICK HERE

 

Leave a Reply

Your email address will not be published. Required fields are marked *