14 Replies - 1726 Views - Last Post: 07 February 2010 - 02:51 AM Rate Topic: -----

#1 Jin_minx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 29-January 10

Array Class

Posted 03 February 2010 - 01:32 AM

I have a program that requires me to design a class that has an array of floating-point numbers. The constructor has to 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 it should store a number in any element of the array, retrieve a number from any element of the array, return the highest, lowest and average of all the numbers in the array.

I am not sure of the syntax to retrieve a number from any element of the class array. It would also be great if you tell me where I could make the code more efficient according to the specifications. I would really appreciate the help. Thanks. The code is below. I've changed the data type of the class array to "double" to hold the floating point numbers but it is still just taking integers. Thanks in advance for your help.

//Header file

#ifndef NumberList_H        // include guard to keep from being run twice
#define NumberList_H        // defines class

class NumberList
{
   private:
       int *list; //Pointer to the array
       int numElements; //Number of elements
       
       
   public:
	   bool isValid(int); //Validates subscript 
       NumberList(int);  //Constructor
       ~NumberList();//Destructor
        void setElement(int, int);
        int getElement(int); //Returns an element
        
        
        // Mutators used to alter variables
        void setHighest(double);        // set the highest value
        void setLowest(double);        // set the lowest value
        void setAverage(double);        // set the average value

       // Accessors used to get the variables
        double getHighest() const;
        double getLowest() const;
        double getAverage() const;

};
#endif        // closes guard
       
              




//Implementation code

#include <iostream>
#include <cstdlib>
#include "numberList.h"

using namespace std;

//The constructor accepts integer argument and dynamically allocate the array
//to hold that many numbers

// The default constructor
NumberList::NumberList(int size)
{
    list = new int[size];        // points to a dynamically allocated array of integers
    numElements = size;                // number of elements in the array
    for(int index=0; index<size; index++)
      list[index]=0;
    
}

//The destructor releases allocated memory

NumberList::~NumberList()
{
  delete []list;
}

//isValid member function

bool NumberList::isValid(int element) 
{
     bool status;
     
     if(element < 0 || element >= numElements)
        status=false;
     else
       status = true;
     return status;
}    

//setElement member function

void NumberList::setElement(int element, int value) 
{
   if (isValid(element))
       list[element]=value;
   else
   {
       cout<<"Error: Invalid subscript\n";
       exit(EXIT_FAILURE);
   } 
}

//getElement member function

int NumberList::getElement(int element) 
{
    if(isValid(element))
       return list[element];
    else
    {
        cout<<"Error: Invalid subscript\n";
        exit(EXIT_FAILURE);
   } 
}

//getHighest
double NumberList::getHighest() const
{
    int count;      // local to count in loop
    double highest;  // to hold highest

    // set the first array element to highest
    highest = list[0];

    // step through array size to compare
    for (count =1; count < numElements; count++)
    {
        if (list[count] > highest)
        {
            // stores the highest number
            highest = list[count];
        }
    }
    return  highest;
}  


// getLowest
double NumberList::getLowest() const
{
    int count;      // local to count in loop
    double lowest;  // to hold lowest

    // set the first array element to lowest
    lowest = list[0];

    // step through array size to compare
    for (count = 1; count < numElements; count++)
    {
        if (list[count] < lowest)
        {
            // stores the lowest number
            lowest = list[count];
        }
    }
    return  lowest;
}
                                         
// only return value
double NumberList::getAverage() const
{
    double total = 0.0;    // accumulator for function
    int count;            // local to count in loop
    double average=0.0;        // to hold average

    // step through array size to add up numbers
    for (count = 1; count < numElements; count++)
    {
        total =+ list[count];
    }
    average = (total/count);
    return average;
    
}



//Function Main
#include <iostream>
#include <iomanip>
#include "numberList.h"        

using namespace std;

// Main to run program
int main()
{
   const int SIZE=3;
   NumberList numbers(SIZE);
   int val, x;

   
   numbers.setElement(2,14);
   
   
   
 for(x=0; x<SIZE;x++)
 {

    numbers.setElement(0,9);//store a number in any element of the array
    cout<<" "<<numbers.getElement(x)<<endl;
	
 }

 

   

 // Display the Array's data.
    cout << "\t Array Information \n";
    cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";    
    cout << "\t Highest : " << numbers.getHighest() << endl;
    cout << "\t Lowest: " << numbers.getLowest() << endl;
    cout << "\t Average: " << numbers.getAverage() << endl;
    cout << endl;
    cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
    cout << endl;
    
 cin.get();
}


This post has been edited by Jin_minx: 03 February 2010 - 03:19 AM


Is This A Good Question/Topic? 1
  • +

Replies To: Array Class

#2 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 109
  • View blog
  • Posts: 1,530
  • Joined: 25-January 07

Re: Array Class

Posted 03 February 2010 - 01:44 AM

In your function getAverage() you have a loop
for (count = 1; count < numElements; count++)
    {
        total =+ list[count];
    }



You are iterating array from 1 to (numElements-1) so you miss your first element from array.
start count from 0 to (numElements-1) and see if that helps.
Was This Post Helpful? 1
  • +
  • -

#3 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,455
  • Joined: 16-May 09

Re: Array Class

Posted 03 February 2010 - 07:28 AM

First of all, you can change isValid function like this:
bool NumberList::isValid(int element) {
     if(element < 0 || element >= numElements)
        return false;
     else
       return true;
}

Your previous definition was not wrong at all, but this one is a little shorter.

From what I understood from your post, you want to hold float numbers. If you want to achieve this, you have to create an array of floats, so change the constructor to something like:
NumberList::NumberList(int size) {
    list = new float[size];        // points to a dynamically allocated array of integers
    numElements = size;                // number of elements in the array
    for(int index=0; index<size; index++)
      list[index]=0;
}

Now the constructor creates an array of floats. Also, you need to change other functions to work with floats:
void NumberList::setElement(int element, float value) {
   if (isValid(element))
       list[element]=value;
   else
   {
       cout<<"Error: Invalid subscript\n";
       //exit(EXIT_FAILURE); if called, causes memory leak
   } 
}

and...
float NumberList::getElement(int element) {
    if(isValid(element))
       return list[element];
    else
    {
        cout<<"Error: Invalid subscript\n";
        //exit(EXIT_FAILURE); if called, causes memory leak
   } 
}


Change other functions to work with your desired type as well.

Edit: Pay attention, if the element is not valid and exit is called, then the destructor of your class is not called, which causes a memory leak as your dynamic array is not deleted.

This post has been edited by Anarion: 03 February 2010 - 07:48 AM

Was This Post Helpful? 1
  • +
  • -

#4 Munawwar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 161
  • View blog
  • Posts: 457
  • Joined: 20-January 10

Re: Array Class

Posted 03 February 2010 - 08:06 AM

Yes, in additon to that change 'int* list;' in the NumberList class to 'float* list;'.
Was This Post Helpful? 0
  • +
  • -

#5 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2209
  • View blog
  • Posts: 9,183
  • Joined: 18-February 07

Re: Array Class

Posted 03 February 2010 - 09:07 AM

@Anarion -- I thought we already went over this:

I submit to the jury that you are guilty of silly redundant programming:

One should never use the following construction:
if (condition) { return true; } else { return false; }


or this *similar* construction (of which you are guilty above):
if (condition) { return false; } else { return true; }


The 'condition' is a Boolean expression and already evaluates to either true or false. So the first version of the construction above reduces down to:
return condition;

and the second to:
return !condition;


So your sample above:

View PostAnarion said:

bool NumberList::isValid(int element) {
     if(element < 0 || element >= numElements)
        return false;
     else
       return true;
}


is silly, and could have been reduced to:
bool NumberList::isValid(int element) {
     return (element >= 0 && element < numElements);
}


note the lack of the silly if-statement converting from a Boolean expression to a Boolean.

I submit then that you good sir, are guilty of being silly.


(Don't worry about it though, I have done it 100's of times and the only way I stop myself from doing it is to berate myself for being silly every time I do -- I suppose that one could make the argument that it is more "clear" the other way... but really that is a silly argument too).
Was This Post Helpful? 2
  • +
  • -

#6 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,455
  • Joined: 16-May 09

Re: Array Class

Posted 03 February 2010 - 09:24 AM

That was a lame mistake I made *cries so bad*
Thanks for mentioning it NickDMax. Now I am going to burn the back of my hand, not to do such a silly and lame mistake again :ph34r: *ouch!* Now I am punished completely!!!
Was This Post Helpful? 0
  • +
  • -

#7 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,662
  • Joined: 20-September 08

Re: Array Class

Posted 03 February 2010 - 09:52 AM

Hidden in plain sight is an even greater folly ... It should be obvious that 'every creation has a creator' ... and that ... 'a great creation has A Great Creator.'

But like Nick says ... we are often so blind to see ... what is so simple and so ... 'right in front of us'.
Was This Post Helpful? 0
  • +
  • -

#8 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2209
  • View blog
  • Posts: 9,183
  • Joined: 18-February 07

Re: Array Class

Posted 03 February 2010 - 10:24 AM

View PostDavid W, on 03 February 2010 - 11:52 AM, said:

Hidden in plain sight is an even greater folly ... It should be obvious that 'every creation has a creator' ... and that ... 'a great creation has A Great Creator.'

But like Nick says ... we are often so blind to see ... what is so simple and so ... 'right in front of us'.


You know David, as I get older I find time and again that so many of my "ingenious" solutions were more complicated than they need to be. To paraphrase Richard Feynman, sometimes we just don't really understand what we know.

Knowing how to write a conditional statement may require knowing that the result of a Boolean or "logical" expression must be either true or false -- but that knowledge does not necessarily translate into understanding that if you wish to know the value of the Boolean expression you don't need the conditional statement.

As I get older I find myself time and again revisiting things that I "know" just to realize that I was missing understanding. This is especially true of C++. I have a TON of knowledge about C++ -- and yet I learned 3 new things just this morning. *technically* they were things I already knew, but I didn't put the pieces together to really *understand* what I knew.
Was This Post Helpful? 0
  • +
  • -

#9 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,662
  • Joined: 20-September 08

Re: Array Class

Posted 03 February 2010 - 11:09 AM

Thanks Nick, for your seasoned and insightful comments ...

And yes, isn't it wonderful, that even 'old dogs' like us, can learn new tricks :)

And of those, now obvious and simple things ... that before were hidden ... sadly, the most vital and profound, still tragically seems to elude many ... especially in this dumbed down and toxic highly drugged computer generation.

The tremendous design, work and construction ... of all the pieces, (both hardware and software), necessary ... to get to the stage of C++ running on a computer ... and then a compiled program running on many users computers ... well ... the obvious, is often overlooked ... that: this all did not happen by random chance.

And we then fail to apply this so simple, but very vital insight, personally ... to our Creator. Surely, it's so sad, to be 'so appreciated' ... denied of existence even.

Who, after so creating ... and so giving ... likes being ... so denied?

This post has been edited by David W: 03 February 2010 - 11:13 AM

Was This Post Helpful? 0
  • +
  • -

#10 Jin_minx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 29-January 10

Re: Array Class

Posted 03 February 2010 - 01:53 PM

View PostAmitTheInfinity, on 03 February 2010 - 12:44 AM, said:

In your function getAverage() you have a loop
for (count = 1; count < numElements; count++)
    {
        total =+ list[count];
    }



You are iterating array from 1 to (numElements-1) so you miss your first element from array.
start count from 0 to (numElements-1) and see if that helps.


When I changed the count from 1 to 0, I ended up with a negative number. I left the count to 1 and divided the total by the numElements and it gave me the correct average. I would love to know why I ended up with a negative number after changing the count to 0 though. Thanks.

This post has been edited by Jin_minx: 03 February 2010 - 02:00 PM

Was This Post Helpful? 0
  • +
  • -

#11 Jin_minx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 29-January 10

Re: Array Class

Posted 03 February 2010 - 02:07 PM

Thanks for all your help. I've made the necessary changes. I would also like the syntax for retrieving a value from any subscript in the array. For e.g, how would I retrieve the number from array[3]?

This post has been edited by Jin_minx: 03 February 2010 - 02:09 PM

Was This Post Helpful? 0
  • +
  • -

#12 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2209
  • View blog
  • Posts: 9,183
  • Joined: 18-February 07

Re: Array Class

Posted 03 February 2010 - 02:23 PM

well you already have "getElement(int)" which would work...

array.getElement(3);

but I suppose you want fancy brackets....

declare this inside you class:
float operator[](int element);


and then implement:
float NumberList::operator[](int element) { return getElement(element); }

Was This Post Helpful? 1
  • +
  • -

#13 Jin_minx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 29-January 10

Re: Array Class

Posted 03 February 2010 - 03:04 PM

Thank you
Was This Post Helpful? 0
  • +
  • -

#14 Jin_minx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 29-January 10

Re: Array Class

Posted 03 February 2010 - 03:14 PM

View PostNickDMax, on 03 February 2010 - 01:23 PM, said:

well you already have "getElement(int)" which would work...

array.getElement(3);

but I suppose you want fancy brackets....

declare this inside you class:
float operator[](int element);


and then implement:
float NumberList::operator[](int element) { return getElement(element); }


Yeah I did want the fancy brackets, thanks for all your help.
Was This Post Helpful? 0
  • +
  • -

#15 Jin_minx  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 9
  • Joined: 29-January 10

Re: Array Class

Posted 07 February 2010 - 02:51 AM

1
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1