< previous page page_605 next page >

Page 605
result into totalOccupants. Next, counter becomes 1 and the loop test occurs. The second loop iteration adds the contents of totalOccupants to the contents of occupants[1], storing the result into totalOccupants. Now counter becomes 2 and the loop test is made. You can confirm that the loop invariant is true just before the test occurs: totalOccupants equals the sum of occupants[0] through occupants[1], and 0<counter < 350 because counter is 2. Eventually, the loop adds the contents of occupants[349] to the sum and increments counter to 350. Just before the loop test occurs, the loop invariant is true because totalOccupants is the sum of occupants[0] through occupants[349] and counter equals 350. At this point, the loop condition is false, and control exits the loop.
Note how we used the named constant BUILDING_SIZE in both the array declaration and the For loop. When constants are used in this manner, changes can be made easily. If the number of apartments changes from 350 to 400, only the const declaration of BUILDING_SIZE needs to be changed. If the literal value 350 were used in place of BUILDING_SIZE, several of the statements in the code above, and probably many more throughout the rest of the program, would have to be changed.
Because an array index is an integer value, we can access the components by their position in the array-that is, the first, the second, the third, and so on, until the last. Using an int index is the most common way of thinking about an array. C++, however, provides more flexibility by allowing an index to be of any integral type. (The index expression still must evaluate to an integer in the range from 0 through one less than the array size.) The next example shows an array where the indices are values of an enumeration type.
enum Drink {ORANGE, COLA, ROOT_BEER, GINGER_ALE, CHEERY, LEMON};

float salesAmt[6]; // Array of 6 floats, to be indexed by Drink type
Drink flavor;      // Variable of the index type
Drink is an enumeration type in which the enumerators ORANGE, COLA, ..., LEMON have internal representations 0 through 5, respectively. salesAmt is a group of six float components representing dollar sales figures for each kind of drink (see Figure 11-7). The following code prints the values in the array (see Chapter 10 to review how to increment values of enumeration types in For loops).
for (flavor = ORANGE; flavor <= LEMON; flavor = Drink(flavor + 1))

        // Invariant (prior to test):
        //     salesAmt[0..int(flavor)-1] have been output
        //  && ORANGE <= flavor <= int(LEMON) + 1

    cout << salesAmt[flavor] << endl;

 
< previous page page_605 next page >