The break-Statement

  1. The break-statement can be used within a loop to exit it prematurely.

  2. When the break-statement is executed within a loop, the loop ends immediately and execution continues with the statement following the loop statement.

  3. In a nested loop, the break statement interrupts only the loop it is placed in.

  4. The following example from the textbook illustrates how the break-statement is used:

    // Sums up to 10 negative numbers entered from the keyboard,
    // or until a positive number is entered.
    // Make sure that the positive number is not included in computing the sum

    #include <iostream>
    using namespace std;

    int main( )
    {
       int number, sum = 0, count = 0;
       cout << "Enter 10 negative numbers:\n";

       while (++count <= 10)
       {
          cin >> number;

          if (number >= 0)
          {
             cout << "ERROR: positive number"
                << " or zero was entered as the\n"
                << count << "the number! Input ends "
                << "with the " << count << "th number.\n"
                << count << "the number was not added in.\n";
             break;
          }

          sum = sum + number;
       }

       cout << sum << " is the sum of the first "
                << (count - 1) << " numbers.\n";

       return 0;
    }