Loops in C++

Need of Loops 

If I have to print Hello world for four times , what are the ways to do this ?
One method is by just writing the Hello World statement four times like this
cout<<"Hello World ";

cout<<"Hello World ";
cout<<"Hello World ";
cout<<"Hello World ";
This will give the desired output but what if , I have print it 100 times or 1000 times ? Will it be suitable ?
To overcome this problem , we use loops .


Types of loops in C++

There are three types of loops in C++ :
I. for loop

II. while loop
III. do while loop 


I. for loop

The syntax of for loop is :

for (initialize counter ; check counter ; increment counter )
{
    statement 1; 
    statement 2;
    .....

}

The statements within the curly braces are executed until the counter check is true. The moment condition become false the execution stops.
There should be the some stopping condition in for loop , otherwise it will go in infinite loop. 
Following code snippet gives clear idea of for loop

for (int i = 0 ; i< 5 ; i++)
{
   cout<<"Hello World ";
}

Above program prints " Hello World " five times
The first term in parentheses after for keyword ( int i = 0 ) is called initialization. 
Second term , i< 5 is the condition which is checked every time and is responsible for breaking the loop.
Third term , i++ is called increment .  It increase the value of i by 1 every time.

II. while loop

The syntax of while loop is like

initialize counter;
while( condition )
{
   do this ;
  and this;
  and this; 
 increment counter;
}

The statements inside the curly braces are executed until the condition is true. The  condition gives true or false value and depending on it the body of loop is executed.
Following code snippet clears the idea.
 
int i =1;
 while(i<=3) 
{
   cout<<"Hello World "; 
 i++;
}

Above code gives output as Hello World 3 times.
The code above is self explanatory , initialize the counter , check the condition and increment counter every time.

III. do while loop   

This is special kind of loop , which execute the body at least once.
The syntax for do while loop is  
initialize counter;
do {
  this ;
 and this ;
  and this;
   increment counter;
}while ( condition );

The function of do while loop is exact same as that of while loop except one thing. The statement inside curly braces are executed at least once even if the condition is not true.
Below is the snippet of do while loop
int i = 1;
do {
  cout<<"Hello World ";
  i++;
} while(i<=5);

The output of program is Hello World five times.