Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++, thank you! Design a class that has an array of floating-point numbers. The

ID: 654692 • Letter: C

Question

C++, thank you!

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 program.

Explanation / Answer

#include <iostream>
using namespace std;
class array
{
private:
   double *ptr;
   int size;
public:
   array(int i)
       {ptr=new double[i];
       size=i;
       }
   ~array()
   {delete ptr;
   }
   void setnum(int i, double n)
       { *(ptr+i)=n;
        }
   double getnum(int i)
       {return *(ptr+i);
       }
   double average()
       {double sum=0;
       int i;
       for(i=0;i<size;i++)
          sum+=*(ptr+i);
       return sum/size;
       }
    double largest()
       {double l;
       int i;
       l=*ptr;
       for(i=1;i<size;i++)
          if(*(ptr+i)>l)
               l=*(ptr+i);
       return l;
       }
    double smallest()
       {double l;
       int i;
       l=*ptr;
       for(i=1;i<size;i++)
          if(*(ptr+i)<l)
               l=*(ptr+i);
       return l;
      }      
};

int main()
{ int size,i;
   double num;  
   cout<<"How many numbers do you have? ";
   cin>>size;
   array numbers(size);
   cout<<"Enter the numbers: ";
   for(i=0;i<size;i++)
     {cout<<"Enter number"<<i+1<<": ";
      cin>>num;
      numbers.setnum(i,num);
     }
   cout<<"The array: ";
   for(i=0;i<size;i++)
     cout<<numbers.getnum(i)<<" ";
   cout<<endl;
   cout<<"The largest number is:"<<numbers.largest()<<endl;
   cout<<"The smallest number is:"<<numbers.smallest()<<endl;
   cout<<"The average is:"<<numbers.average()<<endl;
   system("pause");
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote