< previous page page_728 next page >

Page 728
(text box continued from previous page)
Even though the components are all of the same data type, they represent different things. The components in the Item Number column represent an identifying number; those in the Number Sold column represent the quantity sold; the Cost per Item column contains prices; and the Tax Rate column holds percentages. Defining this structure as a set of four parallel arrays also allows us to represent Item Number and Number Sold with integers, which are a better choice for this type of information.
To decide whether to use parallel arrays or a multidimensional array, we can ask three questions:
1. Are all the components of the same data type?
2. Do all the components represent the same kinds of values?
3. Can a set of independent features be used as indices to select a component?
If the answer to all three questions is yes, a multidimensional array is appropriate. Otherwise, parallel arrays are a better choice.
In some cases, a single data structure is more appropriate than multiple arrays. In the next chapter, we look at a data structure called a record, a structure that allows us to group nonhomogeneous items. As we introduce more data structures, we provide additional guidelines on how to choose among them.

Problem-Solving Case Study City Council Election
0728-01.gif
Problem: There has just been a hotly contested city council election. In four voting precincts, citizens have cast their ballots for four candidates. Let's do an analysis of the votes for the four candidates by precinct. We want to know how many votes each candidate received in each precinct, how many total votes each candidate received, and how many total votes were cast in each precinct.
Input: An arbitrary number of votes in a file voteFile, with each vote represented as a pair of numbers: a precinct number (1 through 4) and a candidate number (1 through 4); and candidate names, entered from the keyboard (to be used for printing the output).
Output: The following three items, written to a file reportFile: a table showing how many votes each candidate received in each precinct, the total number of votes for each candidate, and the total number of votes in each precinct.

 
< previous page page_728 next page >