write Factorial of a Number in C using do-while Loop program

Factorial program by using do while loop
Program 


#include<stdio.h>
#include<conio.h>
void main()
{
    int n,i=1,f=1;
    clrscr();
     
    printf("\n Enter The Number:");
    scanf("%d",&n);
     
    //LOOP TO CALCULATE THE FACTORIAL OF A NUMBER
    do
    {
        f=f*i;
        i++;
    }while(i<=n);
     
    printf("\n The Factorial of %d is %d",n,f);
    getch();
}


Working:
  1. First the computer reads the number 
  2. To find the factorial of the number from the user.
  3. Using do-while loop the value of ‘i’ is multiplied with the value of ‘f’. 
  4. The loop continues till the value of ‘i’ is less than or equal to ‘n’(i<=n).
  5. 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 6.

  1. It assign the value of n=6 , i=1 , f=1.
  2. Then the loop continues till the condition of the do-while loop is true.
  • 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.
  •  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.

  • 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.

  • 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.

  • do

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

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

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

do

f=f*i (f=120*6) So f=720

i++ (i=i+1) So i=7

i<=n (7<=6) , do-while loop condition is false.
 It comes out of the do-while loop.

Finally it prints as given below
The Factorial of 6 is 720

Thus the program execution is completed.











Dall

Post a Comment

0 Comments