Loop Types

Loop Types

There may be a situation, when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages:

C++ programming language provides the following type of loops to handle looping requirements.

Loop             Type Description
while loop         Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

for loop         Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

do…while loop    Like a ‘while’ statement, except that it tests the condition at the end of the loop body.

nested loops     You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.

While Loop
A while loop statement repeatedly executes a target statement as long as a given condition is true.

Syntax
The syntax of a while loop in C++ is:
while(condition)
{
statement(s);
}

for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax
The syntax of a for loop in C++ is:
for ( init; condition; increment )
{
statement(s);
}

do…while Loop
 
Unlike for and while loops, which test the loop condition at the top of the loop, the do…while loop checks its condition at the bottom of the loop. A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

Syntax
The syntax of a do…while loop in C++ is:
do
{
statement(s);
}while( condition );

Nested Loops
A loop can be nested inside of another loop. C++ allows at least 256 levels of nesting.

Syntax
The syntax for a nested for loop statement in C++ is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}

error: Content is protected !!