Loops
A loop statement allows you to execute a statement multiple
times. Two loop statements, for and
while, test at the top of the loop.
The do statement tests at the bottom,
thereby ensuring that the loop body executes at least once. This section
describes the loop statements. See Section 4.6 for additional
statements that affect or control loop execution.
A loop statement can declare variables in the scope of the loop’s substatement. Every time the loop iterates, it reenters the substatement scope. This means objects that are declared in the substatement (and in the loop’s condition) are created and destroyed with every loop iteration.
while Statements
A while statement repeats a statement while a condition is
true. The syntax is:
while (condition)statement
The condition is evaluated and
converted to bool. If the value is
true,
statement is executed, and the loop
repeats. If the value is false, the
loop finishes and execution continues with the subsequent statement.
Thus, if condition is false the first time it is evaluated, the
statement is never executed.
A continue statement in a while
loop branches to the top of the loop, and execution continues with the
evaluation of condition. A break statement exits immediately.
A while loop is typically
used for unbounded iteration, that is, when you don’t know beforehand
how many times a loop will iterate. Example 4-5 shows how the while loop can be used to control
I/O.
#include <algorithm> ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access