Kotlin Array - average() Function



The Kotlin array average() function is used to calculates the average of all the elements of an array. This function works on integers as well as other types and returns a double value.

Following are the types −

  • Byte
  • Short
  • Int
  • Long
  • Float
  • Double

Syntax

Following is the syntax of Kotlin array average() function −

fun IntArray.average(): Double

Parameters

This function does not accepts any parameters

Return value

This function returns an average value of types double.

Example 1

Following is the basic example, we use the average() function to calculates the average of an integer array −

fun main(args: Array<String>) {
   var array = Array(10) { i -> i}

   var result=array.average()
   print("The average of ( ")
   for(i in array)
      print("$i ")
   print(") is $result")
}

Output

Following is the output −

The average of ( 0 1 2 3 4 5 6 7 8 9 ) is 4.5

Example 2

Now, let's see another example. Here, we use the average() function to calculates the average of a float array −

fun main() {
   val array = arrayOf(5.5f, 6.5f, 7.5f, 8.5f)

   val result = array.average()
   println("The average of (${array.joinToString(", ")}) is $result")
}

Output

Following is the output −

The average of (5.5, 6.5, 7.5, 8.5) is 7.0

Example 3

The example below calculates the average of the short array using the average() function −

fun main() {
   val numbers: Array<Short> = arrayOf(1, 2, 3, 4, 5)
   val average = numbers.average()
   println("The average is $average")
}

Output

Following is the output −

The average is 3.0
kotlin_arrays.htm
Advertisements