M10 Pointers

mail@pastecode.io avatar
unknown
c_cpp
7 months ago
2.4 kB
3
Indexable
Never
//
//  main.cpp
//  M10Pointers_Xu
//
//  Created by Ashley Xu on 12/10/23.
//

#include <iostream>
#include <algorithm>
using namespace std;

// Function prototypes
void getTestScores(double *scores, int numScores);
void sortScores(double *scores, int numScores);
double calculateAverage(const double *scores, int numScores);
void displayResults(const double *scores, int numScores, double average);

int main() {
    // get number of test scores from user
    int numScores;  
    cout << "Enter the number of test scores: ";
    cin >> numScores;

    // validate input for a positive number of test scores
    while (numScores <= 0) {
        cout << "Please enter a positive number of test scores: ";
        cin >> numScores;
    }

    // dynamically allocate array to hold the test scores
    double *testScores = new double[numScores];

    // get test scores from user
    getTestScores(testScores, numScores);

    // sort test scores in ascending order
    sortScores(testScores, numScores);

    // calculate the average of the test scores
    double average = calculateAverage(testScores, numScores);

    // display sorted list of scores and the average
    displayResults(testScores, numScores, average);

    // deallocate the dynamically allocated memory
    delete[] testScores;

    return 0;
}

void getTestScores(double *scores, int numScores) {
    // get test scores from user
    for (int i = 0; i < numScores; ++i) {
        cout << "Enter test score #" << (i + 1) << ": ";
            cin >> scores[i];
            // validate input for non-negative test scores
            if (scores[i] < 0) {
                cout << "Please enter a non-negative test score.\n";
            }
    }
}
void sortScores(double *scores, int numScores) {
    // Use sort to sort scores in ascending order
    sort(scores, scores + numScores);
}

double calculateAverage(const double *scores, int numScores) {
    // calculate the average of the test scores
    double sum = 0.0;
    for (int i = 0; i < numScores; ++i) {
        sum += scores[i];
    }
    return (numScores > 0) ? (sum / numScores) : 0.0;
}

void displayResults(const double *scores, int numScores, double average) {
    // display the sorted list of scores and the average
    cout << "\nSorted List of Test Scores: " << endl;
    for (int i = 0; i < numScores; ++i) {
        cout << *(scores + i) << endl;
    }
    cout << "\nAverage Test Score: " << average << endl;
}
Leave a Comment