Array Homework help!

Hey there guys!

I need help with my arrays homework. So I have to write c++ program where it needs to read the integers from a file names "numbers.txt", pass that array of integers to a function which will compute and return the average (as a double) and display the average returned from the function.

This is all I have currently:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
int n = 0; //n is the number of the integers in the file ==> 12
int num;
int arr[100];

ifstream File;
File.open("numbers.txt");
while(!File.eof())
{
File >> arr[n];
n++;
}

File.close();

for(int i=0;i<12;n++)
{
cout << arr[i] << " ";
}

cout << "done\n";
return 0;
}




Can ya'll help me out? I JUST CAN'T FIGURE IT OUT AND I THINK I AM OVERTHINKING!
Last edited on
for(int i=0;i<12;n++)
Maybe you want to change that to
for(int i=0;i<n;i++)


Don't use while(!File.eof()), since this won't fail at the point when there is nothing left; (it will fail after the next aborted read).
Use
while(File >> arr[n]) n++;
or, better, check you have enough space first:
while(n<100 && File >> arr[n]) n++;
for function that computes average:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
double AverageFinder(int arr[], int n){
double average;
int total;

for(int i = 0; i < n; i++){

//add each number in the array

}

average = total / n;

return average;


then in main set your call on this function equal to the variable that you will use for your average.
ex:
average = AverageFinder(arr, n)
Topic archived. No new replies allowed.