219k views
0 votes
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 Demonstrate the class in a main program. All methods should be implemented and called.

User Tgikal
by
5.5k points

1 Answer

1 vote

Answer:

See explaination for the code

Step-by-step explanation:

Here is the code

class NumberArray

{

private:

float *aptr; // Pointer to the array

int arraySize; // Holds the array size

float max,min,avg;

public:

NumberArray(int); // Constructor

~NumberArray(); // Destructor

int size() const // Returns the array size

{ return arraySize; }

void storeNumber(float num,int ele);

float retrieveNumber(int ele);

float getHighest();

float getLowest();

float getAverage();

};

//*******************************************************

// Constructor for IntArray class. Sets the size of the *

// array and allocates memory for it. *

//*******************************************************

NumberArray::NumberArray(int s)

{

arraySize = s;

aptr = new float [s];

for (int count = 0; count < arraySize; count++)

*(aptr + count) = 0;

}

//******************************************************

// Destructor for IntArray class. *

//******************************************************

NumberArray::~NumberArray()

{

if (arraySize > 0)

delete [] aptr;

}

void NumberArray::storeNumber(float num,int ele)

{

if(ele<arraySize)

*(aptr+ele)=num;

}

float NumberArray::retrieveNumber(int ele)

{

return *(aptr+ele);

}

float NumberArray::getHighest()

{

float high=*(aptr+0);

for(int i=1;i<arraySize;i++)

if(high<*(aptr+i))

high=*(aptr+i);

return high;

}

float NumberArray::getLowest()

{

float low=*(aptr+0);

for(int i=1;i<arraySize;i++)

if(low>*(aptr+i))

low=*(aptr+i);

return low;

}

float NumberArray:: getAverage()

{

float ag=0;

for(int i=1;i<arraySize;i++)

ag+=*(aptr+i);

ag=ag/arraySize;

return ag;

}

//Header file section

#include <iostream>

using namespace std;

int main()

{

const int SIZE = 10; // Array size

// Define an IntArray with 10 elements.

NumberArray table(SIZE);

//function call to store values

table.storeNumber(1,0);

table.storeNumber(3,1);

table.storeNumber(7,2);

table.storeNumber(2,3);

//display values

cout<<"Highest value:"<<table.getHighest()<<endl;

cout<<"Lowest Value:"<<table.getLowest()<<endl;

cout<<"Average:"<<table.getAverage()<<endl;

///pause system for a while

system("pause");

return 0;

}

User Leif Andersen
by
4.9k points