2

I wanted to know how I could add all of the elements of a float array together and make the sum float average;. Would I have to use a for loop or is there another way to add element 0 with 1 with 2 with 3, etc.?

3
  • Is this a homework assignment? Commented Oct 5, 2011 at 14:40
  • 2
    Adding a bunch of floats is tricky, does the result have to be "as precise as possible", just "a bit precise" or can it be "naively sum them" (the difference with the actual sum can be quite big in that case) Commented Oct 5, 2011 at 15:04
  • @harold: from another question of Chris, it seems that those are grades, so the magnitude of the elements should be about the same. In this case, I think precision is not too much of an issue. Commented Oct 5, 2011 at 16:47

2 Answers 2

7

You may use a for loop, or you can use std::accumulate.

#include <iostream>
#include <numeric>

int main()
{
  float arr[17] = { 1, 2, 3, };

  //Sum the array
  const float sum = std::accumulate(arr, arr+17, 0.0 ); 

  std::cout << "Sum: " << sum << "\n";
  std::cout << "Average: " << sum/17 << "\n";
}
Sign up to request clarification or add additional context in comments.

2 Comments

while a good answer, that comment in the middle is a bit misleading :D
Thanks, @MooingDuck. As you might imagine, I didn't write my answer from scratch. I cribbed it from a "how to sum std::vector" example.
1

You can use std::accumulate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.