Easy Tutorial
❮ Cpp Function Call By Value Cpp Useful Resources ❯

C++ Loops

Sometimes, you may need to execute the same block of code multiple times. Normally, 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.

Loop statements allow us to execute a statement or group of statements multiple times. Below is the general form of a loop statement in most programming languages:

Loop Types

The C++ programming language provides the following types of loops. Click on the links to see details for each type.

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 Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while loop Similar to a while statement, except that it tests the condition at the end of the loop body.
nested loops You can use one or more loops within any other while, for, or do..while loop.

Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

C++ provides the following control statements. Click on the links to see details for each statement.

Control Statement Description
break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
goto statement Transfers control to the labeled statement. However, it is not recommended to use goto statements in your program.

Infinite Loop

If the condition never becomes false, the loop will become an infinite loop. The for loop is traditionally used for this purpose. Since none of the three expressions that form the loop are required, you can make an endless loop by leaving the conditional expression empty.

Example

#include <iostream>
using namespace std;

int main ()
{
   for( ; ; )
   {
      printf("This loop will run forever.\n");
   }

   return 0;
}

When the conditional expression is absent, it is assumed to be true. You can also set an initial value and increment expression, but in general, C++ programmers prefer to use for(;;) structure to represent an infinite loop.

Note: You can terminate an infinite loop by pressing Ctrl + C.

❮ Cpp Function Call By Value Cpp Useful Resources ❯