Reputation: 109
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
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