In: Computer Science
Create a c++ program that:
(90 to 100 is an A, 80 to 89 is a B, 70 to 79 is a C, 60 to 69 is a D, 0 to 60 is a F)
Code:
#include <fstream>
#include<iostream>
#include <vector>
using namespace std;
void printHistogram(char ch, int num) {
printf("[%c]",ch);
for (int j = 0; j < num; ++j) {
printf("*");
}
printf("\n");
}
int main() {
vector<int>v;
ifstream is("a.txt");
int x;
if ( is.peek() == ifstream::traits_type::eof() )
{
// Empty File
}else{
while (is >> x){
//read integer from file
v.push_back(x);
}
int sum=0;
vector<int>v2;
int inv, val, A,B,C,D,F;
for(int i=0; i<v.size(); i++){
if(v[i]<0 || v[i]>100){
inv++;
}else{
v2.push_back(v[i]);
val++;
sum+=v[i];
if(v[i]<60){
F++;
}else if(v[i]>=60 && v[i]<70){
D++;
}else if(v[i]>=70 && v[i]<80){
C++;
}else if(v[i]>=80 && v[i]<90){
B++;
}else if(v[i]>=90 && v[i]<=100){
A++;
}
}
}
sort(v2.begin(), v2.end());
if(val==0){
cout<<"Invalid scores: "<<inv<<endl;
cout<<"No valid scores"<<endl;
}else{
float avg = sum/v2.size();
cout<<"Valid scores: "<<val<<endl;
cout<<"Inalid scores: "<<inv<<endl;
cout<<"Highest valid score: "<<v2[v2.size()-1]<<endl;
cout<<"Lowest valid score: "<<v2[0]<<endl;
cout<<"Average valid score: ";
printf("%.2f\n",avg);
printHistogram('A',A);
printHistogram('B',B);
printHistogram('C',C);
printHistogram('D',D);
printHistogram('F',F);
}
}
is.close();
return 0;
}
Output: