2 min read

THE WHILE LOOP

while loop can be address as an entry control loop, since the text-expression is present at entry only.

Syntax:

 
 Initialization;
 while (condition) {
 // code block to be executed
  updation;
 } 

In a while loop initialization must be done outside the loop.

Remember, while statement should not be terminated.

Example

int main()
{
   int i=1;
   while(i<=5)
   {
cout<<i<<\n;
i++;
}
   return 0;
} 

The given program initializes variable i , as long as i<=5 body of the loop is executed and update takes place, otherwise control comes out of the body.

OUTPUT

1
2
3
4
5

THE DO-WHILE LOOP

It is the last iterative statement/loop in c++. It is also known as exit– control loop since text-expression is present at the exit point (outside loop body).That means the do-while loop always executes at least once even when the test-expression is false initially.

Syntax:

 
 Initialization;
 do {
 // code block to be executed
  updation;
 }while (condition); 

Example

int main()
{
   char ch= "a";
   do
   {
cout<<ch<<\n;
ch++;
}while(ch<="z");
   return 0;
} 

The above code prints characters from “a” onwards until the condition ch<= “z” becomes false.

  • The most common use of this loop is in menu-selection programs, where the menu is flashed at least once.
  • Always take care of terminator, otherwise, you will get an error.

Comparison of different types of loops

Comparison between for,while,do-while loop
Parametersforwhiledo-while
InitializationBefore or within the parenthesis of the loopBefore the loopBefore the loop
Test ConditionBefore the body of loopBefore the body of the loopAfter the body of the loop.
Updating ConditionAfter the first executionAfter the first executionAfter the First execution.
Loop VariablecountercounterSentinel and counter

If you liked my post please follow me on @priya123 , to get the latest articles from my side.

Categories: Uncategorized

0 Comments

Leave a Reply