-3

This might be a bit of a noob question but let's say we have an integer vector with 40 elements. How could i use a for loop to iterate through the vector while adding the elements in groups of 10?

So the first 10 elements would be added and stored, then the next 10 elements, and so on?

I'm not sure what condition to use?

int sum; 
for(int i = 0; i < vec.size(); i++)
{
if(some condition)
{
sum = vec[i] + sum; 
}
}
Nicholas
  • 89
  • 6

1 Answers1

2

This is purely an example, as there are potential errors with this approach (see below) -- but it's a demonstration of how you might approach the problem.

The outer loop counts buckets (an arbitrary name for your groups of 10), while the inner loop goes through each element in that bucket.

std::vector<int> sum_buckets_of_10(const std::vector<int> &values) {
    std::vector<int> result(values.size() / 10);

    for(unsigned int bucket = 0; bucket = values.size() / 10; bucket += 1) {
        int sum = 0;
        for(unsigned int index = 0; index < 10; index += 1)
            sum += values[bucket * 10 + index];
        result[bucket] = sum;
    }

    return result;
}

Note that this approach assumes you're working with a values vector that contains a multiple of 10 elements. You'll have to think about how to adapt it for arbitrary sizes.

Inigo Selwood
  • 822
  • 9
  • 20