< previous page page_604 next page >

Page 604
Passing an array as a parameter gives the function access to the entire array. Later in the chapter, we look at parameter passage in detail.
Examples of Declaring and Accessing Arrays
We now look in detail at some specific examples of declaring and accessing arrays. Here are some declarations that a program might use to analyze occupancy rates in an apartment building:
const int BUILDING_SIZE = 350;   // Number of apartments

int occupants[BUILDING_SIZE];    // occupants[i] is the number of
                                 //   occupants in apartment i
int totalOccupants;              // Total number of occupants
int counter;                     // Loop control and index variable
occupants is a 350-element array of type int (see Figure 11-6). occupants[0] =3 if the first apartment has three occupants; occupants[1] =5 if the second apartment has five occupants; and so on. If values have been stored into the array, then the following code totals the number of occupants in the building.
totalOccupants = 0;
for (counter = 0; counter < BUILDING_SIZE; counter++)

        // Invariant (prior to test):
        //     totalOccupants == sum of occupants[0..counter-1]
        //  && 0 <= counter <= BUILDING_SIZE

    totalOccupants = totalOccupants + occupants[counter];
The first time through the loop, counter is 0. We add the contents of totalOccupants (which is 0) to the contents of occupants[0], storing the
0604-01.gif
Figure 11-6
occupants Array

 
< previous page page_604 next page >