In: Computer Science
In C++
Write a program that dynamically allocates a built-in array large enough to hold a user-defined number of test scores. (Ask the user how many grades will be entered and use a dynamic array to store the numbers.) Once all the scores are entered, the array should be passed to a function that calculates the average score. The program should display the scores and average. Use pointer notation rather than array notation whenever possible. (Input Validation: Do not accept negative numbers for test scores.) Make it a class, call it something like gradeholder. You will need a destructor because you are using dynamic arrays.
I need your help. Thank you
#include <iostream>
using namespace std;
// function to calculate average of the scores
double calAverage(double *ptr, int size) {
// initialize sum to 0
double sum = 0.0;
// calculate sum
for(int i = 0; i < size; i++) {
sum += *(ptr + i);
}
// return the average
return sum/size;
}
// main function
int main() {
// declare variable
int n;
// read the number of scores in array
cout << "Number of test scores: ";
cin >> n;
// dynamically allocate the array to store scores
double *scores = new double[n];
for(int i = 0; i < n; i++){
// read scores
cout << "Enter score " << i + 1 << ": ";
cin >> *(scores + i);
// validating user input
while (*(scores + i) < 0){
cout << "Test score can not be negative."<<endl;
cout << "Please re-enter: "<<endl;
cin >> *(scores + i);
}
}
// display scores
cout << "\n\nTest Scores: ";
for(int i = 0; i < n; i++){
cout << *(scores + i) << " ";
}
// call function to calculate average
cout << "\nAverage: ";
cout << calAverage(scores, n); // function call to calculate average
// delete the array free its memory
delete[] scores;
return 0;
}