Help with array!

I have been able to accomplish this practice problem but I need to be able to enter -1 (meaning last input number) to calculate the average of all numbers, regardless if I enter 2 scores or 25 scores. I'm going to assume a while loop and counter but I'm not too sure how to write it within the array.

Here's what I have so far.

 ``12345678910111213141516171819202122232425262728293031323334353637`` `````` #include using namespace std; //Number of inspections const int inspections = 25; int main() { int sum = 0; int average = 0; int input; //Get inspection scores cout << "Enter up to 25 scores followed by -1 (you do not need to type 25 scores)." << endl; cout << endl; for (int i = 0; i != inspections; ++i) { cout << "Enter inspection score: " << endl; cin >> input; sum += input; } // Get average and print it average = sum / inspections; cout << endl; cout << "The average of all inspection scores is: " << average << endl; cout << endl; system("pause"); return 0; } ``````
Last edited on

This may not work exactly the way I think it will but should get you started.

 ``1234567891011`` `````` for (int i = 0; i != inspections; ++i) { cout << "Enter inspection score: " << endl; cin >> input; if (input < 0) {break;} else {sum += input;} }``````
Last edited on
I will give this a whirl and let you know! Thanks!
Well it definitely works but it's using -1 as a score as well.... so i'll type in

score 1. 9
score 2. 9
score 3. 9
score 4. -1 (to initiate average of previous scores)
output - average is 1
 ``123456789101112131415161718192021222324252627282930313233`` ``````#include int main() { const int MAX_INSPECTIONS = 25; // maximum number of inspections const int SENTINEL = -1 ; // sentinel to indicate end of input int num_scores_entered = 0 ; // actual number of scores entered long long sum = 0; // sum of all the scores // Get inspection scores std::cout << "Enter up to a maximum of " << MAX_INSPECTIONS << " scores. " << "end input with " << SENTINEL << '\n' ; int score ; while( num_scores_entered < MAX_INSPECTIONS && // max number of scores have not been reached and std::cout << "score? " && std::cin >> score && // a score was successfully read from stdin and score != SENTINEL ) // it is not the sentinel indicating end of input { sum += score ; ++num_scores_entered ; } std::cout << "\n#scores: " << num_scores_entered << '\n' << "sum: " << sum << '\n' ; // Get average and print it if( num_scores_entered != 0 ) // if at least one score was entered { const double average = double(sum) / num_scores_entered ; // avoid integer division std::cout << "The average of all inspection scores is: " << average << '\n' ; } }``````
Topic archived. No new replies allowed.