Programming in C

(Barry) #1

102 Chapter 7 Working with Arrays


Bad response: 15
5
5
1
7
4
10
5
5
6
8
9

Rating Number of Responses
------ -------------------
1 1
2 0
3 1
4 1
5 6
6 3
7 2
8 2
9 2
10 1

The arrayratingCountersis defined to contain 11 elements. A valid question you
might ask is, “If there are only 10 possible responses to the survey, why is the array
defined to contain 11 elements rather than 10?”The answer lies in the strategy for
counting the responses in each particular rating category. Because each response can be a
number from 1 to 10, the program keeps track of the responses for any one particular
rating by simply incrementing the corresponding array element (after first checking to
make certain that the user entered a valid response between 1 and 10). For example, if a
rating of 5 is typed in, the value of ratingCounters[5]is incremented by one. By
employing this technique, the total number of respondents who rated the TV show a 5
are contained in ratingCounters[5].
The reason for 11 elements versus 10 should now be clear. Because the highest rating
number is a 10, you must set up your array to contain 11 elements to index
ratingCounters[10],remembering that because of the zeroth element, the number of
elements in an array is always one more than the highest index number. Because no
response can have a value of zero,ratingCounters[0]is never used. In fact, in the for
loops that initialize and display the contents of the array, note that the variable istarts at
1 , and thereby bypasses the initialization and display of ratingCounters[0].

Program 7.2 Continued
Free download pdf