C++ sum a vector of digits
C++ code to sum a vector of digits:
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> digits = {1, 2, 3, 4, 5};
int sum = std::accumulate(digits.begin(), digits.end(), 0);
std::cout << "Sum of the digits: " << sum << std::endl;
return 0;
}
Explanation:
- Include Libraries:
#include <iostream>
: This library allows input and output operations.#include <vector>
: This library allows the use of vectors.#include <numeric>
: This library provides numeric algorithms.Main Function:
The program's entry point is the
main
function.Vector Initialization:
std::vector<int> digits = {1, 2, 3, 4, 5};
: A vector nameddigits
is created and initialized with the values 1, 2, 3, 4, and 5.Sum Calculation:
int sum = std::accumulate(digits.begin(), digits.end(), 0);
: Thestd::accumulate
algorithm is used to calculate the sum of the digits in the vector. It takes the range of the vector (digits.begin()
anddigits.end()
) and an initial value of 0.Output:
std::cout << "Sum of the digits: " << sum << std::endl;
: The sum of the digits is printed to the standard output.Return:
return 0;
: Themain
function returns 0 to indicate successful program execution. ```