Please write the code in C++ Design a class that has an array of floating point
ID: 3859801 • Letter: P
Question
Please write the code in C++
Design a class that has an array of floating point numbers. The constructor should accept an integer argument and dynamically allocate the array to hold that many numbers. The destructor should free the memory held by the array. In addition, there should be member functions to perform the following operations:
* Store a number in any element of the array
* Retrieve a number from any element of the array
* Return the highest value stored in the array
* Return the lowest value stored in the array
* Return the average of all the numbers stored in the array
Please follow the instructions, Thanks!
Explanation / Answer
#include<iostream>
using namespace std;
class NumberArray{
float *arr;
int size;
public:
NumberArray();
NumberArray(int);
~NumberArray();
float getElement(int);
void setElement(int,float);
float getMax();
float getLowest();
float getAverage();
};
int main(){
int size,index;
float value;
cout<<"Enter size: ";
cin>>size;
NumberArray myArr(size);
cout<<"Number Array object created and initialized to 0.";
cout<<" Time to load array ";
for(int i=0;i<size;i++){
cout<<"Enter element "<<i<<": ";
cin>>value;
myArr.setElement(i,value);
}
cout<<" The current array is: ";
for(int i=0;i<size;i++){
cout<<myArr.getElement(i)<<" ";
}
cout<<" The highest value stored in the array is "<<myArr.getMax();
cout<<" The lowest value stored in the array is "<<myArr.getLowest();
cout<<" The average value in the array is "<<myArr.getAverage();
cout<<" Press any key to continue . . . ";
cin.get();
return 0;
}//end main
//NumberArray definitions
NumberArray::NumberArray(){
size=1;
arr=new float[size];
for(int i=0;i<size;i++){
arr[i]=0;
}
}
NumberArray::NumberArray(int sz){
if(sz>0)
size=sz;
else
size=1;
arr=new float[size];
for(int i=0;i<size;i++){
arr[i]=0;
}
}
NumberArray::~NumberArray(){
delete []arr;
}
float NumberArray::getElement(int idx){
if(idx<0||idx>=size){
cout<<" Error: Index enter was out of bound. -1 Returned. ";
return -1;
}
else
return arr[idx];
}
void NumberArray::setElement(int idx, float value){
if(idx<0||idx>=size)
cout<<" Error: Index enter was out of bound. ";
else
arr[idx]=value;
return;
}
float NumberArray::getMax(){
float max=arr[0];
for(int i=1;i<size;i++){
if(max<arr[i]){
max=arr[i];
}
}
return max;
}
float NumberArray::getLowest(){
float min=arr[0];
for(int i=1;i<size;i++){
if(min>arr[i]){
min=arr[i];
}
}
return min;
}
float NumberArray::getAverage(){
float sum=0;
for(int i=0;i<size;i++){
sum+=arr[i];
}
return sum/(float)size;
}