Function to calculate the average of an array

Hello every one,
i make a function to return the average value of an array in C++ as follow

double getAverage(int arr[])
{
int sizeArr;
sizeArr = sizeof(arr) / sizeof(*arr);
int sum = 0;
double avg;
for (int i = 0; i < sizeArr; i++)
{
sum += arr[i];
}
avg = double(sum) / sizeArr;
return avg;
}

However i does not work properly, it always returns the first value of the array. Any suggestion would be appriciated!
Your problem is here:

sizeof(arr)

arr is a pointer. so this will give you the size of a pointer (typically 4 bytes). It will not give you the size of the array.

The size of the array cannot be obtained from the pointer alone, and must be passed separately to the function:

1
2
3
double getAverage(int arr[], int sizeArr)
{
  //... 



EDIT: this issue is why I really dislike the use of sizeof() to determine array sizes.
Last edited on
> this issue is why I really dislike the use of sizeof() to determine array sizes.

So don't use it. Instead, use something like this:
1
2
template < typename T, std::size_t N > 
constexpr std::size_t size( T(&)[N] ) { return N ; }


Thanks all you guys!
You may do not bother about arrays' sizes if you will use standard algorithms.:)

For example

double average = std::accumulate( std::begin( a ), std::end( a ), 0.0 ) / std::distance( std::begin( a ), std::end( a ) );
Last edited on
For variety, boost has a library for calculating statistics too, although it's probably an overkill to use it for the average alone:

1
2
3
4
5
6
7
template<size_t N>
double getAverage(int (&arr)[N])
{
    using namespace boost::accumulators;
    return mean(std::for_each(arr, arr+N,
                accumulator_set<double, stats<tag::mean>>()));
}                


http://liveworkspace.org/code/U5yQ1$0
Here's something I did a few weeks ago:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iterator>
#include <vector>
// Returns the sum of all values in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type 
    sumRange( Iter first, Iter last)
{
    std::iterator_traits<Iter>::value_type sum = std::iterator_traits<Iter>::value_type(0);
    while ( first != last )
        sum += *first++;
    return sum;
}

// Returns the number of elements in an array with a pointer to the start and a pointer to the end+1
template <class Iter>
int sizeRange ( Iter first, Iter last)
{
    return last - first;
}

// Returns the mean of all elements in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type 
    mean(Iter first, Iter last)
{
    return sumRange(first, last) / sizeRange(first, last);
}

// Returns the mean of all elements in the range [first, last)
template <class Iter>
typename std::iterator_traits<Iter>::value_type 
    median(Iter first, Iter last)
{
    std::vector< std::iterator_traits<Iter>::value_type > arr( first, last );

    std::sort( arr.begin(), arr.end() );

    return arr.at( arr.size()/2 );
}

// Returns the first mode of all elements in the range [first, last)
// If no mode is found, 0 is returned.
template <class Iter>
typename std::iterator_traits<Iter>::value_type 
    mode(Iter first, Iter last)
{
    typedef std::iterator_traits<Iter>::value_type type_t;

    std::vector<type_t> arr (first, last);

    std::sort(arr.begin(), arr.end() );

    type_t output = type_t();
    int final_frequency = 0;
    int local_frequency = 0;

    for (std::vector<type_t>::iterator it = arr.begin(); it != arr.end()-1; ++it)
    {
        if (*it == *(it+1)) local_frequency++;
        else                local_frequency = 0;

        if (local_frequency > final_frequency)
        {
            final_frequency = local_frequency;
            output = *it;
        }
    }

    return output;
}
Last edited on
closed account (o3hC5Di1)
Just out of interest, why didn't you use:

sumRange - std::accumulate
sizeRange - std::distance

Again, just out of interest, not criticizing :)

All the best,
NwN
Topic archived. No new replies allowed.