Summation Using Iteration Loop
Make a program that continuously prompts the user to enter integer numbers.
The program should accept and store these numbers in a std::vector<int>.
If the user enters a negative number, the program should stop asking for more numbers.
Use an iteration loop to output all of the stored numberes, and calculate the sum of them. Then output the sum.
Answer
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers;
int input;
// Prompt for input until a negative number is entered
std::cout << "Enter numbers (negative number to end): ";
while (std::cin >> input && input >= 0) {
numbers.push_back(input);
}
int sum = 0;
std::cout << "Elements in the vector: ";
// Iterate over the vector, print each element, and add to sum
for (int num : numbers) {
std::cout << num << " ";
sum += num;
}
// Output the sum
std::cout << "\nSum of elements: " << sum << std::endl;
return 0;
}
In this program
std::cin >> inputis included as part of thewhilecondition.std::cin >> inputwill be evaluated as false if there is a type missmatch, or an input failure. This effectively makes it so that the input will stop if the user inputs a value that doesn't work with our program. This goes beyond the original scope of the task. Puttingstd::cin >> inputinside the while loop and checking that it's positive before callingpush_backis also sufficient.