7.4.7. Using arrays to Summarize Survey Results

Our next example uses arrays to summarize the results of data collected in a survey. Consider the following problem statement:

Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses in an integer array and determine the frequency of each rating.

This is a popular type of array-processing application (Fig. 7.11). We wish to summarize the number of responses of each type (that is, 1–5). The array responses (lines 15–16) is a 20-element integer array of the students’ responses to the survey. The array responses is declared const, as its values do not (and should not) change. We use a six-element array frequency (line 19) to count the number of occurrences of each response. Each element of the array is used as a counter for one of the survey responses and is initialized to zero. As in Fig. 7.10, we ignore frequency[0].


 1   // Fig. 7.11: fig07_11.cpp
 2   // Poll analysis program.
 3   #include <iostream>
 4   #include <iomanip>
 5   #include <array>
 6   using namespace std;
 7
 8   int main()
 9   {
10      // define array sizes
11      const size_t responseSize = 20; // size of array responses
12      const size_t frequencySize = 6; // size of array frequency
13
14      // place survey responses in array responses
15      const array< unsigned int, responseSize > responses =
16         { 1, 2, 5, 4, 3, 5, 2, 1, 3, 1, 4, 3, 3, 3, 2, 3, 3, 2, 2, 5 };
17
18      // initialize frequency counters to 0
19      array< unsigned int, frequencySize > frequency = {};
20
21      // for each answer, select responses element and use that value
22      // as frequency subscript to determine element to increment
23      for ( size_t answer = 0; answer < responses.size(); ++answer )
24         ++frequency[ responses[ answer ] ];
25
26      cout << "Rating" << setw( 17 ) << "Frequency" << endl;
27
28      // output each array element's value
29      for ( size_t rating = 1; rating < frequency.size(); ++rating )
30         cout << setw( 6 ) << rating << setw( 17 ) << frequency[ rating ]
31            << endl;
32   } // end main


Rating        Frequency
     1                3
     2                5
     3                7
     4                2
     5                3


Fig. 7.11. Poll analysis program.

The first for statement (lines 23–24) takes the responses one at a time from the array responses and increments one of the five counters in the frequency array (frequency[1] to frequency[5]). The key statement in the loop is line 24, which increments the appropriate frequency counter, depending on the value of responses[answer].

Let’s consider several iterations of the for loop. When control variable answer is 0, the value of responses[answer] is the value of responses[0] (i.e., 1 in line 16), so the program interprets ++frequency[responses[answer]] as

++frequency[ 1 ]

which increments the value in array element 1. To evaluate the expression, start with the value in the innermost set of square brackets (answer). Once you know answer’s value (which is the value of the loop control variable in line 23), plug it into the expression and evaluate the expression in the next outer set of square brackets (i.e., responses[answer], which is a value selected from the responses array in lines 15–16). Then use the resulting value as the subscript for the frequency array to specify which counter to increment.

When answer is 1, responses[answer] is the value of responses[1], which is 2, so the program interprets ++frequency[responses[answer]] as

++frequency[ 2 ]

which increments array element 2.

When answer is 2, responses[answer] is the value of responses[2], which is 5, so the program interprets ++frequency[responses[answer]] as

++frequency[ 5 ]

which increments array element 5, and so on. Regardless of the number of responses processed in the survey, the program requires only a six-element array (ignoring element zero) to summarize the results, because all the response values are between 1 and 5 and the subscript values for an six-element array are 0 through 5.

Bounds Checking for array Subscripts

If the data in responses contained an invalid value, such as 13, the program would have attempted to add 1 to frequency[13], which is outside the bounds of the array. When you use the [] operator to access an array element, C++ provides no automatic array bounds checking to prevent you from referring to an element that does not exist. Thus, an executing program can “walk off” either end of an array without warning. In Section 7.10, we demonstrate the class template vector’s at function, which performs bounds checking for you. Class template array also has an at function.

It’s important to ensure that every subscript you use to access an array element is within the array’s bounds—that is, greater than or equal to 0 and less than the number of array elements.

Allowing programs to read from or write to array elements outside the bounds of arrays are common security flaws. Reading from out-of-bounds array elements can cause a program to crash or even appear to execute correctly while using bad data. Writing to an out-of-bounds element (known as a buffer overflow) can corrupt a program’s data in memory, crash a program and allow attackers to exploit the system and execute their own code. For more information on buffer overflows, see en.wikipedia.org/wiki/Buffer_overflow.


Image Common Programming Error 7.3

Referring to an element outside the array bounds is an execution-time logic error. It isn’t a syntax error.



Image Error-Prevention Tip 7.1

When looping through an array, the index should never go below 0 and should always be less than the total number of array elements (one less than the size of the array). Make sure that the loop-termination condition prevents accessing elements outside this range. In Chapters 1516, you’ll learn about iterators, which can help prevent accessing elements outside an array’s (or other container’s) bounds.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.102.90