Loops in C++

Loops in C++

Loops in C++ used to execute a block of code or statements. C++ provides the following types of loop to handle the looping requirements in program.

In all programming language, loops are used to execute a block of statements repeatedly till a satisfied the particular condition.

There are 3 types of loops in C++ they are follows

    • for loop
    • while loop
    • do…while loop

1. For loop in C++

For loop is used to execute a set of statement repeatedly until satisfied the particular condition and it is also used to iterate a part of the program several times. 

Syntax of for-loop in C++

for(initialization; condition; incr/decr){    
//body of loop    
}

Program of for loop in C++

#include <iostream>  
using namespace std;  
int main() {  
         for(int i=1;i<=10;i++){      
            cout<<i <<"\n";      
          }       
    }

Output

1
2
3
4
5
6
7
8
9
10

 

2. While loop in C++

The while loop is an empty-controlled loop and it through a block of code as long as a specified condition is true

Syntax of while loop in C++

while(condition){    
//code to be executed    
}    

Program of while loop in C++

#include <iostream>  
using namespace std;  
int main() {         
 int i=1;      
         while(i<=10)   
       {      
            cout<<i <<"\n";    
            i++;  
          }       
    }  

Output

1
2
3
4
5
6
7
8
9
10

 

3. do…while Loop in C++

do while loop is used when some situations is necessary to execute body of the loop before testing the condition and this situations handled by do while loop. do statement evaluates the body of the loop at first and at the end, the condition is checked using while statement.

Syntax of do while loop in C++

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

Program of do while loop in C++

#include <iostream>  
using namespace std;  
int main() {  
     int i = 1;    
          do{    
              cout<<i<<"\n";    
              i++;    
          } while (i <= 10) ;    
}

Output

1
2
3
4
5
6
7
8
9
10

 

 

Read more, Break and Continue Statements in C++

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *