reading in a file and using for loops to calculate statistics

Hi, I'm very new to programming and i'm still trying to figure it out. Please any help with this would be very appreciated.

For this project, we have to write simple for loops to read 100000 numbers from a file. We actually read the same numbers twice, once in each of 2 for loops. The first for loop sums up all of the numbers and calculates the average.

1.Prompt for and read a file name.
2.Open the file
3.Use a for loop to read and sum up (in a long) the first 100000 int numbers in the file (e.g. sum1)
4.Also inside the loop, we have to find the biggest and smallest number using if statements to find each of these.
5. Then we calculate the average (in a double)
6.Close the file

The second for loop uses that mean when re-reading each of the numbers to calculate a variance and standard deviation for the numbers. Then we print the statistics you have calculated.

This is what I have so far, which i'm not sure if it's right. Please any help would be greatly appreciated, I spent most of friday and saturday working on it and still couldn't figure it out.

#define _USE_MATH_DEFINES // for C++
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>


using namespace std;

int main()
{
int numbers;
long sum;
double mean;
string file;
cout <<"Enter a file name: " <<endl;
cin >> file;
ifstream inFile;
return 0;
}
Last edited on
Please use code tags so the site will add line numbers to your code. Edit your post, highlight the code and click the <> button to the right of the edit window.

Here is your code extended to read 100,000 numbers from the file twice
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#define _USE_MATH_DEFINES			 // for C++
#include <cmath>
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int
main()
{
    int number;
    long sum;
    double mean;
    string file;
    cout << "Enter a file name: " << endl;
    cin >> file;
    ifstream inFile(file);

    for (int i=0; i<100000; ++i) { // for loop runs 100,000 times
	// read a number and check if the stream is still valid.
	if (!(inFile >> number)) {
	    // oops. Something wrong.
	    cout << "Can't read the " << i+1 << "'th number\n";
	    return 1;
	}
    }
    inFile.seekg(0);		// seek back to the beginning of the stream
    for (int i=0; i<100000; ++i) {
	inFile >> number;	// no error checking since it worked the first time.
    }

    return 0;
}


Just add code to compute the sum, biggest, smallest, average and standard deviation. I urge you do do these one at a time. In other words, add code to compute the sum, get that working and then move on to compute the biggest etc.

Also, I'd have it read a small number (like 5) of the values first so you can test it an verify your results.
Topic archived. No new replies allowed.