Menu
Coddy logo textTech

Recap - Vector Operations

Part of the Logic & Flow section of Coddy's C++ journey — lesson 17 of 56.

challenge icon

Challenge

Easy

Create a program that builds a collection of integers from user input and calculates their sum using vector operations and range-based iteration.

The following inputs will be provided:

  • An integer n representing how many numbers will be entered
  • Then n integers to add to the collection
  • One additional integer to add to the collection

Your program should:

  1. Create an empty std::vector<int> named numbers
  2. Use push_back() to add each of the first n integers to the vector
  3. Use push_back() to add the additional integer to the vector
  4. Use a range-based for loop to iterate through all elements in the vector
  5. Calculate the sum of all numbers in the vector during iteration
  6. Print the total sum of all elements

Use the following exact output format:

Sum: [total sum]

The range-based for loop should use the syntax for (int num : numbers) to access each element. Initialize a sum variable to 0 before the loop, then add each number to the sum during iteration.

Try it yourself

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Read the number of integers
    int n;
    cin >> n;
    
    // Read the n integers
    vector<int> numbers;
    for (int i = 0; i < n; i++) {
        int num;
        cin >> num;
        // TODO: Add num to the vector using push_back()
    }
    
    // Read the additional integer
    int additional;
    cin >> additional;
    // TODO: Add the additional integer to the vector
    
    // TODO: Calculate sum using range-based for loop
    int sum = 0;
    // Write your range-based for loop here
    
    // Output the result
    cout << "Sum: " << sum << endl;
    
    return 0;
}

All lessons in Logic & Flow