|
|
|
|
|
|
|
When the termination condition occurs and the flow of control passes to the statement following the loop, the variables used in the loop still contain values. And if the cin stream has been used, the reading marker has been left at some point in the stream. Or maybe an output file has new contents. If these variables or files are used elsewhere in the program, the loop must leave them ready to be used. So, the final step in designing a loop is answering this question: |
|
|
|
|
|
|
|
|
What is the state of the program on exiting the loop? |
|
|
|
|
|
|
|
|
Now we have to consider the consequences of our design and double check its validity. For example, suppose we've used an event counter and later processing depends on the number of events. It's important to be sure (with an algorithm walk-through) that the value left in the counter is the exact number of eventsthat it is not off by 1. |
|
|
|
|
|
|
|
|
Look at this code segment: |
|
|
|
|
|
|
|
|
commaCount = 1; // This code is incorrect
cin.get(inChar);
while (inChar != \n)
{
if (inChar == ,)
commaCount++;
cin.get(inChar);
}
cout << commaCount << endl; |
|
|
|
|
|
|
|
|
This loop reads characters from an input line and counts the number of commas on the line. However, when the loop terminates, commaCount equals the actual number of commas plus 1 because the loop initializes the event counter to 1 before any events take place. By determining the state of commaCount at loop exit, we've detected a flaw in the initialization. commaCount should be initialized to zero. |
|
|
|
|
|
|
|
|
Designing correct loops depends as much on experience as it does on the application of design methodology. At this point, you may want to read through the first two problem-solving case studies at the end of the chapter to see how the loop design process is applied to some real problems. |
|
|
|
|
|
|
|
|
In Chapter 5, we described nested If statements. It's also possible to nest While statements. Both While and If statements contain statements and are themselves statements. So the body of a While statement or the branch of an |
|
|
|
|
|