Skip to content

Instantly share code, notes, and snippets.

@EricTendian
Last active December 26, 2015 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EricTendian/7110413 to your computer and use it in GitHub Desktop.
Save EricTendian/7110413 to your computer and use it in GitHub Desktop.
Reads a file called grades.txt with 20 grades, one on each line, and outputs the average of all the numbers.
#include <iostream>
#include <fstream>
using namespace std;
const int STUDENTS = 20;
double findAvg(int[]);
int main() {
int grades[STUDENTS] ;
ifstream in;
in.open("grades.txt");
int currLine;
int cnt = 0;
while (in >> currLine) {
if (cnt>STUDENTS) {
cout << "Error: excess number of grades.";
break;
}
grades[cnt] = int(currLine);
cnt++;
}
in.close();
cout << findAvg(grades) << endl;
}
double findAvg(int grades[]) {
int sum = 0;
double avg = 0;
for (int i = 0; i < STUDENTS; i++) {
sum+=grades[i];
}
avg = double(sum) / double(STUDENTS);
return avg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment