
- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
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