C++: Learning the Basics – Introduction to DO WHILE LOOPS

The Do-While loop is essentially an inversion of the while loop.

Why is the Do-While loop important?
It executes the loop statements unconditionally the first time. It then evaluates the conditional expression specified before executing the statements again.

A sample code for the Do-While loop is attached below. I have also annotated the code so that a newbie can get a better understanding.

Situation #1: Do-while loop for the addition of 10 numbers put in by the user.

#include <iostream.h>
#include <conio.h>
void main()
{
  clrscr(); #clear the screen
  int sum=0, counter=0, num; #counter represents the number of intergers the user has put in
  
  do
  {  cout<<"\n\t Enter a number: ";
     cin>>num;

     sum=sum+num;
     counter++; #each time the user puts in a number, the counter increases by one. The ++ signifies an increment of 1

  } while (counter<10); #the process of adding the numbers is follwed until counter<10. The program checks that the condition is met after adding the numbers once. 

  cout<<"\n\t Sum= :<<sum; 
  getch();
}

Complete code:

#include <iostream.h>
#include <conio.h>
void main()
{

 clrscr(); 
 int sum=0, counter=0, num; 
 
 do
 { cout<<"\n\t Enter a number: ";
   cin>>num;

   sum=sum+num;
   counter++; 

 } while (counter<10); 

 cout<<"\n\t Sum= :<<sum; 
 getch();

}

Situation #2: User enters a number and the program displays its factorial.

#include <iostream.h> 
#include <conio.h> 
void main()
{
   clrscr();
   int fact=1, num;
   
   cout<<"\n\t Enter a number: ";
   cin>>num;
   
   do
   {    
        fact=fact*num;
        num=num-1;
   } while (num>0);
 
   cout<<"\n\t Factorial= "<<fact;
   getch();

}

 

Posted in C++

Leave a comment