Programming & Design
Question:
How do you find the sum of an array in c++?
?
2013-10-22 18:10:22 UTC
Let's say the array is for Cities with corresponding Outages.
How do I show the Sum of all of the outages.
Three answers:
?
2013-10-22 18:57:11 UTC
By adding them up.
_Object
2013-10-22 18:42:53 UTC
"Let's say the array is for Cities with corresponding Outages. "
Would std:: map<> (or even std:: vector<>) not be a better fit in this case?
The sum of all elements* in an array.may be found easily by invoking
for (const auto & Val: OutagesArray) {
Sum += Val;
}
OR
's std:: for_each<> function:
http://en.cppreference.com/w/cpp/algorithm/for_each
class Sum {
int val;
Sum(): val(0) {}
void operator (const int N) {val += N;}
};
int main(int, char **) {
int Outages[] = {329, 123, 12048723, 123, -123124, -9123124};
Sum s = std::for_each(Outages, Outages + 6, Sum());
std:: cout << s.val;
}
2013-10-22 18:32:12 UTC
I take it you're trying to sum every element of the array.
Just do a loop, make the loop variable go from the start of the array to the end. Keep accumulating the array values.
sum = 0;
for(i=0; i
sum = sum array[i];
}
Is really simple.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...