Loops in C++ With Examples

Loops come into picture when we need to execute a particular action in a repeated manner.

Types of loops in C++


C++ Loops

There are two broad categories of loops in C++ :

  • Entry Controlled Loops
  • Exit Controlled Loops

Entry Controlled Loops

In entry controlled loops, the test expressions are tested beforehand i.e. they are tested before the execution of the preceding statements.

There are two entry controlled loops:

For Loops

The for loop is an iterative statement that executes for a given number of times based on the initialization expression.


For Loop C++

Working of For Loops:

The for loops use a loop variable as a pointer to point to the particular instance of the loop being executed.

  • Initially, the loop variable is declared and initialized.
  • Post which, the validity of the test expression in accordance with the particular program is done.
  • Then, the loop variable is updated to a certain value.

The above steps are repeated until it meets the exit condition.

Note: In for loops, the number of iterations i.e. the number of times the loop will execute is known by definition.




While Loops

In while loops, the termination of the loop completely depends on the test expression because in this loop we do not specify the number of iterations.


While Loop In C++++




Exit Controlled Loops

In exit controlled loops, the test expression is analyzed and evaluated at the end of the loop.

Thus, the loop will run and execute at-least-once irrespective of the test expression.

Do-while loop

Do-while loops serve the same purpose as that of the while loops. But, in do-while loops, the test condition is evaluated at the end of the loop.


Do While Loop In C++

As you must have understood from the illustration above, the loop will always execute first, check for the condition later.




Loop Control Statements

The following loops statements are necessary to decide and control the flow of termination of the loop in the program:

  • break statement: As soon as the compiler encounters the break statement, the loop terminates on an immediate basis and the flow of control gets passed to the statement following the loop.
  • continue statement: As soon as the compiler encounters the continue statement at a particular instance of test-condition, it immediately leaves the current condition of the loop and restarts the loop.


Thus, in this article, we have understood the basic working of the C++ loops.


C++ Loops Documentation

By admin

Leave a Reply

%d bloggers like this: