Using C++, Write a program segment that dynamically allocates an array large eno
ID: 3788981 • Letter: U
Question
Using C++,
Write a program segment that dynamically allocates an array large enough to hold a user defined number of (double) test scores. Once all the scores are entered, the array should be passed to a function that calculates and returns the average score. Use Pointer notation whenever possible.
double calculateAverage(function parameter goes here) //
int main()
{ int size;
double * ptrScores;
// complete rest of the main function following the directions above
}
double calculateAverage(function parameter goes here)
{
// complete the rest of this function following the directions above
}
Explanation / Answer
Program:
#include <iostream>
#include <iomanip>
using namespace std;
double calcAverage(double, int);
void bubbleSort(double scores[], int numScores);
int main()
{
double *scores, // To dynamically allocate an array
total = 0.0, // Accumulator
average; // To hold average scores
int numScores, // To hold the number of days of scores
count; // Counter variable
// Get the number of days of scores.
cout << "How many days of test scores do you wish ";
cout << "to process? ";
cin >> numScores;
// Dynamically allocate an array large enough to hold
// that many days of scores amounts.
scores = new double[numScores];
// Get the scores figures for each day.
cout << "Enter the test scores below. ";
for (count = 0; count < numScores; count++)
{
cout << "Day " << (count + 1) << ": ";
cin >> scores[count];
}
// Calculate the total scores
for (count = 0; count < numScores; count++)
{
total += scores[count];
}
bubbleSort(scores,numScores);
average = calcAverage(total, numScores);
cout << endl;
for (count = 0; count < numScores; count++)
{
cout<<"Day "<<(count+1)<<": "<< *(scores + count) <<endl;
}
// Display the results
cout << fixed << showpoint << setprecision(2);
cout << "Average Test Score: " << average << "%" << endl;
// Free dynamically allocated memory
delete [] scores;
scores = 0; // Make scores point to null.
return 0;
}
double calcAverage(double total, int numScores)
{
double avg;
// Calculate the average scores per day
avg = total / numScores;
return avg;
}
void bubbleSort(double array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.