< previous page page_726 next page >

Page 726
0726-01.gif
Figure 13-9
Graphical Representation of Array Variable
sales
Because item controls the outer For loop, we are summing each item's sales by month and store. If we want to find the total sales for each store, we use store to control the outer For loop, summing its sales by month and item with the inner loops.
for (store = 0; store < NUM_STORES; store++)
{
    numberSold = 0;
    for (item = 0; item < NUM_ITEMS; item++)
         for (month = 0; month <= currentMonth; month++)
             numberSold = numberSold + sales[store][month][item];
    cout << Store # << store <<  Sales to date =  << numberSold
         <<  endl;
}
It takes two loops to access each component in a two-dimensional array; it takes three loops to access each component in a three-dimensional array. The task to be accomplished determines which index controls the outer loop, the middle loop, and the inner loop. If we want to calculate monthly sales by store, month controls the outer loop and store controls the middle loop. If we want to calculate monthly sales by item, month controls the outer loop and item controls the middle loop.
If we want to keep track of the departments that sell each item, we can add a fourth dimension.
enum Departments {A, B, C, D, E, F, G};
const int NUM_DEPTS = 7;
typedef int SalesType[NUM_STORES][12][NUM_ITEMS][NUM_DEPTS];
How would we visualize this new structure? Not very easily! Fortunately, we do not have to visualize a structure in order to use it. If we want the

 
< previous page page_726 next page >