Write a program that outputs a histogram of grades for an assignment given to a
ID: 3545786 • Letter: W
Question
Write a program that outputs a histogram of grades for an assignment given to a class of students. The program should input each student's grade as an integer and store the grade in a vector. Grades should be entered until the user enters -1 for a grade. The program should then scan through the vector and compute the histogram. In computing the histogram, the minimum value of a grade is 0, but your program should determine the maximum value entered by the user. Output the histogram to the console.
Explanation / Answer
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
vector<int> scores;
int count[100]; // 0 to 100
int grade;
int maxScore = 0;
int i;
// read scores
do
{
cout << "Enter grade(-1 to quit): ";
cin >> grade;
if (grade >= 0)
scores.push_back(grade);
} while (grade >= 0);
for (i = 0; i < 100; i++)
count[i] = 0;
for (i = 0; i < (int)scores.size(); i++)
{
if (maxScore < scores[i])
maxScore = scores[i];
count[scores[i]]++;
}
// display the histogram
for (i = 0; i <= maxScore; i++)
{
cout << setw(2) << i << ": ";
for (int j = 0; j < count[i]; j++)
cout << "*";
cout << endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.