20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

102 Chapter 7 Work<strong>in</strong>g with Arrays<br />

Program 7.2<br />

Bad response: 15<br />

5<br />

5<br />

1<br />

7<br />

4<br />

10<br />

5<br />

5<br />

6<br />

8<br />

9<br />

Cont<strong>in</strong>ued<br />

Rat<strong>in</strong>g Number of Responses<br />

------ -------------------<br />

1 1<br />

2 0<br />

3 1<br />

4 1<br />

5 6<br />

6 3<br />

7 2<br />

8 2<br />

9 2<br />

10 1<br />

The array rat<strong>in</strong>gCounters is def<strong>in</strong>ed to conta<strong>in</strong> 11 elements. A valid question you<br />

might ask is,“If there are only 10 possible responses to the survey, why is the array<br />

def<strong>in</strong>ed to conta<strong>in</strong> 11 elements rather than 10?”The answer lies <strong>in</strong> the strategy for<br />

count<strong>in</strong>g the responses <strong>in</strong> each particular rat<strong>in</strong>g category. Because each response can be a<br />

number from 1 to 10, the program keeps track of the responses for any one particular<br />

rat<strong>in</strong>g by simply <strong>in</strong>crement<strong>in</strong>g the correspond<strong>in</strong>g array element (after first check<strong>in</strong>g to<br />

make certa<strong>in</strong> that the user entered a valid response between 1 and 10). For example, if a<br />

rat<strong>in</strong>g of 5 is typed <strong>in</strong>, the value of rat<strong>in</strong>gCounters[5] is <strong>in</strong>cremented by one. By<br />

employ<strong>in</strong>g this technique, the total number of respondents who rated the TV show a 5<br />

are conta<strong>in</strong>ed <strong>in</strong> rat<strong>in</strong>gCounters[5].<br />

The reason for 11 elements versus 10 should now be clear. Because the highest rat<strong>in</strong>g<br />

number is a 10, you must set up your array to conta<strong>in</strong> 11 elements to <strong>in</strong>dex<br />

rat<strong>in</strong>gCounters[10],remember<strong>in</strong>g that because of the zeroth element, the number of<br />

elements <strong>in</strong> an array is always one more than the highest <strong>in</strong>dex number. Because no<br />

response can have a value of zero, rat<strong>in</strong>gCounters[0] is never used. In fact, <strong>in</strong> the for<br />

loops that <strong>in</strong>itialize and display the contents of the array, note that the variable i starts at<br />

1, and thereby bypasses the <strong>in</strong>itialization and display of rat<strong>in</strong>gCounters[0].

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!