jeudi 27 mai 2021

How to use one-dimension array in c++ to display a survey responses by count and percentage?

The question goes like this...

"Thirty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 5 (1=poor, 2=fair, 3=neutral, 4 =good, and 5=excellent). Write a C++ program that stores 45 responses into a one-dimensional array and gives a summary of each case in terms of count and percentage"

I have already written a program and it runs, however, I think it is very long and I am having trouble finding an alternative.

#include <iostream>
using namespace std;
int main()
{
    int count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
    //  int count=0;
    int rate[45];
    for (int i = 0; i < 45; i++) {
        cout << "Please rate the school's food on 1-5 scale" << endl;
        cin >> rate[i];
    }
    for (int i = 0; i < 45; i++) {
        cout << i + 1 << "." << rate[i] << endl;
    }

    for (int i = 0; i < 45; i++) {
        if (rate[i] == 1) {
            count1 = count1 + 1;
        }
        if (rate[i] == 2) {
            count2 = count2 + 1;
        }
        if (rate[i] == 3) {
            count3 = count3 + 1;
        }
        if (rate[i] == 4) {
            count4 = count4 + 1;
        }
        if (rate[i] == 5) {
            count5 = count5 + 1;
        }
    }

    cout << "------------SUMMARY--------------" << endl;
    cout << "Students who rated:" << endl;
    cout << "The school's food deserves a 1: " << count1 << " " << (count1 * 100) / 45 << "% of the students" << endl;
    cout << "The school's food deserves a 2: " << count2 << " " << (count2 * 100) / 45 << "% of the students" << endl;
    cout << "The school's food deserves a 3: " << count3 << " " << (count3 * 100) / 45 << "% of the students" << endl;
    cout << "The school's food deserves a 4: " << count4 << " " < (count4 * 100) / 45 << "% of the students" << endl;
    cout << "The school's food deserves a 5: " << count5 << " " << (count5 * 100) / 45 << "% of the students" << endl;
    cout << "-------------END OF SUMMARY----------" << endl;

    return 0;
}

Is there an easier way to do it? I appreciate any help, Thank you.

Disclaimer: I am a beginner in c++

Aucun commentaire:

Enregistrer un commentaire