6.7 continue Statement

I l @ ve RuBoard

The continue statement is similar to the brea k 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); } 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net