C++ Loops
Sometimes, you may need to execute the same block of code multiple times. Generally, statements are executed sequentially: the first statement in a function is executed first, then the second statement, and so on.
Programming languages provide various control structures that allow more complex execution paths.
Loop statements allow us to execute a statement or group of statements multiple times; below is the general form of loop statements in most programming languages:
Loop types
The C++ programming language provides the following loop types. Click the link to view details of each type.
| Loop types | 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, simplifying the code for managing loop variables. |
| do...while loop | Similar to the while statement except that it tests the condition at the end of the loop body. |
| Nested Loops | You can use one or more loops inside a while, for, or do..while loop. |
Loop control statements
Loop control statements change the normal sequence of execution. When execution leaves a scope, all automatic objects created in that scope are destroyed.
C++ provides the following control statements. Click the link to view details of each statement.
| Control statement | Description |
|---|---|
| break statement | terminates loop or switch statement; program flow continues to the next statement immediately following the loop or switch. |
| continue statement | Causes the loop to skip the remainder of its body and immediately restart testing the condition. |
| goto statement | Transfers control to a labeled statement. However, the use of the goto statement in programs is discouraged. |
Infinite loop
If the condition never becomes false, the loop becomes an infinite loop.for loops can be used to implement infinite loops in the traditional sense. Since none of the three expressions that make up the loop is required, you can leave some condition expressions empty to form an infinite loop.
Example
#include
<
iostream
using
namespace
std;
int
main
(
)
{
for
(
; ;
)
{
printf
(
"
This loop will run forever.
\
n
"
)
;
}
return
0
;
}
When the condition expression is absent, it is assumed to be true. You can also set an initial value and an increment expression, but generally C++ programmers prefer to use the for(;;) structure to represent an infinite loop.
**Note:** You can press Ctrl + C to terminate an infinite loop.