226k views
5 votes
Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible.

1 Answer

1 vote

Answer:

// Program written in C++

// Comments are used to explain some lines

#include <iostream>

#include <iomanip>

using namespace std;

// Functions

void getData(double *, int);

void selectionSort(double *, int);

double getAverage(double *, int);

void displayData(double *, int, double);

int main() //Main Method

{

double *ToTest, // To dynamically allocate an array

Average; // To hold the average of the scores

int Scores; // To hold number of scores

// Get number of scores

cout << "Number of average to find? ";

cin >> Scores;

// Allocate an array to number of scores

ToTest = new double[Scores];

getData(ToTest, Scores);

selectionSort(ToTest, Scores);

Average = getAverage(ToTest, Scores);

printData(ToTest, Scores, Average);

return 0;

}

//Get Data

void getData(double *ToTest, int Scores)

{

cout << "Enter each scores.\\";

for (int i = 0; i < Scores; i++)

{

do

{

cout << "Score #" << (i + 1) << ": ";

cin >> *(ToTest + i);

if (*(ToTest + i) < 0)

{

cout << "Scores must be greater than 0.\\"

<< "Re-enter ";

}

} while (*(Test + i) < 0);

}

}

// Selection Sort

void selectionSort(double *ToTest, int Scores)

{

int startscan, minIndex;

double minValue;

for (startscan = 0; startscan < (Scores - 1); startscan++)

{

minIndex = startscan;

minValue = *(ToTest + startscan);

for (int i = startscan + 1; i < Scores; i++)

{

if (*(ToTest + i) < minValue)

{

minValue = *(Test + i);

minIndex = i;

}

}

*(ToTest + minIndex) = *(ToTest + startscan);

*(ToTest + startscan) = minValue;

}

}

// Calculate Average

double getAverage(double *ToTest, int Scores)

{

double Total;

for (int i = 0; i < Scores; i++)

{

Total += *(ToTest + i);

}

return Total / Scores;

}

// Print Data

void printData(double *ToTest, int Scores, double Avg)

{

cout << "\\ Test scores\\";

cout << "Number of scores: " << Scores << endl;

cout << "Scores in ascending-order:\\";

for (int i = 0; i < Scores; i++)

{

cout << "#" << (i + 1) << ": " << *(ToTest + i) << endl;

}

cout << fixed << showpoint << setprecision(2);

cout << "Average score: " << Avg << endl;

}

User Robert Ilbrink
by
5.2k points