-
C++ Help
I am struggling to write this program and would like to ask if anyone would like to help me out:
In a survey, people were asked to rate a video on meat preaparation a scale from 1 to 10. There were 40 responses (ratings from 1 to 10).
I am trying to write a program to
1) enter the 40 values (standard input),
2) using an array, store the frequency of each response, and
3) after the 40 values have been entered, display the number of each response. I am looking at an example output to look like the following:
Meat Preparation Survey Responses:
1 – 7 responses
2 – 2 responses
3 – 8 responses
4 – 1 response
5 – 0 responses
6 – 3 responses
7 – 4 responses
8 – 6 responses
9 – 5 responses
10 – 4 responses
-
Code:
#include <iostream>
using namespace std;
int main()
{
int grade[20];
int counter=0;
while(counter < 20)
{
cout << "Enter your grade\t";
cin >> grade[counter++];
}
for(int x=1; x < 11;x++)
{
int index=0;
for(int y=0; y < 20; y++)
{
if (grade[y] == x)
index++;
}
cout << x << " - " << index << " responses." << endl;
}
system("PAUSE");
}
-
[edit]grrrr, accidently double posted[/edit]
-
Here's a slighly different version that lets you choose at runtime the number of responses to enter, and validates user input.
Code:
#include <iostream>
using namespace std;
int main()
{
int *grade;
int responses;
cout<<"How many responses would you like to process? ";
cin>>responses;
cout<<endl;
grade = new int[responses];
for(int i = 0; i < responses; i++)
{
cout<<"Response "<< i <<" of "<<responses<<": ";
cin>>grade[i];
if(grade[i] < 1 || grade[i] > 10)
{
cout<<"Invalid response please input another: "<<endl;
i--;
}
else
{
cout<<endl;
system("cls");
}
}
for(i = 1; i < 11; i++)
{
int index = 0;
for(int x = 0; x < responses; x++)
{
if(grade[x] == i)
index++;
}
cout << i << " - " << index << " responses." << endl;
}
delete[] grade;
system("PAUSE");
}