Skip to main content

How to find the average of elements in an array in Kotlin

How to find the average of elements in an array in Kotlin.

Here's a step-by-step tutorial on how to find the average of elements in an array using Kotlin:

Step 1: Initialize the array

Start by initializing an array with a set of numbers. For example, let's consider an array of integers:

val numbers = arrayOf(5, 10, 15, 20, 25)

Step 2: Calculate the sum of elements

Create a variable to store the sum of all the elements in the array. Iterate through each element of the array and add it to the sum. Here's an example of how you can do this:

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

Step 3: Calculate the average

Next, calculate the average by dividing the sum by the total number of elements in the array. To get the total number of elements, you can use the size property of the array. Here's how you can calculate the average:

val average = sum / numbers.size.toDouble()

Note that we use toDouble() to ensure that the division is done with floating-point precision, as the result may not always be an integer.

Step 4: Display the average

Finally, you can display the average to the user. You can do this by printing it to the console:

println("The average is: $average")

Complete Example

Here's the complete example that puts all the steps together:

fun main() {
val numbers = arrayOf(5, 10, 15, 20, 25)

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

val average = sum / numbers.size.toDouble()

println("The average is: $average")
}

When you run this code, it will output:

The average is: 15.0

This means that the average of the numbers in the array is 15.0.

Handling an Empty Array

If there is a possibility that the array may be empty, you should handle this case to avoid division by zero. In such cases, you can check if the array is empty before calculating the average. Here's an example:

if (numbers.isEmpty()) {
println("The array is empty.")
} else {
// Calculate the average
}

This way, you can display an appropriate message to the user if the array is empty.

That's it! You now know how to find the average of elements in an array using Kotlin.