C++ tutorial, C++ programs, C++ Exercises, C++ Example Programs

Saturday, March 17, 2018

C Plus Plus Program to Calculate Factorial of Number Using Do While Loop

Program To Calculate Factorial of a Number Using do ... while Loop

Program To Calculate Factorial of a Number Using do ... while Loop

 What is Factorial?


factorial of a number is calculated by multiplying all the integer numbers from given number n to 1.
For example, factorial of  3 = 3 x 2 x 1.

What is do while Loop in C++ ?


do while loop is the third loop provided by C++. First two are for loop and while loop. The do while loop is used to execute a set of one or more statements repeatedly as long as the given condition remains true.

The main difference between while loop and do while loop is that

 the syntax of do while loop places the condition after the body of loop. The effect of this is that the loop body of do while loop is executed at least once irrespective of the given condition for loop is true or false for first time.

The syntax of do while loop is:


   do
   statement;
  while  ( condition );

   or for a set two or of statements the syntax of do while loop will be as follows:

   do
  {
     statement 1;
     statement 2;
     .
     .
     .
    statement n;
  }
   while ( condition );

Simple example of do while loop to display first 5 numbers 1 to 5


  int i=1;
  do
   {
      cout<<i<<endl;
      i++;
    }
     while ( i<=5 );

  output:
    1
    2
    3
    4
    5

Now we start writing the the program to calculate factorial of a number provided by the user at runtime using do ... while loop

// This program will calculate factorial of a given number provided //by user at run time using do while loop
#include<iostream.h>
#include<conio.h>

void main( )

  {
         int num,  i, fact;
         clrscr( );
         cout<<"Enter a number to calculate Factorial=";
         cin>>num;
         fact= 1;
         i = 1;
         do
             {
                 fact = fact * i;
                 i++;
             } 
              while ( i <= num );
          
           cout<<"Factorial of = "<<num<< " = "<<fact;
           getche();
      }

      

Sample Output of  Program To Calculate Factorial of a Number Using do ... while Loop

Enter a Number to Calculate Factorial: 4
Factorial of 4 = 24


More Programs of Factorial are as follows:


Factorial By For Loop Statement

 Program Factorial by While Loop Logic



     
Share:

0 comments:

Post a Comment

We Love To Hear From You!

EasyCPPprogramming.blogspotcom

Labels