*Find the average value of the given array of numbers.*

Calculating the average value of an array has two subtasksâ€”calculate the sum and divide it by the size of the array. So, one of the solutions can look like this:

my @data = 7, 11, 34, 50, 200;

say sum(@data) / @data;

Here, theÂ `sum`

built-in function returns the sum of the elements of theÂ `@data`

array. To get the size of an array, you may call theÂ `elems`

method:

say sum(@data) / @data.elems;

This is a straightforward way, which is a bit redundant for our task. As theÂ `@data`

is used in numeric context as an operand of the division operator, explicitly calling theÂ `elems`

method is not necessary.

Another approach is to use the reduction operator:

say ([+] @data) / @data;

In this example,Â `[+] @data`

is equivalent toÂ `@data[0] + @data[1] +Â ...+ @data[N]`

, where theÂ `+`

operator is placed between all the elements of the array. Be careful with the parentheses in this code. If you omit them, the result will be incorrect, as the actual sum consists of a single elementÂ `@data / @data`

, which equals one. If you omit the space before the opening brace, it will be considered as a parenthesis grouping the arguments of theÂ sayfunction, and the result is also incorrect, as the code prints only the sum of the array elements and divides the result ofÂ `say`

(which isÂ 1).

### Like this:

Like Loading...

*Related*