6.7 continue Statement
The
continue statement is similar to the
break statement,
except that instead of terminating the loop, it starts re-executing
the body of the loop from the top. For example,
let's modify the previous program to total only
numbers larger than 0. This means that when you see a negative
number, you want to skip the rest of the loop. To do this you need an
if to check for negative numbers and a
continue to restart the loop. The result is Example 6-3.
Example 6-3. total2/total2.cpp
#include <iostream>
int total; // Running total of all numbers so far
int item; // next item to add to the list
int minus_items; // number of negative items
int main( )
{
total = 0;
minus_items = 0;
while (true) {
std::cout << "Enter # to add\n";
std::cout << " or 0 to stop:";
std::cin >> item;
if (item == 0)
break;
if (item < 0) {
++minus_items;
continue;
}
total += item;
std::cout << "Total: " << total << '\n';
}
std::cout << "Final total " << total << '\n';
std::cout << "with " << minus_items << " negative items omitted\n";
return (0);
}
|