//***************************************************************** // R. A. Hillyard // histogram.cpp // March 2001 // // Accept exam scores (between 0 and 100) from the user. The end-of-input will // be signalled by the value -1. Display a histogram of those scores by printing // the number of scores between 0 & 9, between 10 & 19, between 20 & 29, etc. // Method: // range[0] holds the number of scores between 0 and 9 // range[1] holds the number of scores between 10 and 19 // | // | // | // range[9] holds the number of scores between 90 and 99 // range[10] holds the number of 100s //***************************************************************** #include <iostream> using namespace std; const int NUM_RANGES = 11; int main() { int score; //variable for user input int range[NUM_RANGES]; //range[k] holds the number of scores seen //so far between 10*k and 10*k + 9
//initialize the counters for (int k = 0; k < NUM_RANGES; k++) range[k] = 0;
//get input cout << "Enter scores --- (-1 to quit)" << endl; do { cout << "> "; cin >> score; if (score == -1) break; range[score / 10]++; //increment the counter } while (true);
//print results cout << endl << "Histogram of scores:" << endl; for (int k = 0; k < NUM_RANGES-1; k++) cout << 10*k << " to " << 10*k + 9 << " : " << range[k] << endl; cout << "100 : " << range[10] << endl; return 0; } //************************Program Output*************************** Enter scores --- (-1 to quit) > 87 > 55 > 44 > 33 > 98 > 12 > 7 > 34 > 33 > 66 > 77 > 88 > 99 > 100 > 100 > 0 > 34 > 94 > 87 > -1 Histogram of scores: 0 to 9 : 2 10 to 19 : 1 20 to 29 : 0 30 to 39 : 4 40 to 49 : 1 50 to 59 : 1 60 to 69 : 1 70 to 79 : 1 80 to 89 : 3 90 to 99 : 3 100 : 2