In: Computer Science
Write a C++ program that reads a file consisting of students’
test scores
in the range 0–200. It should then determine the number of
students
having scores in each of the following ranges: 0–24, 25–49,
50–74,
75–99, 100–124, 125–149, 150–174, and 175–200. Output the
score ranges and the number of students. (Run your program with
the
following input data: 76, 89, 150, 135, 200, 76, 12, 100, 150,
28,
178, 189, 167, 200, 175, 150, 87, 99, 129, 149, 176, 200, 87,
35, 157, 189.)
Thanks for the question, here is the code in C++
Note: Please refer the screenshot for the input file having the scores data. Also, when you run the program make sure you update the filename correctly in the below line -
char * filename ="F:\\scores.txt";
Have included comments so that you can follow the code. Let me know in case you have any questions.
============================================================================
#include<iostream>
#include<fstream>
using namespace std;
// utlility function that accepts a number and returns
// the index in the array where it should be counted
int get_index(int n){
if(n>=200)return 7;
return n/25;
}
// accepts an int array and prints the frequency in the range
void displayHistogram(int range[], int size){
for(int i=0;i<size;i++){
if(i!=size-1)
cout<<25*i<<"-"<<i*25+24<<" :
"<<range[i]<<endl;
else
cout<<25*i<<"-"<<i*25+25<<" :
"<<range[i]<<endl;
}
}
int main(){
// update the filename of the input file in the below
line.
char * filename ="F:\\scores.txt";
ifstream infile(filename);
int range[8]{0};
if(infile.is_open()){
int score;
while(infile>>score){
range[get_index(score)]+=1;
}
infile.close();
displayHistogram(range,8);
}else{
cout<<"Unable to read data
from file: "<<filename<<endl;
}
}