|
|
|
|
|
|
|
The simplest way to access a component is to look in a given location. For example, a user enters map coordinates that we use as indices into an array of street names to access the sought-after name at those coordinates. This process is referred to as random access because the user may enter any set of coordinates at random. |
|
|
|
|
|
|
|
|
There are many cases in which we might wish to perform an operation on all the elements of a particular row or column in a table. Look back at the hiTemp array pictured in Figure 133, where the rows represent weeks of the year and the columns represent days of the week. The data represents the high temperatures for each day in a year. If we wanted the average high temperature for a given week, we would sum the values in that row and divide by 7. If we wanted the average for a given day of the week, we would sum the values in that column and divide by 52. The former case is access along rows; the latter case is access along columns. |
|
|
|
|
|
|
|
|
Now, suppose that we wish to determine the average for the year. We must access every element in the array, sum them, and divide by 364. In this case, the order of accessby row or by columnis not important. (The same is true when we initialize every element of an array to 0.) This is access throughout the array. |
|
|
|
|
|
|
|
|
There are situations when we must access every element in an array in a particular order, either by rows or by columns. For example, if we wanted the average for every week, we would run through the entire array, taking each row in turn. However, if we wanted the average for each day of the week, we would run through the array a column at a time. |
|
|
|
|
|
|
|
|
Let's take a closer look at these patterns of access by considering four common examples of array processing. |
|
|
|
|
|
|
|
|
3. Initialize the table to all zeroes (or some special value). |
|
|
|
|
|
|
|
|
First, let's define some constants and variables using general identifiers, such as row and col, rather than problem-dependent identifiers. Then let's look at each algorithm in terms of generalized table processing. |
|
|
|
|
|
|
|
|
const int NUM_ROWS = 50;
const int NUM_COLS = 50;
int table [NUM_ROWS] [NUM_COLS]; // A two-dimensional array
int rowLength; // Data is in 0..rowLength1
int row; // A row index
int colLength; // Data is in 0..colLength1
int col; // A column index
int total; // A variable for summing |
|
|
|
|
|