< previous page page_278 next page >

Page 278
If statement can contain other While and If statements. By nesting, we can create complex control structures.
Suppose we want to extend our code for counting commas on one line, repeating it for all the lines in a file. We put an EOF-controlled loop around it:
cin.get(inChar);               // Initialize outer loop
while (cin)                    // Outer loop test
{
    commaCount = 0;            // Initialize inner loop
                               //   (Priming read is taken care of
                               //    by outer loop's priming read)
    while (inChar != \n)     // Inner loop test
    {
        if (inChar == ,)
            commaCount++;
        cin.get(inChar);       // Update inner termination condition
    }
    cout << commaCount << endl;
    cin.get(inChar);           // Update outer termination condition
}
In this code, notice that we have omitted the priming read for the inner loop. The priming read for the outer loop has already primed the pump. It would be a mistake to include another priming read just before the inner loop; the character read by the outer priming read would be destroyed before we could test it.
Let's examine the general pattern of a simple nested loop:
Initialize outer loop
while (Outer loop condition)
{
  .
  .
  .
 Initialize inner loop
 while (Inner loop condition)
 {
  Inner loop processing and update
 }
  .
  .
  .
 Outer loop update
}
Notice that each loop has its own initialization, test, and update. The dots represent places where processing may take place in the outer loop. It's pos-

 
< previous page page_278 next page >