C++ Online Compiler
Example: Summing Integers in a Vector in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Summing Integers in a Vector #include <iostream> #include <vector> // Required for std::vector #include <numeric> // Required for std::accumulate (alternative) using namespace std; int main() { // Step 1: Declare and initialize a vector of integers vector<int> numbers = {10, 20, 30, 40, 50}; // Step 2: Initialize a variable to store the sum int total = 0; // Step 3: Iterate through the vector and add each element to the total for (int num : numbers) { // Range-based for loop for convenience total += num; } // Alternative using std::accumulate (requires <numeric>) // int total_accumulate = accumulate(numbers.begin(), numbers.end(), 0); // cout << "The total sum using std::accumulate is: " << total_accumulate << endl; // Step 4: Display the final result cout << "The sum of integers in the vector is: " << total << endl; return 0; }
Output
Clear
ADVERTISEMENTS