Find the average value from an array in Swift
In this Swift programming tutorial, we are going to learn how to find the average value from an array.
We can easily find the average of all the elements of an array using the following method. Let us understand it step by step in a simple way.
Average value from an array in Swift
Firstly let us declare an integer array of definite length as shown below.
let arr = [1,2,3,4,5,6]
Now we will calculate the sum of all the elements of the array using a reduce method. The reduce method helps us to convert the array into a single value.
The intial_value is the starting value whereas the next_partial_value tells us how it should combine the initial value with every element of an array.
var sum = arr.reduce(0,+)
Here, the reduce method adds the initial value 0 to the first element of an array and that result becomes the initial value of the next element of the array. It continues till there is no element left in the array. At last, the method returns the final initial value as a sum.
Now, we will calculate the length of the array using a built-in property known as count. It returns the number of elements present in the array.
var length = arr.count
We know that average is calculated as the sum of elements divided by the number of elements. So let us divide the sum by length to get the average as result and print it.
var avg = Double(sum)/Double(length) print(avg)
Here, we have converted the types of sum and length to Double to get the result in decimal.
Swift program to find the average value from an array
let arr = [1,2,3,4,5,6] var sum = arr.reduce(0,+) var length = arr.count var avg = Double(sum)/Double(length) print(avg)