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.
#include <iostream>
usingnamespace std;
//Number of inspections
constint 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;
}
#include <iostream>
int main()
{
constint MAX_INSPECTIONS = 25; // maximum number of inspections
constint SENTINEL = -1 ; // sentinel to indicate end of input
int num_scores_entered = 0 ; // actual number of scores entered
longlong 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
{
constdouble average = double(sum) / num_scores_entered ; // avoid integer division
std::cout << "The average of all inspection scores is: " << average << '\n' ;
}
}