#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

double average(int sum, int numElms)
{
	int i;
	double avg;

    avg = sum/numElms;


	return sum;
}

int main()
{
	ifstream fileIn;
    const int MAX_ARRAY = 500;
    int scores[MAX_ARRAY];
    int numElms, sum;
    int i;

    fileIn.open("pgm5data.txt"); //open file

    if (fileIn.fail() )
    {
        cout << "Error opening file";
        exit(-1);
    }

    i = 0;
    fileIn >> scores[i];
    while (!fileIn.eof() && i < MAX_ARRAY)
    {
        i++;
        fileIn >> scores[i];
		sum+=scores[i];
    }
    numElms = i;

	cout << "\nSum is: " << average(sum, numElms);

    return 0;
}

I don't understand why im getting huge numbers that aren't anywhere close to what I need. Advice? thanks!

Maybe your function should return avg instead of sum?

Your right, but Im still gettting the same error

Hmm...

try initializing sum to 0, see if that helps.

int numElms, sum=0;

//instead of 
int numElms, sum;

I GOT IT, Line 34 should not be there.

Nevermind its giving me a different number for each average

After compiling your code using my own input file I see the problem. You were adding the sum in the wrong place, which was after the last (unsuccessful) read from the file. It was adding a way huge number at the end, which made your calculations off.

I put a couple extra cout's in there to test. Remove them and this code should be what you want:

i = 0;
    fileIn >> scores[i];
    cout<<"scores[i]: "<<scores[i]<<endl;
    while (!fileIn.eof() && i < MAX_ARRAY)
    {
        sum+=scores[i];
        cout<<endl<<i<<": "<<sum<<endl;
        i++;
        fileIn >> scores[i];
        cout<<"scores[i]: "<<scores[i]<<endl;
			
    }
    numElms = i;

	cout << "\nAvg is: " << average(sum, numElms);
commented: Thanks! +1

Beware of this in your function:

double average(int sum, int numElms)
{
	//int i;
	double avg;
        avg = sum/numElms;
	return avg;
}

Since the two operands are integers the result placed into avg will be an integer result (so truncated or 0 if the denominator is bigger) despite the fact that it's a double variable. Cast one (or both) of the operands to a double to get the correct answer. avg = ((double) sum)/numElms;

It was adding a way huge number at the end, which made your calculations off.

Since I cannot edit the post, I'll just add another reply here.

I think the reason for the way huge number is because your array is un-initialized. In case anyone (who didn't know already) wants to know. :)

Since I cannot edit the post, I'll just add another reply here.

I think the reason for the way huge number is because your array is un-initialized. In case anyone (who didn't know already) wants to know. :)

I wasn't undermining what you wrote at all. Sorry if I wasn't clear about that. I was just warning against another issue that was going to manifest itself one way or the other.