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:
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].Initialize two variables:
sumandcount. Setsumto 0 andcountto the number of elements in the list. In Kotlin, you can get the number of elements in a list using thesizeproperty. So, in our case,countwill be equal to5.
val numbers = listOf(5, 10, 15, 20, 25)
val count = numbers.size
var sum = 0
- Iterate over the list using a
forloop. Add each number to thesumvariable.
for (number in numbers) {
sum += number
}
- Calculate the average by dividing the
sumby thecount. To ensure that the average is a floating-point number, you can use thetoDouble()function.
val average: Double = sum.toDouble() / count
- 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.