C++

C++ Loop Types

C++ Loop Types

In this section, we will look into various types of loops present in C++. Often in a program, you need to execute a block of code several number of times. For example, taking marks in 5 subjects from user. Here same set of instructions are executed multiple times sequentially. For such cases, C++ provides loop. A loop statement enables sequential execution of statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages. 

C++ provides 3 types of loops

  1. The while
  2. The for 
  3. The do…while

The “while” loop is used when you want a statement to execute continuously till the condition specified is true. The “for” tells us how many times the loop is executed but while loop does not tell us how many times the loop will execute. The syntax for while loop is simple as shown below:

while (condition)
 {
 	//loop statements;
 }

The for loop is the most popular looping construct used in any programming language. The syntax of for loop is as follows

for (variable initialization; condition; increment operation)
 {
 	//loop statements;
 }

For e.g.

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

The initialization step allows you to declare and initialize counter variable. In the next step, you can evaluate the variable against a condition and in the final step, you can increment or decrement the value of the variable. The loop will go on till the condition becomes false. Then, the program will exit the loop and continue with the rest of the statements.

The do while loop executes at least once because the condition is evaluated only at the bottom of the loop. In the do while loop, the body of the loop will be executed first and then the condition will be evaluated. The syntax of do while loop is :

do
 {
 // statement execution;
 }
 while(condition);