11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

72 Part I: Introduction to C++ ProgrammingOnce within the loop, BreakDemo retrieves a number from the keyboard. Onlyafter the program has read a number can it test to see whether the number itjust read matches the exit criteria. If the input number is negative, controlpasses to the break, causing the program to exit the loop. If the input numberis not negative, control skips over the break command to the expression thatsums the new value into the accumulator. After the program exits the loop, itoutputs the accumulated value and then exits.When performing an operation on a variable repeatedly in a loop, make surethat the variable is initialized properly before entering the loop. In this case,the program zeros accumulator before entering the loop where value isadded to it.The result of an example run appears as follows:This program sums values entered by the userTerminate the loop by entering a negative numberEnter next number: 1Enter next number: 2Enter next number: 3Enter next number: -1The total is 6Press any key to continue . . .The continue command is used less frequently. When the program encountersthe 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 mightinput. Only a zero terminates this version (the complete program appears onthe CD-ROM as ContinueDemo):while(true) // this while() has the same effect as for(;;){// input a valuecout > value;// if the value is negative...if (value < 0){// ...output an error message...cout

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!