6.6 break Statement
We have used a while statement to compute Fibonacci numbers
less than 100. The loop exits when the condition at the beginning
becomes false. Loops also can be exited at any point through the use
of a break statement.
Suppose you want to add a series of numbers and you
don't know how many numbers are to be added
together. You want to read numbers and need some way of letting the
program know it has reached the end of the list. Example 6-2 allows
you to use the number zero (0) to signal the end of the list.
Note that the while statement begins
with:
while (true) {
The program will loop forever because the while would exit only when the expression
true is false. The only way to
exit this loop is through a break
statement.
We detect the end-of-list indicator (zero) with the statement
following if statement, then use
break to exit the loop.
if (item == 0)
break;
Example 6-2. total/total.cpp
#include <iostream>
int total; // Running total of all numbers so far
int item; // next item to add to the list
int main( )
{
total = 0;
while (true) {
std::cout << "Enter # to add \n";
std::cout << " or 0 to stop:";
std::cin >> item;
if (item == 0)
break;
total += item;
std::cout << "Total: " << total << '\n';
}
std::cout << "Final total " << total << '\n';
return (0);
}
Note that this program makes use of an old programming trick called
an indicator to end the input. In this example, our end-of-input
indicator is the number 0.
|