16.3 Homework 2a : Text-based histogram (c++) Arrays are one of the fundamental
ID: 3880674 • Letter: 1
Question
16.3 Homework 2a : Text-based histogram (c++)
Arrays are one of the fundamental data structures in computer science. This homework is designed to get you working with 1 and 2 dimensional arrays in C++. There are 2 problems in this homework.
Related C++ HackerRank Problems
Introduction -> For Loop
Introduction -> Arrays Introduction
Introduction -> Variable Sized Arrays
Problem 2a : Text-based Histogram
Write a program to generate a text-based histogram for a quiz given to a class of students. The quiz is graded on a scale from 0-10. Write a program that allows the user to enter grades for each student. As the grades are being entered, the program should count, using an array, the number of grades of each value. The user indicates the end of the input by a negative number. The program should be capable of handling an arbitrary number of student grades.
When printed, the histogram should show the grade value, followed by X's for the number of grades for each score, followed by the actual number in parentheses.
Sample program run
Explanation / Answer
Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.
//histogram.cpp
#include<iostream>
using namespace std;
int main(){
int g=0;
/**
initializing an array capable of storing 11 elements */
int grades[11];
/**
filling the array with zeroes, the idea is that the possible
range of grades is between 0 and 10, so we are storing
the count of each elements in its corresponding index.
i.e count of 5 will be in grades[5], count of 10 will be in
grades[10] */
for(int i=0;i<11;i++){
grades[i]=0;
}
/**
a variable used to store the largest grade entered */
int largestGrade=0;
cout<<" Enter each grade and a negative number to stop:"<<endl;
while(!(g<0)){
/**
loops until a negative number is entered */
cin>>g;
if(g>=0 && g<=10){
/**
if it is a valid grade between 0 and 10, incrementing the
count at particular index. i.e. if the input grade is 2,
grades[2] will be incremented */
grades[g]++;
if(g>largestGrade){
/**
if it is larger than the assumed number, making it as the largest */
largestGrade=g;
}
}
}
/**
printing the histogram of all grades entered, from 0 to the
largest grade entered */
cout<<"Histogram of grades:"<<endl;
for(int i=0;i<=largestGrade;i++){
printf("%d:",i);
/**
printing X for the value equivalent to the count */
for(int j=0;j<grades[i];j++){
printf("X");
}
/**
Displaying the count */
printf(" (%d) ",grades[i]);
}
return 0;
}
/*OUTPUT*/
Enter each grade and a negative number to stop:
0
0
0
0
1
1
3
3
3
2
2
4
5
5
5
5
5
5
-1
Histogram of grades:
0: XXXX (4)
1: XX (2)
2: XX (2)
3: XXX (3)
4: X (1)
5: XXXXXX (6)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.