matiboy212121
matiboy212121

Reputation: 101

Specific number of elements - vectors

I am trying to print out the sum of the first 'x' elements within a vector. Basically, the user inputs a bunch of numbers (which are pushed back into the vector) and once they decide to exit the loop, they have to choose the number of elements that they want to sum.

For example, if they entered "6, 5, 43, 21, 2, 1", they choose the numbers which they wish to sum, e.g. "3". Finally, the output should be "The sum of the first 3 numbers is "6, 5, and 43 is 54".

The only thing I have found was to find the sum of the vector which (I believe) is not much use to me.

I also checked a c++ website with the <vector> library but can't figure if any of the functions are of much use. This is for c++ and bear in mind that, I am a new programmer.

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

int main()
{
    //  1) read in numbers from user input, into vector -DONE
    //  2) Include a prompt for user to choose to stop inputting numbers - DONE
    //  3) ask user how many nums they want to sum from vector -
    //  4) print the sum of the first (e.g. 3 if user chooses) elemens in vector.
    vector <int> nums;
    int userInput, n, total;

    cout << "Please enter some numbers (press '|' to stop input) " << endl;
    while (cin >> userInput) 
    {
        if (userInput == '|') 
        {
            break; //stops the loop if the input is |.
        }
        nums.push_back(userInput); //push back userInput into nums vector.
    }
    cout << "How many numbers do you want to sum from the vector (the numbers you inputted) ? " << endl;
    cin >> total;
    cout << nums.size() - nums[total]; //stuck here
    return 0;
}

Upvotes: 2

Views: 700

Answers (2)

JeJo
JeJo

Reputation: 32972

You can use std::accumulate from the <numeric>, to calculate the sum of a range, as follows.

#include <numeric>  // std::accumulate
#include <vector>

int sumUpTo(const std::vector<int>& vec, const std::size_t total)
{
    if (total > vec.size()) 
    // if the index exceeds the vec size
    // return the sum of the conatining elelemnts or provide an exception
        return std::accumulate(vec.begin(), vec.end(), 0); 
    
    return std::accumulate(vec.begin(), vec.begin() + total, 0);
}

(See a demo)


Also comparing the integer with a char here

if (userInput == '|') 

will fail when the user enters 124, because (int)'|' == 124. You need to rethink this part. My suggestion would be asking the user the number of elements he/she wants to input beforehand and run the loop only for that.

Also do not practice with using namespace std;

Upvotes: 3

asmmo
asmmo

Reputation: 7100

You can use std::accumulate from header <numeric>, as follows

std::cout << std::accumulate(nums.begin(), nums.begin()+total,0);

Upvotes: 2

Related Questions