//Diego Martinez                         CSC5               Chapter 9, P.537, #2
/*******************************************************************************
*  CALCULATING AND SORTING TEST SCORES DYNAMICALLY
* ______________________________________________________________________________
* This program dynamically allocates an array of test scores based on user input,
* sorts the scores in ascending order using a sorting function, and calculates
* the average score using a separate function. Pointer notation is used throughout
* the program whenever possible.
* 
* Computation is based on the Formula:
*	
*	Average = (sum of all test scores) / (number of test scores)
* 
*______________________________________________________________________________
* INPUT
*		
*	number of test scores (size of dynamic array)
*	test scores entered by the user (non-negative values)
*	
* OUTPUT
*	
*	sorted list of test scores (ascending order)
*	average of all test scores
*	
*******************************************************************************/
#include <iostream>
using namespace std;

// Function prototypes
void sortScores(double* scores, int size);
double calculateAverage(double* scores, int size);

int main()
{
    double* scores;
    int size;

    // Ask user for number of test scores
    cout << "Enter number of test scores: ";
    cin >> size;

    // Dynamically allocate array
    scores = new double[size];

    // Input scores with validation
    for (int i = 0; i < size; i++)
    {
        cout << "Enter score " << (i + 1) << ": ";
        cin >> *(scores + i);

        // Input validation: no negative numbers
        while (*(scores + i) < 0)
        {
            cout << "Invalid input. Enter a non-negative score: ";
            cin >> *(scores + i);
        }
    }

    // Sort scores
    sortScores(scores, size);

    // Calculate average
    double average = calculateAverage(scores, size);

    // Display sorted scores
    cout << "\nSorted Test Scores:" << endl;
    for (int i = 0; i < size; i++)
    {
        cout << *(scores + i) << " ";
    }

    // Display average
    cout << "\n\nAverage Score: " << average << endl;

    // Free memory
    delete[] scores;

    return 0;
}

// Function to sort scores (ascending order using bubble sort)
void sortScores(double* scores, int size)
{
    double temp;

    for (int i = 0; i < size - 1; i++)
    {
        for (int j = 0; j < size - i - 1; j++)
        {
            if (*(scores + j) > *(scores + j + 1))
            {
                temp = *(scores + j);
                *(scores + j) = *(scores + j + 1);
                *(scores + j + 1) = temp;
            }
        }
    }
}

// Function to calculate average
double calculateAverage(double* scores, int size)
{
    double sum = 0;

    for (int i = 0; i < size; i++)
    {
        sum += *(scores + i);
    }

    return sum / size;
}