< previous page page_265 next page >

Page 265
    if (number < 0)             // Test input value
        nonNegative = FALSE;     // Set flag if event occurred
    else
        sum = sum + number;
}
Notice that we can code sentinel-controlled loops with flags. In fact, this code uses a negative value as a sentinel.
You do not have to initialize flags to TRUE; you can initialize them to FALSE. If you do, you must use the NOT operator (!) in the While expression and reset the flag to TRUE when the event occurs. Compare the code segment above with the one below; both perform the same task. (Assume that negative is a Boolean variable.)
sum = 0;
negative = FALSE;                // Initialize flag
while ( !negative )
{
    cin >> number;
    if (number < 0)             // Test input value
        negative = TRUE;         // Set flag if event occurred
    else
        sum = sum + number;
}
As one more example, look at the While statement in the Payroll program of Chapter 1 (page 35). This is a sentinel-controlled loop because an employee number (empNum) with a value of 0 is used to stop the loop. We could have used a flag instead, as follows. (moreData is a Boolean variable.)
cin >> empNum;
moreData = (empNum != 0);        // moreData is TRUE if empNum != 0
while (moreData)
{
    .
    .
    .
    cin >> empNum;               // Get the next employee number
    moreData = (empNum != 0);    // Update the flag accordingly
}
Looping Subtasks
We have been looking at ways to use loops to affect the flow of control in programs. Looping by itself does nothing. The loop body must perform a task in order for the loop to accomplish something. In this section, we look at three taskscounting, summing, and keeping track of a previous valuethat often are used in loops.

 
< previous page page_265 next page >