How to Apply Special Loop Controls in C++ - dummies

How to Apply Special Loop Controls in C++

By Stephen R. Davis

C++ defines two special flow-control commands known as break and continue. Sometimes the condition for terminating a loop occurs at neither the beginning nor the end of the loop, but in the middle. Consider a program that accumulates numbers of values entered by the user. The loop terminates when the user enters a negative number.

The challenge with this problem is that the program can’t exit the loop until the user has entered a value but must exit before the value is added to the sum.

For these cases, C++ defines the break command. When encountered, the break causes control to exit the current loop immediately. Control passes from the break statement to the statement immediately following the closed brace at the end of the loop.

The format of the break commands is as follows:

while(condition) // break works equally well in for loop
    if (some other condition)
        break;   // exit the loop
}                // control passes here when the
                 // program encounters the break

Armed with this new break command, one solution to the accumulator problem appears as the program BreakDemo:

// BreakDemo - input a series of numbers.
//             Continue to accumulate the sum
//             of these numbers until the user
//             enters a negative number.
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
    // input the loop count
    int accumulator = 0;
    cout << "This program sums values from the usern"
         << "Terminate by entering a negative number"
         << endl;
    // loop "forever"
        // fetch another number
        int nValue = 0;
        cout << "Enter next number: ";
        cin  >> nValue;
        // if it's negative...
        if (nValue < 0)
            // ...then exit
        // ...otherwise add the number to the accumulator
        accumulator += nValue;
    // now that we've exited the loop
    // output the accumulated result
    cout << "nThe total is "
         << accumulator
         << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    return 0;

After explaining the rules to the user (entering a negative number to terminate and so on), the program enters what looks like an infinite for loop. Once within the loop, BreakDemo retrieves a number from the keyboard. Only after the program has read the number can it test to see whether that number matches the exit criteria.

If the input number is negative, control passes to the break, causing the program to exit the loop. If the input number is not negative, control skips over the break command to the expression that sums the new value into the accumulator. After the program exits the loop, it outputs the accumulated value and then exits.

When performing an operation on a variable repeatedly in a loop, make sure that the variable is initialized properly before entering the loop. In this case, the program zeroes accumulator before entering the loop where nValue is added to it.

The result of an example run appears as follows:

This program sums values from the user
Terminate by entering a negative number
Enter next number: 1
Enter next number: 2
Enter next number: 3
Enter next number: -1
The total is 6
Press Enter to continue...

The similar continue command is used less frequently. When the program encounters the continue command, it immediately moves back to the top of the loop. The rest of the statements in the loop are ignored for the current iteration.

The following example snippet ignores negative numbers that the user might input. Only a 0 terminates this version (the complete program appears on the website as ContinueDemo):

while(true)    // this while() has the same effect as for(;;)
    // input a value
    cout << "Input a value:";
    cin  >> nValue;
   // if the value is negative...
    if (nValue < 0)
        // ...output an error message...
        cout << "Negative numbers are not allowedn";
        // ...and go back to the top of the loop
    // ...continue to process input like normal