Recap - Vector Operations
Part of the Logic & Flow section of Coddy's C++ journey — lesson 17 of 56.
Challenge
EasyCreate 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
nrepresenting how many numbers will be entered - Then
nintegers to add to the collection - One additional integer to add to the collection
Your program should:
- Create an empty
std::vector<int>namednumbers - Use
push_back()to add each of the firstnintegers to the vector - Use
push_back()to add the additional integer to the vector - Use a range-based for loop to iterate through all elements in the vector
- Calculate the sum of all numbers in the vector during iteration
- 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
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items