Classes and array struggles

Here is my problem:
Write a class for a one dimensional array with 100 elements.
Have a constructor set all elements randomly
Write methods for:
- Getting the average value
I am still new to classes and therefore try to keep things very simple, but I am failing to get my head around what each function in a class can do and where to put my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <time.h>

using namespace std;
class Array
{
	
private:

public:
	int sArr[100];
	
	Array ()
	{
	for (int ii=0;ii<100;ii++)
	     sArr[ii]=rand();
	}

And this is what I have so far, but I am confused as to whether I should have the randomiser in this part, and I am struggling calling the random elements in another function to check the average.
I am confused as to whether I should have the randomiser in this part

It looks to me as though you've done what was asked; you're initialising the array elements to random numbers, inside the constructors.

My personal preference, however, would not be to put the definitions of the methods inside the class definition, but to put them separately in a C++ file. So your class definition in the header would be:

1
2
3
4
5
6
7
8
9
10
class Array
{
private:

public:
	int sArr[100];
	
	Array ();
        int getAverage();
};


and the method definitions would be in Array.cpp :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "Array.h"

Array::Array ()
{
    for (int ii=0;ii<100;ii++)
    {
        sArr[ii]=rand();
    }
}

int Array::getAverage()
{
    // Write your function here
}


Some other points:

using namespace std; is best avoided, especially in header files.

Why do you have those include statements at the top of your file? You're not using anything from those header files.

It's good practice to make data members of a class like this private, not public. The whole point of writing classes is to encapsulate (i.e. hide) implementation details like this from the code that uses the class. Your interface methods should be public, and everything else should be private, unless there's a really good reason to keep them public.

Even when a code block only contains a single statement - as in your for loop - I'd recommend using braces around it. That way, if you decide later to add more lines to the loop, you don't forget to add braces and screw up the logic. So:

1
2
3
4
for (int ii=0;ii<100;ii++)
{
    sArr[ii]=rand();
}

Last edited on
Topic archived. No new replies allowed.