how to find the sum of a vector c++
To find the sum of a vector in C++, you can use a loop to iterate through each element of the vector and add them together. Here is an example code snippet that demonstrates this:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < numbers.size(); i++) {
sum += numbers[i];
}
std::cout << "The sum of the vector is: " << sum << std::endl;
return 0;
}
In this code, we first include the necessary header files iostream
and vector
to work with vectors and output the result. We then declare a std::vector<int>
named numbers
and initialize it with some integer values.
Next, we declare an integer variable sum
and initialize it to 0. This variable will store the sum of the vector elements.
We then use a for
loop to iterate through each element of the vector. The loop variable i
starts from 0 and goes up to numbers.size() - 1
, which is the index of the last element in the vector. We access each element using the subscript operator []
and add it to the sum
variable.
Finally, we print the value of sum
using std::cout
and the insertion operator <<
.
When you run this code, it will output the sum of the vector, which in this case is 15. You can modify the numbers
vector or add more elements to test the code with different inputs.