1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
#include <iostream>
#include <iomanip>
using namespace std;
//Function prototypes
void sortTestScores(int *TestScores, int size_Test);
double avgTestScore(int *TestScores, int size_Test);
void printTestScores(int *TestScores, int size_Test);
int main()
{
//Define variables
int *TestScores;
int size_Test, score;
double average;
//Get the number of test scores you want to average
cout << "How many test scores do you want to enter?";
cin >> size_Test;
//Dynamically allocate an array large enough to hold that many scores
TestScores = new int[size_Test];
//Get test scores
cout << "Enter " << size_Test << " positive test scores below:" << endl;
for (int i=0; i<size_Test; i++)
{
//Display score
cout << "Score " << i + 1 << ": ";
cin >> score;
// Input validation. Only numbers between 0-100
while (score<0 || score>100)
{
cout << "You must enter a score that is positive" << endl;
cout << "Please enter again: ";
cin >> score;
}
TestScores[i]=score;
}
//Dsiplay the results
cout << "Test Scores: ";
printTestScores(TestScores, size_Test);
sortTestScores(TestScores, size_Test);
cout << "The test scores, sorted in ascending order, are: \n";
printTestScores(TestScores, size_Test);
average = avgTestScore(TestScores, size_Test);
cout << fixed << showpoint << setprecision(2);
cout << "The average of all the test scores is " << average << endl;
system ("pause");
return 0;
}
//Accepts a dynamic array of test scores and size of array, then sorts in ascending order
//Sort function implementation
void sortTestScores(int *TestScores, int size_Test)
{
int *last=TestScores+size_Test; //get last location of array
for (int *first = TestScores; first < last-1; first++)
{
for(int *next=first+1; next<last; next++)
{
if (*next<*first)
{
int temp=*first;
*first=*next;
*next=temp;
}
}
}
}
//calculates and returns average of test scores
double avgTestScores(int *TestScores, int size_Test)
{
int total = 0;
double average;
int *arranged=TestScores;
for (int i=0; i < size_Test; i++)
{
total+= *arranged;
arranged++;
}
average= double(total) / size_Test;
return average;
}
//Prints test scores stored in array
void printTestScores(int *TestScores, int size_Test)
{
int *arranged=TestScores;
for (int i=0; i < size_Test; i++)
{
cout << *arranged << " " << arranged << endl;
arranged++;
}
}
|