Solving Problems with Arrays 71
Here, the variable highPosition takes the place of highest. Because we
aren’t directly tracking the grade closest to the average, when it’s time to com-
pare the closest grade against the current grade, we use
highPosition as a refer-
ence into
studentArray . If the grade in the current array position is higher,
the current position in our processing loop is assigned to
highPosition .
Once the loop is over, we can access the name of the student with the grade
closest to the average using
studentArray[highPosition].name, and we can also
access any other data related to that student record.
Multidimensional Arrays
So far, we’ve only discussed one-dimensional arrays because they are the most
common. Two-dimensional arrays are uncommon, and arrays with three or
more dimensions are rare. That’s because most data is one-dimensional by
nature. Furthermore, data that is inherently multidimensional can be repre-
sented as multiple single-dimension arrays, so using a multidimensional array
is always the choice of the programmer. Consider the business license data of
Table 3-1. That’s clearly multidimensional data. I mean, look at it—it’s a grid!
I represented this multidimensional data, however, as two one-dimensional
arrays,
categoryThresholds and licenseCost. I could have represented the data
table as a two-dimensional array, like this:
const double licenseData[2][numberCategories] = {
{0.0, 50000.0, 150000.0, 500000.0},
{50.0, 200.0, 1000.0, 5000.0}
};
It’s difficult to discern any advantage from combining the two arrays into
one. None of our code is simplified because there is no reason to process all
of the data in the table at once. What is clear, though, is that we have lowered
the readability and ease of use for our table data. In the original version, the
names of the two separate arrays make it clear what data is stored in each.
With the combined array, we programmers will have to remember that refer-
ences of the form
licenseData[0][] refer to the gross sales thresholds of the
different business categories, while references of the form
licenseData[1][]
refer to business license costs.
Sometimes it does make sense to use a multidimensional array, though.
Suppose we are processing the monthly sales data for three sales agents, and
one of the tasks is finding the highest monthly sales, from any agent. Having
all of the data in one 3 x 12 array means we can process the entire array at
once, using nested loops:
const int NUM_AGENTS = 3;
const int NUM_MONTHS = 12;
int sales[NUM_AGENTS][NUM_MONTHS] = {
{1856, 498, 30924, 87478, 328, 2653, 387, 3754, 387587, 2873, 276, 32},
{5865, 5456, 3983, 6464, 9957, 4785, 3875, 3838, 4959, 1122, 7766, 2534},
{23, 55, 67, 99, 265, 376, 232, 223, 4546, 564, 4544, 3434}
};