In: Computer Science
In C++
1. Test Scores #1
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.
Solution
Code
#include <iostream>
#include <iomanip>
using namespace std;
double calculateAverageScore(double *, int);
int main()
{
int numGrades;
//userinput
cout << "Enter number of test scores: ";
cin >> numGrades;
//dynamic allocation
double *testScores = new double[numGrades];
for(int i = 0; i < numGrades; i++){
cout << "Score " << i + 1 << ": ";
cin >> *(testScores + i);
//checking user input for negative number
while(*(testScores + i) < 0){
cout << "You entered negative number"<<endl;
cout << "Please enter the number again"<<endl;
cin >> *(testScores + i);
}
}
cout << fixed << setprecision(1);
cout << endl;
cout << "TestScores: \n";
for(int i = 0; i < numGrades; i++){
cout << *(testScores + i) << " ";
}
cout << "\n\nAverage of " << numGrades << " tests
is: ";
cout << calculateAverageScore(testScores, numGrades);
delete[] testScores;
testScores=0;
return 0;
}
double calculateAverageScore(double *ptr, int size){
double sum = 0.0;
for(int i = 0; i < size; i++){
sum += *(ptr + i);
}
return (double)sum/size;
}
Screenshot
OUtput
---
all the best