C++ find sum of vector

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> vec = {1, 2, 3, 4, 5};
    int sum = 0;

    for (int i = 0; i < vec.size(); i++) {
        sum += vec[i];
    }

    std::cout << "The sum of the vector is: " << sum << std::endl;

    return 0;
}

Explanation of each step:

  1. Include necessary libraries: The code starts by including the <iostream> and <vector> libraries, which are required for input/output operations and using the vector container, respectively.

  2. Declare and initialize the vector: A vector named vec is declared and initialized with some integer values. In this example, we have initialized it with the values 1, 2, 3, 4, and 5.

  3. Declare and initialize the sum: An integer variable named sum is declared and initialized to 0. This variable will store the sum of the vector elements.

  4. Iterate through the vector: A for loop is used to iterate through each element of the vector. The loop variable i starts from 0 and goes up to vec.size() - 1. vec.size() returns the number of elements in the vector.

  5. Calculate the sum: Inside the loop, each element of the vector is added to the sum variable using the += operator. This accumulates the sum of all elements in the vector.

  6. Print the result: After the loop ends, the calculated sum is printed to the console using std::cout and the insertion operator <<.

  7. Return 0: The main() function ends with return 0;, indicating successful program execution to the operating system.

This code snippet finds the sum of a vector by iterating through its elements and accumulating their values in a separate variable.