While Loop
We will examine how Boolean expressions can be used in a while statement. A while statement makes a program repeats a statement or group of statements. Such repetitions are called loops.
while loop
count-controlled loop
event-controlled loop
A while loop
The syntax of the while loop is:
while ( Expression )
{
Statement
}
A while statement allows a program to continue executing a statement as long as the value of the Boolean expression is true. When the Boolean expression is evaluated as false, execution of the program continues with the statement immediately following the while statement.
Count-controlled while loop
Now let s look at the following C++ code:
sum = 0;
count = 1;
while (count <= 10)
{
cout << "Enter a value: ";
cin >> value;
sum = sum + value;
count++;
}
cout << "The sum of the 10 numbers is "
<< sum << endl;
The variables sum and count are assigned the values 0 and 1 respectively.
The Boolean expression (count <= 10) is evaluated. Because the value in count is less than or equal to 10, the expression is true and the compound statement (block) associated with the While statement is executed. A number is extracted from the standard input stream and added to the sum.
The value in count is incremented by 1.
The While expression is evaluated again. Because the value stored in the count is still less than 10, the compound satatement associated with the While statement is executed again. This process countinues until count contains the value 11. At that time, the expression is no longer true, the body of the While loop is not executed again, and the execution continues with the statement immediately following the While statement. In this case, it continues with a cout that sends the labeled answer to the output stream.
Count-controlled while loop
A count-controlled loop is one that is executed a certain number of times. The above example shows a count-controlled loop. We know that the program sends the answer to the output stream after excuting the loop body 10 times. Now let s look at another loop control structure --- event-controlled loop.
Event-controlled loop
An event-controlled loop is one whose execution is controlled by the occurence of an event whithin the loop itself. Now let s look at an example of an event-controlled loop that reads and sums value from cin until a negative value is encountered.
sum = 0;
cout << "Enter a value: ";
cin >> value;