Looping Statements in C++: For, While and Do-While

Loop means iteration. In c++ loops are used to repeat certain block of code until a condition is satisfied. 

In c++ we use three loop statements:

  1. while
  2. do-while
  3. for

While Loop

While Loop is a condition based and entry controlled (means the condition is tested before entering the loop body) loop. It repeats a group of statements while a given condition is true.

Syntax

    while(condition) 
    {
       statement;
    }
Example
    a=0; 
    While(a<=10)
    {
        cout<<a;
        a++;
    }

do-while 

do-while Loop is also a condition based but exit controlled (means the condition is tested at the bottom of the loop) loop. It repeats a group of statements while a given condition is true. 

But the major difference between while and do-while loop is that, do while loop is guaranteed to execute at least one time.

Syntax

do 

{
   statement;
}
while( condition );

Example

a=0;

do

{

   cout<<a;

   a++;

}

while(a<=0);

For Loop

This is range based and entry controlled loop that provide a simple loop structure.

Syntax

for(initialization;condition;inc/dec)

{

      statements;

}

Here:

Initialization: The initialization statement is executed only once. Initialize variable using assignment statement such as i=1.

Condition: This is an expression that returns either true or false. If it returns true the body of for loop executed otherwise the loop is terminated.

Update(inc/dec): Update the value of initialized variable and check the condition. It is also done using assignment operators such as i=i+1 or i++.

Example

int i;

for(i=0;i<=10;i++)
{
      cout<<i;
}

0 Comments:

Post a Comment

If you have any queries or suggestions, please let me know!