1

Its my beginners c++ assignment, I have a file of 12 columns of numbers and having 50 rows.

I am asked to find the average of the 11th column of the numbers and display it on the standard output.

Its a beginners class so NO advanced topics like vectors are allowed .

I was trying to make 12 variables for each coloumn and use the while loop to read the 11th coloumn but can't figure out how to add all the numbers of 11th coloumn into that variable.

The while loop I used was like this:

while(inputfile >> col1 >> col2>> col3>> col4>> col5>> col6>> col7>>
     col8>> col9>> col10>> col11>> col12 ) 
{ cout<< col11 << endl; }

Side note : all the col above are int variables. And inputfile is the ifstream file object

The above loop would print out the whole coloumn 11 but I can't figure out how to add the whole coloumn 11 of 50 rows (i.e 50 numbers) to find the average(divide the total by 50)

The above method might be wrong too

Any help in this matter will be appreciated.

Hopeful of a response soon.

Thanks in advance. :)

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
Love Patel
  • 19
  • 6

2 Answers2

0

Use a variable to store the sum and count and get the average

int sum = 0;
int count = 0;
double average = 0;
cout << "Calculating Average for: \n";
while(inputfile >> col1  >> col2  >> col3 >> col4 >> col5
                >> col6  >> col7  >> col8 >> col9 >> col10 
                >> col11 >> col12 )  { 
    cout << col11 << " ";
    sum += col11;
    ++count;
}
cout << " \n";
average = static_cast<double>(sum)/count;
cout << "Sum: "     << sum << "\n";
     << "Count: "   << count << "\n";
     << "Average: " << average << endl;
Sridhar Nagarajan
  • 1,085
  • 6
  • 14
  • 1
    Since this is an answer aimed at a beginner, I'd strongly suggest editing your answer to follow good practices, such as [using `std::` explcitly](http://stackoverflow.com/a/1452738/1171191), [avoiding `endl`](http://kuhllib.com/2012/01/14/stop-excessive-use-of-stdendl/), and personally I prefer pre- to post-increment for `count` - not a big deal in this case, but a good habit for objects that are more expensive to copy. Also, is it really best to just drop a complete code answer for a homework question? You could give the necessary parts, with explanation, and let the asker integrate it. – BoBTFish Feb 25 '15 at 08:26
  • (Also worth pointing out that while I do agree with Dietmar's arguments re. `endl`, I avoid it more for clarity of code than performance reasons; it is so often misunderstood and misused, I prefer to just make the `flush` explicit when I really do mean it.) – BoBTFish Feb 25 '15 at 08:30
  • Even more concerning, your code completely incorrectly calculates the average. `sum/count` is an integer division, so will truncate the result to an `int` *before* converting to a `double`! – BoBTFish Feb 25 '15 at 08:38
  • I agree with your point @BoBTFish made some edits, ,one thing though, using `std::` for a code which does not have any namespace except `std` is unnecessary. – Sridhar Nagarajan Feb 25 '15 at 14:51
  • Still a pretty awful habit to get into: it's a problem in most cases, and provides no benefit in the case where there is no current name clash risk. All but the most trivial 3 line code example *should* use namespaces, so there is every chance your code will have namespaces in the future *or* it is a code sample for a beginner, who we don't want to learn bad habits. It makes the code much easier to read when you know where a function comes from. People understand the semantics of Standard LIbrary functions, but might not assume that is what you are using without the `std::` prefix. – BoBTFish Feb 25 '15 at 14:55
  • @BoBTFish thanks for the info, will keep in mind for future answers. – Sridhar Nagarajan Feb 25 '15 at 15:01
0

Since the only answer is wrong, and the comment perhaps missing a vital clue...

You need to keep a running total of the collumn 11 values. I'd also keep track of the count, although in your case you could just skip that and hard-code the value 50. So the bits you need are:

int total = 0;
int count = 0;

then in your read loop:

while (...) {
    total += col11; // keep a running total
    ++count; // add 1 to count
}

Then to calculate the average, you divide one by the other.

But, this is a little tricky. If you do it directly, you divide one int by another int, and get the result truncated to an int. E.g. 1/2 would give you 0, which is not what you mean (0.5).

You need to use a cast to turn at least one of the values into a double before the division is done:

double average = static_cast<double>(total) / count;

See full code here.

Other ways around the division problem would be to store total or count as a double in the first place, although I find that misleading as they are really integers, or if you are sticking with using 50 directly, you could just do average = total / 50.0 (50.0 is a double value).

Since you are a beginner, I'll also take a moment to advise you against using namespace std; and use of endl, not just for performance reasons, but also to make the code clearer by separating the unrelated actions of writing a newline and flushing a stream.

Community
  • 1
  • 1
BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • Hi Thanks a lot for this but I would like to know, about why would I prefer pre increment instead of post increment of count in this case? – Love Patel Feb 25 '15 at 14:22
  • In this particular case, it doesn't make a lot of difference. That is, the compiler will optimise away the difference. `++i` just increments `i` in place. `i++` increments `i`, but returns a copy of its original value. Since you don't use that previous value, why bother creating it? Not too expensive with `int`s, and almost certainly optimised out, but for objects that are expensive to copy, or in a tight loop, it could matter. Hence I prefer `++i` unless I have an actual reason to use `i++`. Yes, the name of the language is [wrong](http://tinyurl.com/qzqkpap). – BoBTFish Feb 25 '15 at 14:27
  • I would also like to know about the cerr object, what is it and when and where is it used, and how different is it from the cout obj, Also is while loop must here or it can be done with other loops aswell?? – Love Patel Feb 25 '15 at 18:31
  • @LovePatel [`std::cerr`](http://en.cppreference.com/w/cpp/io/cerr) is basically the same as `std::cout`, except that it writes to the stderr output (usually the same terminal as stdout unless you have redirected one of them) and it flushes on every write operation. It is intended for reporting errors back to the user immediately. `for `and `while` loops are equivalent, you can always reword one as the other, they are just syntactical convenience. – BoBTFish Feb 26 '15 at 07:32