sum elements in vector c++
#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 elements in the vector is: " << sum << std::endl;
return 0;
}
Explanation:
Include necessary libraries:
iostream
for input/output andvector
for using vectors.Define the main function: The program starts executing from here.
Create a vector of integers:
std::vector<int> numbers = {1, 2, 3, 4, 5};
initializes a vector namednumbers
with five integers: 1, 2, 3, 4, and 5.Initialize a variable for sum:
int sum = 0;
declares an integer variablesum
and initializes it to zero.Loop through the vector elements:
for (int i = 0; i < numbers.size(); ++i)
initiates a loop that starts from 0 and iterates up to the size of the vectornumbers
.Accumulate the sum:
sum += numbers[i];
adds each element of the vectornumbers
to thesum
variable.Print the sum:
std::cout << "The sum of elements in the vector is: " << sum << std::endl;
outputs the calculated sum of the elements in the vector to the console.Return 0:
return 0;
signifies a successful execution and termination of the program.