Sams Teach Yourself C++ in 21 Days

(singke) #1
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
Complete. Counter: 5.
This simple program demonstrates the fundamentals of the whileloop. On line
8, an integer variable called counteris created and initialized to zero. This is
then used as a part of a condition. The condition is tested, and if it is true, the body of
the whileloop is executed. In this case, the condition tested on line 10 is whether
counteris less than 5. If the condition is true, the body of the loop is executed; on line
12, the counter is incremented, and on line 13, the value is printed. When the conditional
statement on line 10 fails (when counteris no longer less than 5 ), the entire body of the
whileloop (lines 11–14) is skipped. Program execution falls through to line 15.
It is worth noting here that it is a good idea to always use braces around the block exe-
cuted by a loop, even when it is just a single line of code. This avoids the common error
of inadvertently putting a semicolon at the end of a loop and causing it to endlessly
repeat—for instance,
int counter = 0;
while ( counter < 5 );
counter++;
In this example, the counter++is never executed.

OUTPUT


178 Day 7


ANALYSIS

The whileStatement
The syntax for the whilestatement is as follows:
while ( condition)
statement;
conditionis any C++ expression, and statementis any valid C++ statement or block of
statements. When conditionevaluates true, statementis executed, and then condition
is tested again. This continues until conditiontests false, at which time the whileloop
terminates and execution continues on the first line below statement.
Example
// count to 10
int x = 0;
while (x < 10)
cout << “X: “ << x++;
Free download pdf