How to get the average in an array

it a an C++ and it need to accept an array as a parameter and loop though the array adding the array elements and return their sum divided by the number of elements used. Am confused on changed it to find the average added on with the highest and lowest number.

1
2
3
4
5
6
7
8
9
10
{  
   int i;   
   
   max = min = v[0];
   
   for (i = 1; i < n; i++) ]
   {  
      if (v[i] > max) max = v[i];
      if (v[i] < min) min = v[i];
   }
What do you mean by
the average added on with the highest and lowest number
Ignoring your last statement:
Supposing you had a six element array int a[]={1,4,27,13,6 ,2};
You could use a for loop to print out the individual elements with say cout<<a[i]<<" "; in the body of the for loop.
If you had a statement also in this for loop body like sum+=a[1], sum when printed would = 53.
sum/number of element=average of array values= 8. How would you get a more accurate average?
simple example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <numeric>

int main()
{
    int array[] = {1, 2, 4, 5, 6};

    const int Count = sizeof(array) / sizeof(array[0]);
    int average = std::accumulate(array, array + Count, 0) / Count;
    std::cout << average << '\n';

    return 0;
}
buffbill, (i) you probably mean sum+=a[i];, (ii) more accurate average can be done if avarage is not integer, e.g.
1
2
3
4
double av;
int sum = 0, count = 0;
...
av = sum / double(count);


Note that, at least, the denominator must be cast to double type.
Last edited on
buffbill, (i) you probably mean sum+=a[i]

Yep i certainly did, Thanks for pointing out the error. 1 should be 'i'
Topic archived. No new replies allowed.