In: Computer Science
In C++
Write a class named TestScores. The class constructor should accept an array of test scores as its argument. The class should have a member function that returns the average of the test scores. If any test score in the array is negative or greater than 100, the class should throw an exception. Demonstrate the class in program.
I have written the program using C++PROGRAMMING LANGUAGE.
OUTPUT :
input : 86, 11, 11, 39, 43, 56, 65, 77, 99 , 11
input : 86, -11, 11, 39, 143, 56, 65, -77, 99 , 11
CODE :
//included the required libraries
#include <iostream>
#include <exception>
using namespace std;
//exception class
class myexception: public exception
{
virtual const char* what() const throw()
{
return "Array consists of negative scores or scores which is more than 100!!!";//returning statement when exception comes to the console
}
} myex;
//class TestScores
class TestScores
{
public:
int *scores;
//Constructor
TestScores(int arr[])
{
scores = arr;//input array storing in scores pointer
}
double average();//function declaration
};
//function definition for average
double TestScores::average()
{
int average = 0;//declared average variable to zero
for (int i=0; i<10; i++)
{
//condition to check whether the score is negative or more than 100
//cout << scores[i]<<endl;
if(scores[i]>=0 && scores[i]<=100){
average+=scores[i];
}else{
average = 0;
throw myex;//throwing exception
}
}
return (average/10.0);//return average
}
//main method
int main() {
//initialized the scores integer array variable
int Scores[10] = {86, 11, 11, 39, 43, 56, 65, 77, 99 , 11};
TestScores TestScores_object(Scores);//TestScores object
//Calling average method and printing the result on the console
cout << "Average Score is : "<< TestScores_object.average();
}
Thanks..