9. PAY PARTICULAR ATTENTION TO THE CHANGE IN THE CONTROLLING BOOLEAN...

2.9. Pay particular attention to the change in the controlling Boolean expression.

Loops 81

Display 2.8 A break Statement in a Loop1 #include <iostream>2 using namespace std;3 int main( )4 {5 int number, sum = 0, count = 0;6 cout << "Enter 4 negative numbers:\n";7 while (++count <= 4) 8 {9 cin >> number;10 if (number >= 0)11 {12 cout << "ERROR: positive number"13 << " or zero was entered as the\n"14 << count << "th number! Input ends "15 << "with the " << count << "th number.\n"16 << count << "th number was not added in.\n";17 break;18 }19 sum = sum + number;20 }21 cout << sum << " is the sum of the first " 22 << (count - 1) << " numbers.\n";23 return 0;24 }SAMPLE DIALOGUEEnter 4 negative numbers:-1 -2 3 -4ERROR: positive number or zero was entered as the3rd number! Input ends with the 3rd number.3rd number was not added in-3 is the sum of the first 2 numbers.

82 Flow of Control

Display 2.9 A continue Statement in a Loop6 cout << "Enter 4 negative numbers, ONE PER LINE:\n";7 while (count < 4) 12 cout << "ERROR: positive number (or zero)!\n"13 << "Reenter that number and continue:\n";14 continue;15 }16 sum = sum + number;17 count++;18 }19 cout << sum << " is the sum of the " 20 << count << " numbers.\n";21 return 0;22 }Enter 4 negative numbers, ONE PER LINE:1ERROR: positive number (or zero)!Reenter that number and continue:-1-23ERROR: positive number!-3-4-10 is the sum of the 4 numbers.

Chapter Summary 83

Note that you never absolutely need a

break

or

continue

statement. The programs

in Displays 2.8 and 2.9 can be rewritten so that neither uses either a

break

or

continue

statement. The

continue

statement can be particularly tricky and can make your code

hard to read. It may be best to avoid the

continue

statement completely or at least use

it only on rare occasions.

NESTED LOOPS

It is perfectly legal to nest one loop statement inside another loop statement. When

doing so, remember that any

break

or

continue

statement applies to the innermost

loop (or

switch

) statement containing the

break

or

continue

statement. It is best to

avoid nested loops by placing the inner loop inside a function definition and placing a

function invocation inside the outer loop. Functions are introduced in Chapter 3.

Self-Test Exercises