Kotlin Program to Calculate Average Using Arrays

In this program, we will learn to code the Kotlin Program to Calculate Average Using Arrays. Let’s understand How to calculate average using arrays in Kotlin Programming Language.

We will need to first understand the concept of Arrays in Kotlin and we declare Arrays in Kotlin Programming Language.

Arrays in Kotlin

Arrays in Kotlin Programming Language are a collection of homogenous data. In Kotlin there are ByteArray, IntArray , DoubleArray Classes that represent primitive datatype arrays.

Kotlin Program to Calculate Average Using Arrays

// Kotlin Program to Calculate Average Using Arrays
    
  fun main(args: Array<String>) {
    val numArray = intArrayOf(11,51,7,18,101)
    var sum = 0.0

    for (num in numArray) {
        sum += num
    }

    val average = sum / numArray.size
    println("The average is: %.2f".format(average))
}

    

Output

The average is: 37.60

How Does This Program Work ?

val numArray = intArrayOf(11,51,7,18,101)

In this program, we have declared an Integer array using the IntArray Class and the method intArrayOf() is used to initialize values of an array.

    var sum = 0.0

    for (num in numArray) {
        sum += num
    }

Then, we have declared a variable sum to calculate the sum of the values of the array. Using the For Loop we have find the sum of the the values of array.

    val average = sum / numArray.size

Then, we calculated the average using arrays in Kotlin Programming Language.

    println("The average is: %.2f".format(average))

At last, we display the result using the println() method in Kotlin. Here, the value of the sum is double so we have used the “%.2f” specifier which will allow printing the double value only to 2 decimal places.
This is the Kotlin Program to Calculate Average Using Arrays.

Conclusion

I hope after going through this post, you understand Kotlin Program to Calculate Average Using Arrays.
If you have any doubt regarding the topic, feel free to contact us in the Comment Section. We will be delighted to help you.

Learn More:

Leave a Comment

Your email address will not be published. Required fields are marked *