ChrisMP
ChrisMP

Reputation: 109

Adding All Array Elements Together

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.?

Upvotes: 2

Views: 1313

Answers (2)

Robᵩ
Robᵩ

Reputation: 168626

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";
}

Upvotes: 7

Zameer Manji
Zameer Manji

Reputation: 3025

You can use std::accumulate.

Upvotes: 1

Related Questions