0

I'm trying to calculate the average of specific lines in an array. For example the format of the array looks like this:

float Array[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,...20}

I want to calculate the average of the first 5 numbers in the array, then the average of the next 5 numbers and so on... storing them into another array with only the averages of those numbers.

Here's my code so far

float average_values[4];
for (int a = 0; a < 4; a++){    //20 elements in array divided by 5 = 4
    float sum = 0;
    for (int b = 0; b < (20 / 4); b++){
        sum = sum + scores[b];
    }
    average_values[i] = sum / (20 / 4);
}
0

3 Answers 3

1
#include <stdio.h>
int main()
{
        int scores[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20};
        float average_values[4];
        for (int a = 0; a < 4; a++)
        {    //20 elements in array divided by 5 = 4
            float sum = 0;
            for (int b = 0; b < (20 / 4); b++)
                sum = sum + scores[b+a*5]; // THIS IS THE BIT YOU'D MISSED
            average_values[a] = sum / (20 / 4);
        }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Keeping aside all typos in your current post

I assume you have trouble in filling up your average_values array.

So assume scores array as matrix for 5 columns and 4 rows,

So your inner loop should look like:

for (int b = 0; b < 5; b++){
    sum = sum + scores[ a*5 + b];
                      //~~~ Correct index for next sets
}

Comments

0

With range-v3, it would be:

auto means = Array
             | ranges::view::chunk(5)
             | ranges::view::transform([](auto&& r) { return ranges::accumulate(r, 0.f) / 5; });

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.