//Charlotte Davies-Kiernan CS1A Chapter 9 P. 537 #2
//
/******************************************************************************
*
* Compute Test Average
* ____________________________________________________________________________
* This program will allocate an array not accepting any negative scores and
* then sorts the scores in ascending order. The program will then compute the
* average.
* ____________________________________________________________________________
* Input
* numScores :Number of tests
* scores :Scores on each of the tests
* Output
* sortScores :Function that sorts the test scores in ascending order
* averageScore :Function that computes the average of the scores entered
*****************************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
//Function Prototype
void sortScores(double* scores, int size);
double averageScore(double* scores, int size);
int main() {
//Data Dictionary
int numScores;
double* scores;
double avg;
//Prompt User
cout << "How many test scores will you enter? " << endl;
cin >> numScores;
//Input Validation
while(numScores <= 0) {
cout << "ERROR: Enter a positive number of test scores: " << endl;
cin >> numScores;
}
scores = new double[numScores];
//Input Scores with Validation
for(int i = 0; i < numScores; i++) {
cout << "Enter score #" << (i + 1) << ": " << endl;
cin >> *(scores + i);
//Validate!
while(*(scores + i) < 0) {
cout << "ERROR: Score cannot be negative. Re-enter score #" << (i + 1);
cout << ": " << endl;
cin >> *(scores + i);
}
}
//Sort Scores
sortScores(scores, numScores);
//Calculate Average
avg = averageScore(scores, numScores);
//Display!
cout << "Sorted Test Scores: " << endl;
for(int i = 0; i < numScores; i++) {
cout << *(scores + i) << " ";
}
cout << endl;
cout << "Average Score: " << fixed << setprecision(2) << avg << endl;
//Free memory
delete [] scores;
return 0;
}
//Function Definitions
void sortScores(double* scores, int size) {
for(int i = 0; i < size - 1; i++){
for(int j = i + 1; j < size; j++){
if(*(scores + j) < *(scores + i)){
double temp = *(scores + i);
*(scores + i) = *(scores + j);
*(scores + j) = temp;
}
}
}
}
double averageScore(double* scores, int size){
double total = 0.0;
for(int i = 0; i < size; i++){
total += *(scores + i);
}
return total/size;
}