//Amari Mosley CSC5 Chapter 9, P. 537 #2
/********************************************************************
*
* ALLOCATE TEST SCORES
* _________________________________________________________________
*
* This program dynamically allocates an array to hold a user-defined
* number of test scores. It accepts the scores, and displays the sorted
* scores and average.
*
* _________________________________________________________________
*
* INPUT
* numScores : Number of test scores to enter
* scores : Test scores entered by the user
* OUTPUT
* sortedScores : Test scores sorted in ascending order
* average : Average of all test scores
*
********************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function Prototypes
void sortScores(double*, int);
double calculateAverage(double*, int);
int main()
{
// INPUT
int numScores;
// Get the number of test scores
cout << "How many test scores would you like to enter? ";
cin >> numScores;
// Input Validation
while (numScores <= 0)
{
cout << "Please enter a number greater than 0: ";
cin >> numScores;
}
// Dynamically allocate the array
double* scores = new double[numScores];
// Get test scores from the user
for (int count = 0; count < numScores; count++)
{
cout << "Enter test score #" << (count + 1) << ": ";
cin >> *(scores + count);
// Input Validation
while (*(scores + count) < 0)
{
cout << "Negative scores are not accepted. Enter again: ";
cin >> *(scores + count);
}
}
// Sort the test scores
sortScores(scores, numScores);
// Calculate the average
double average = calculateAverage(scores, numScores);
// Output Sorted Test Scores
cout << endl << "Sorted Test Scores" << endl;
cout << "________________________" << endl;
for (int count = 0; count < numScores; count++)
{
cout << fixed << setprecision(2);
cout << *(scores + count) << endl;
}
// Output Average
cout << endl << "Average Test Score: ";
cout << fixed << setprecision(2) << average << endl;
// Free dynamically allocated memory
delete[] scores;
return 0;
}
// Function to sort scores in ascending order
void sortScores(double* scores, int numScores)
{
double temp;
for (int count = 0; count < numScores - 1; count++)
{
for (int index = count + 1; index < numScores; index++)
{
if (*(scores + count) > *(scores + index))
{
temp = *(scores + count);
*(scores + count) = *(scores + index);
*(scores + index) = temp;
}
}
}
}
// Function to calculate the average test score
double calculateAverage(double* scores, int numScores)
{
double total = 0;
for (int count = 0; count < numScores; count++)
{
total += *(scores + count);
}
return total / numScores;
}