#include <iostream>
#include <vector>
usingnamespace std;
int main( )
{
int n,i,temp;
int sum = 0;
vector<int> v;
cout << "Enter a list of positive numbers.\n"
<< "Place a negative number at the end.\n";
int next;
cin >> next;
while (next > 0)
{
v.push_back(next);
cout << next << " added. ";
cout << "v.size( ) = " << v.size( ) << endl;
cin >> next;
}
for(i=0;i<n;i++)
{
cout << "Enter number" << i+1 << " : ";
cin >> temp;
sum += temp;
}
cout << "\n\nSum of the " << n << " numbers entered by the user is : "<< sum << endl;
cout << "\n\n\n";
return 0;
}
Usually it's easier to read the code (and less chance of forgetting to initialize) if you declare the variables as late as possible (when you know what value to give to them) rather than at the beginning of the function.
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> v;
std::cout << "Enter a list of positive numbers.\n"
<< "Place a negative number at the end.\n";
for (int next; (std::cin >> next) && next >= 0; v.push_back(next))
std::cout << next << " added.\n";
std::cout << "\n\nSum of the " << v.size() << " numbers entered by the user is : " << std::accumulate(v.begin(), v.end(), 0) << "\n\n";
}
Obviously you don't need to use a vector to store the numbers before they are totalled. A running total could be kept as they were entered:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
int main() {
unsigned sum {};
unsigned noNums {};
std::cout << "Enter a list of positive numbers.\n"
<< "Place a negative number at the end.\n";
for (int next; (std::cin >> next) && next >= 0; ++noNums, sum += next)
std::cout << next << " added.\n";
std::cout << "\n\nSum of the " << noNums << " numbers entered by the user is : " << sum << "\n\n";
}