# Array Question

• 07-25-2010
ieatcalculus
Array Question
(For easier understanding, I simplified this problem*:)

In short, I'm trying to write a program that has a function, getAverage(), which should calculate and return the average of the values stored in the array testscores[].

I'm uncertain as to what to set as the 'for loop' conditions; I'd appreciate any help.

Code:

```#include <iostream> using namespace std; double getAverage(int testscores[]); int main () {     int testscores[] = {100, 90, 95};         cout << getAverage(testscores);         system ("pause");     return 0; } double getAverage(int testscores[]) {     int sum = 0;         int i;     for (i = 0; ; i++) // what would I put in between the semicolons?     {         sum += testscores[i];     }         int average;     average = sum/i;     return average; }```
• 07-25-2010
laserlight
Pass the number of elements as another argument to the getAverage function, then you can use i < num_elements as the loop condition.
• 07-25-2010
ieatcalculus
what? like this?: (It doesn't work?)

Code:

```#include <iostream> using namespace std; double getAverage(int testscores[], int num_elements); int main () {     int num_elements;     int testscores[num_elements] = {100, 90, 95};         cout << getAverage(testscores);         system ("pause");     return 0; } double getAverage(int testscores[], int num_elements) {     int sum = 0;         int i;     for (i = 0; i < num_elements ; i++)     {         sum += testscores[i];     }         int average;     average = sum/i;         cout << "sum" << sum << "average" << average;     return average; }```
• 07-25-2010
laserlight
You forgot to change the place where the function is called.
• 07-25-2010
ieatcalculus
Right. Regardless, it still won't work. The error message says "variable-sized object 'testscores' may not be initialized"
• 07-25-2010
laserlight
Oh, I missed that. Your main function should actually be:
Code:

```int main() {     int testscores[] = {100, 90, 95};         cout << getAverage(testscores, sizeof(testscores) / sizeof(testscores[0]));         system ("pause");     return 0; }```
• 07-25-2010
ieatcalculus
Oh gosh, there was actually a predefined function all along..? (Fixed!)

Thank you again, laserlight! You've been more than helpful ;)
• 07-25-2010
laserlight
Quote:

Originally Posted by ieatcalculus
there was actually a predefined function all along..?

If you are talking about sizeof, then no, it is an operator, not a function. Take care when using it: a common mistake is to attempt to use it on a pointer to the first element of an array, in order to try and find out the size in bytes of the array, only to end up with the size in bytes of the pointer instead.

You may want to use a std::vector or std::tr1::array container instead.