< previous page page_634 next page >

Page 634
//******************************************************************

void Print( /* in */ const int freqCount[] )  // List of char counts

// Prints each character and its frequency (if nonzero)

// Precondition:
//     freqCount[MIN_CHAR..MAX_CHAR] are assigned
// Postcondition:
//     For all i, where MIN_CHAR <= i <= MAX_CHAR,
//         IF freqCount[i] > 0
//             freqCount[i] and the char equivalent of i
//             have been printed

{
    char index;  // Loop control and index variable

    for (index = MIN_CHAR; index <= MAX_CHAR; index++)

            // Invariant (prior to test):
            //     For all i, where MIN_CHAR <= i <= index-1,
            //         IF freqCount[i] > 0
            //             freqCount[i] and the char equivalent of i
            //             have been printed
            //  && MIN_CHAR <= index <= MAX_CHAR+1

        if (freqCount[index] > 0)
            cout << index << " occurred "
                 << setw(3) << freqCount[index] << " time(s)"
                 << end1;
}
See how much simpler the solution becomes when we take advantage of the fact that the character itself can be the index to its own frequency counter? In Case Study Follow-Up Question 3 at the end of this chapter, you are asked to modify this program to handle the case in which a specified subset of the characters is counted (as was done in the previous case study).
Using the same input file as was used in the previous problem,
Roses are red,
violets are blue.
If I can learn C++,
so can you.
we get the following output from the CountAll program:

 
< previous page page_634 next page >