Programming in C

(Barry) #1

100 Chapter 7 Working with Arrays


Program 7.1 Output
values[0] = 197
values[1] = 0
values[2] = -101
values[3] = 547
values[4] = 0
values[5] = 350
values[6] = 0
values[7] = 0
values[8] = 0
values[9] = 35

The variable indexassumes the values 0through 9 as the last valid subscript of an array
is always one less than the number of elements (due to that zeroth element). Because you
never assigned valuesto five of the elements in the array—elements 1, 4, and 6 through
8—the valuesthat are displayed for them are meaningless. Even though the program’s
output shows these values as zero, the value of any uninitialized variable or array element
is not defined. For this reason, no assumption should ever be made as to the value of an
uninitialized variable or array element.

Using Array Elements as Counters


It’s now time to consider a slightly more practical example. Suppose you took a tele-
phone survey to discover how people felt about a particular television show and you
asked each respondent to rate the show on a scale from 1 to 10, inclusive. After inter-
viewing 5,000 people, you accumulated a list of 5,000 numbers. Now, you want to ana-
lyze the results. One of the first pieces of data you want to gather is a table showing the
distribution of the ratings. In other words, you want to know how many people rated
the show a 1, how many rated it a 2, and so on up to 10.
Although not an impossible chore, it would be a bit tedious to go through each
response and manually count the number of responses in each rating category. In addi-
tion, if you have a response that could be answered in more than 10 ways (consider the
task of categorizing the age of the respondent), this approach would be even more
unreasonable. So, you want to develop a program to count the number of responses for
each rating.The first impulse might be to set up 10 different counters, called perhaps
rating_1through rating_10, and then to increment the appropriate counter each time
the corresponding rating was entered. But once again, if you are dealing with more than
10 possible choices, this approach could become a bit tedious. And besides, an approach
that uses an array provides the vehicle for implementing a much cleaner solution, even in
this case.
You can set up an array of counters called ratingCounters, for example, and then
you can increment the corresponding counter as each response is entered.To conserve
space in this book, Program 7.2 assumes you are dealing with only 20 responses. In addi-
tion, it’s always good practice to first get a program working on a smaller test case before
Free download pdf