Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming Principles and Practice using C++, 2 nd Edition by Bjarne Stroustrup

ID: 3695775 • Letter: P

Question

Programming Principles and Practice using C++, 2 nd Edition by Bjarne Stroustrup. Addison Wesley/Pearson, 2014

Write a program that reads and stores a series of integers and then computes the sum of the N integers. First ask for N, then read the values into a vector, then calculate the sum of the first N value. For example:

"Please enter the number of values you want to sum:"

3

"Please enter some integers (press '|' to stop):"

12 23 13 24 15 |

"The sum of the first 3 numbers (12 23 13) is 48."

Handle all inputs. For example, make sure to give an error message if the user asks for a sum of more numbers than there are in the vector.

Explanation / Answer

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

int main()
{

vector<int> vec;
int i,n,sum=0;
string s;

cout << "Please enter the number of values you want to sum:" << endl;
cin >> n;

std::string::size_type sz;
cout << "Please enter some integers (press '|' to stop):" << endl;
while(true){
cin >> s;
if(s=="|")
break;
int num = stoi(s,&sz);
vec.push_back(num);
}

for(i = 0; i < n; i++){
sum =sum + vec[i];
}

cout << "sum =" << sum <<endl;

return 0;
}