//Devin Scheu CS1A Chapter 9, P. 537, #2
//
/**************************************************************
*
* PROCESS AND ANALYZE TEST SCORES
* ____________________________________________________________
* This program determines the sorted list of test scores and
* their average based on a user-defined number of scores.
* ____________________________________________________________
* INPUT
* numScores : The number of test scores to process
* testScores : The test scores entered by the user
*
* OUTPUT
* sortedScores : The sorted list of test scores
* averageScore : The average of the test scores
*
**************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function to swap two integers using pointers
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to perform bubble sort using pointers
void bubbleSort(int* arr, int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (*(arr + j) > *(arr + j + 1)) {
swap((arr + j), (arr + j + 1));
}
}
}
}
// Function to calculate average using pointers
double calculateAverage(int* arr, int size) {
double sum = 0;
for (int i = 0; i < size; i++) {
sum += *(arr + i);
}
return sum / size;
}
int main () {
//Variable Declarations
int numScores; //INPUT - The number of test scores to process
int* testScores; //INPUT - The test scores entered by the user
double averageScore; //OUTPUT - The average of the test scores
int* sortedScores; //OUTPUT - The sorted list of test scores
//Prompt for Input
cout << "Enter the number of test scores: ";
cin >> numScores;
cout << numScores << endl;
//Allocate dynamic array
testScores = new int[numScores];
//Input Test Scores with EOF check
int validScores = 0;
for (int i = 0; i < numScores && cin >> *(testScores + i); i++) {
while (*(testScores + i) < 0) {
cout << "\nError: Please enter a non-negative score: ";
cin >> *(testScores + i);
}
cout << *(testScores + i) << endl;
validScores++;
}
//Adjust numScores to actual valid inputs if less than expected
if (validScores < numScores) {
numScores = validScores;
}
//Create copy for sorting
sortedScores = new int[numScores];
for (int i = 0; i < numScores; i++) {
*(sortedScores + i) = *(testScores + i);
}
//Sort Scores
bubbleSort(sortedScores, numScores);
//Calculate Average
averageScore = calculateAverage(testScores, numScores);
//Separator and Output Section
cout << "-------------------------------------------------------" << endl;
cout << "OUTPUT:" << endl;
//Output Result
cout << fixed << setprecision(2);
cout << left << setw(25) << "Sorted Scores:" << right;
for (int i = 0; i < numScores; i++) {
cout << *(sortedScores + i);
if (i < numScores - 1) cout << ", ";
}
cout << endl;
cout << left << setw(25) << "Average Score:" << right << setw(15) << averageScore << endl;
//Clean up memory
delete[] testScores;
delete[] sortedScores;
} //end of main()