English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to calculate the average of a given array in Kotlin.
fun main(args: Array<String>) { val numArray = doubleArrayOf(45.3, 67.5, -45.6, 20.34, 33.0, 45.6) var sum = 0.0 for (num in numArray) { sum += num } val average = sum / numArray.size println("Average: %.2f".format(average)) }
When running the program, the output is:
Average: 27.69
In the above program, numArray stores the floating-point values required for the average.
Then, to calculate average, we need to first calculate the sum of all elements in the sum array. This is done using the for loop in Java.-each loop completed.
Finally, we calculate the average using the following formula:
average = sum of numbers / total count
In this case, the total count (total count) is given by numArray.length.
Finally, we use the format() function to print the average so that it uses “%.2f”to limit the decimal point to2
This is the equivalent Java code:Java Program to Calculate Average Using Array