Skip to main content

How to calculate the average of a list of numbers in Kotlin

How to calculate the average of a list of numbers in Kotlin.

Here's a step-by-step tutorial on how to calculate the average of a list of numbers in Kotlin:

  1. First, create a list of numbers that you want to calculate the average of. For example, let's say we have the following list of numbers: [5, 10, 15, 20, 25].

  2. Initialize two variables: sum and count. Set sum to 0 and count to the number of elements in the list. In Kotlin, you can get the number of elements in a list using the size property. So, in our case, count will be equal to 5.

val numbers = listOf(5, 10, 15, 20, 25)
val count = numbers.size
var sum = 0
  1. Iterate over the list using a for loop. Add each number to the sum variable.
for (number in numbers) {
sum += number
}
  1. Calculate the average by dividing the sum by the count. To ensure that the average is a floating-point number, you can use the toDouble() function.
val average: Double = sum.toDouble() / count
  1. Print the average to the console.
println("The average is: $average")

Putting it all together, here's the complete code:

val numbers = listOf(5, 10, 15, 20, 25)
val count = numbers.size
var sum = 0

for (number in numbers) {
sum += number
}

val average: Double = sum.toDouble() / count

println("The average is: $average")

When you run this code, it will output:

The average is: 15.0

That's it! You have successfully calculated the average of a list of numbers in Kotlin.