-2

I'm very new to coding and was just playing around with vectors however I cant seem to find out how to add all elements in a vector together when the amount of elements is user-defined.

#include <iostream>
#include <vector>

using namespace std;

int NoOfItems;
int i=1;
double Odds;
double Cost;
vector<double> CaseNumber;

int main()
{ 
    cout << "How many items in the case: ";
    cin >> NoOfItems;
    while (true) {    
        if (NoOfItems == 0) {
            break;
        } else { 
            cout << "Odds for item " << i <<endl;
            cin >> Odds;
            CaseNumber.push_back(Odds);
            NoOfItems = NoOfItems - 1;
            i = i + 1; 
        }
    }   
}
t j
  • 7,026
  • 12
  • 46
  • 66
O Johnson
  • 1
  • 1

1 Answers1

1

You'll want to spend some time cleaning up your code. There's some very questionable code conventions being used.

Anyways, to sum all of the elements of your vector:

double sum = 0;
for(size_t index = 0; index < CaseNumber.size(); index++) {
    sum += CaseNumber[index];
}

Or, in a way that's slightly more friendly to the semantics of C++:

double sum = 0;
for(double & d : CaseNumber) {
    sum += d;
}

Either will result in the variable sum containing the sum total of all elements in CaseNumber

Xirema
  • 19,889
  • 4
  • 32
  • 68
  • 8
    That, or use `std::accumulate`. – Louis Dionne Feb 11 '16 at 19:37
  • @LouisDionne That too, although given that the user appears to be extremely new to C++ programming, I'd probably recommend this method instead to ensure they understand the underlying mechanics of what they're trying to do. – Xirema Feb 11 '16 at 19:39
  • _@Xirema_ You should at least mention @Louis proposal in your question, because that would make your answer different from the most upvoted and accepted answer in the already proposed duplicate. – πάντα ῥεῖ Feb 11 '16 at 19:42