C++ question help! Please note the program should ask number of grades first, th
ID: 662440 • Letter: C
Question
C++ question help!
Please note the program should ask number of grades first, then grades, and output should be using * to represent numbers (if there are two 20, then output should be 20 **)
Write a program that outputs a histogram of student grades for an assignment. First, the program will input the number of grades and create a dynamic array to store the grades. Then, the program should input each student's grade as an integer and store the grade in the dynamic array.
The program should then scan through the array 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. Use a dynamic array to store the histogram. Output the histogram to the console.
For example, if the input is:
Then the output histogram should be:
You must delete all memory allocated to dynamic arrays before the program ends.
Explanation / Answer
// Also tried in online compiler http://www.tutorialspoint.com/compile_cpp_online.php by giving input
//number of grades:6, grades: 1,2,3,1,1,2
//output: 1: * * *, 2: * *, 3: *;
// code
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
void hist(int arr[], int n)
{
// Pick all elements one by one
for (int i=0; i<n; i++)
{
// Check if the picked element is already printed
int j;
for (j=0; j<i; j++)
if (arr[i] == arr[j])
break;
// If not printed earlier, then print it
if (i == j)
{
int xx = std::count (arr, arr+n, arr[i]);
std::cout<<arr[i]<<": ";
for(int j=0;j<xx;++j)
{
std::cout <<"* ";
}
std::cout<<" ";
}
}
}
int main() {
int* arr = NULL; // Pointer to int, initialize to nothing.
int m; // Size needed for array
std::cout<<"Enter number of grades:";
std::cin >> m; // Read in the size
std::cout<<"Enter grades (each on a new line):";
arr = new int[m]; // Allocate n ints and save ptr in a.
for (int i=0; i<m; i++) {
std::cin>>arr[i]; // Initialize all elements to zero.
}
hist(arr, m);
return 0;
delete [] arr; // When done, free memory pointed to by arr.
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.