Tutorial Study Image

Different Types of Loops in C++ with Examples

August 18, 2022, Learn eTutorial

This tutorial will teach you everything you need to know about generic looping techniques in C++. The C++ programming language provides loops in three distinct ways: for loop, while loop, and do-while loop. You will also see how the infinite loop works in C++.

When will we use loops in C++?

Loop Statements in C++

In programming, there are times when an operation must be performed more than once or n times. When we need to execute a set of statements repeatedly, we use loops.

There may be times when you need to execute a block of code several times. In general, statements are executed in the following order: the first statement in a function is executed first, then the second, and so on. Different control structures are offered by programming languages, enabling more complex execution paths.

Loop Statements in C++

A loop statement allows us to execute a statement or group of statements multiple times, and the general form of a loop statement in most programming languages is as follows:

Types of loops in C++

In C++, loops are classified mainly  into two types:

  1. Entry Controlled loops: Before entering the loop body, the test condition is tested in this type of loop. For Loop and While Loop , they are entry-controlled loops.
  2. Exit Controlled Loops (ECLs): The test condition is evaluated or tested in this type of loop at the end of the loop body. As a result, the loop body will execute at least once regardless of whether the test condition is true or false. The do-while loop is a kind of an exit-controlled loop.

So in order to handle looping requirements, the C++ programming language provides the following types of loops as mentioned above.

Loop Statements in C++
  •  Entry controlled loops
  • Exit controlled loops       
    • Do while loop
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.