Sams Teach Yourself C++ in 21 Days

(singke) #1
More on Program Flow 183

7


Examining while (true)Loops....................................................................


The condition tested in a whileloop can be any valid C++ expression. As long as that
condition remains true, the whileloop continues. You can create a loop that never ends
by using the value truefor the condition to be tested. Listing 7.5 demonstrates counting
to 10 using this construct.

LISTING7.5 whileLoops


1: // Listing 7.5
2: // Demonstrates a while true loop
3: #include <iostream>
4:
5: int main()
6: {
7: int counter = 0;
8:
9: while (true)
10: {
11: counter ++;
12: if (counter > 10)
13: break;
14: }
15: std::cout << “Counter: “ << counter << std::endl;
16: return 0;
17: }

Counter: 11

On line 9, a whileloop is set up with a condition that can never be false. The
loop increments the counter variable on line 11, and then on line 12 it tests to see

OUTPUT


The breakStatement
break;causes the immediate end of a while, do...while, or forloop. Execution jumps to
the closing brace.
Example
while (condition)
{
if (condition2)
break;
// statements;
}

ANALYSIS
Free download pdf