say I have an array that is an integer and stores five numbers, I want to add these numbers together and put them into a certain variable, how do I do this. if you have the answer to this then it would be greatly appreciated if you could respond. thanks.
Asked
Active
Viewed 183 times
-2
-
`for(const auto& val:array) sum += val;` Remember to make `sum` a data type large enough to store the sum and also remember to initialize it to 0. – user4581301 Nov 25 '20 at 17:27
-
2Does this answer your question? [How to sum up elements of a C++ vector?](https://stackoverflow.com/questions/3221812/how-to-sum-up-elements-of-a-c-vector) – Take_Care_ Nov 25 '20 at 17:29
-
See [`std::accumulate`](https://en.cppreference.com/w/cpp/algorithm/accumulate) – Thomas Matthews Nov 25 '20 at 17:37
1 Answers
0
Here is a simple code to sum integers:
#include <vector>
#include <iostream>
int main() {
std::vector<int> a = {1, 2, 3, 4, 5};
int res = 0;
for (auto x: a)
res += x;
std::cout << res << std::endl;
return 0;
}
Output:
15
Alternative way is to use std::accumulate:
#include <vector>
#include <iostream>
#include <numeric>
int main() {
std::vector<int> a = {1, 2, 3, 4, 5};
auto res = std::accumulate(a.begin(), a.end(), 0);
std::cout << res << std::endl;
return 0;
}

Arty
- 14,883
- 6
- 36
- 69