//Amari Mosley CSC5 Chapter 9, P. 538 #4
/********************************************************************
*
* TEST SCORES #2
* _________________________________________________________________
*
* This program dynamically allocates two arrays to hold student
* names and test scores. program sorts the
* scores in ascending order while keeping each student's name
* matched with their score, then displays the sorted results.
*
* _________________________________________________________________
*
* INPUT
* numStudents : Number of students taking the test
* names : Names of the students
* scores : Integer test scores
* OUTPUT
* sortedScores : Student names and scores in ascending order
*
********************************************************************/
#include <iostream>
#include <string>
using namespace std;
// Function Prototype
void sortScores(string*, int*, int);
int main()
{
// INPUT
int numStudents;
// Get the number of students
cout << "How many students took the test? ";
cin >> numStudents;
// Input Validation
while (numStudents <= 0)
{
cout << "Please enter a number greater than 0: ";
cin >> numStudents;
}
// Dynamically allocate the arrays
string* names = new string[numStudents];
int* scores = new int[numStudents];
// Get student names and test scores
for (int count = 0; count < numStudents; count++)
{
cout << "Enter student #" << (count + 1) << "'s name: ";
cin >> *(names + count);
cout << "Enter " << *(names + count) << "'s test score: ";
cin >> *(scores + count);
// Input Validation
while (*(scores + count) < 0)
{
cout << "Negative scores are not accepted. Enter again: ";
cin >> *(scores + count);
}
}
// Sort the student names and scores
sortScores(names, scores, numStudents);
// Output Sorted Student Scores
cout << endl << "Sorted Student Test Scores" << endl;
cout << "______________________________" << endl;
cout << "Student Name\tTest Score" << endl;
for (int count = 0; count < numStudents; count++)
{
cout << *(names + count) << "\t\t";
cout << *(scores + count) << endl;
}
// Free dynamically allocated memory
delete[] names;
delete[] scores;
return 0;
}
// Function to sort student names and scores in ascending order
void sortScores(string* names, int* scores, int numStudents)
{
int tempScore;
string tempName;
for (int count = 0; count < numStudents - 1; count++)
{
for (int index = count + 1; index < numStudents; index++)
{
if (*(scores + count) > *(scores + index))
{
tempScore = *(scores + count);
*(scores + count) = *(scores + index);
*(scores + index) = tempScore;
tempName = *(names + count);
*(names + count) = *(names + index);
*(names + index) = tempName;
}
}
}
}