Kotlin program to find sum and average of array elements

Kotlin | Sum and Average of array elements: Here, we are going to learn how to find the sum and average of all array elements which a double type in Kotlin programming language? Submitted by IncludeHelp, on May 05, 2020

Kotlin - Find sum and average of array elements

Given a double type array, we have to find sum and average of its all elements.

Example:

Input:
arr = [4.0, 56.0, 7.0, 8.0, 43.0, 2.0, 3.0]

Output:
sum = 123.0
average = 17.571428571428573

Program to find sum and average of array elements in Kotlin

package com.includehelp import java.util.* //Main Function entry Point of Program fun main(args: Array<String>) { //Input Stream val s = Scanner(System.`in`) //Input Array Size print("Enter number of elements in the array: ") val size = s.nextInt() //Create Double array of Given size val doubleArray = DoubleArray(size) //Input array elements println("Enter Arrays Elements:") for (i in doubleArray.indices) { print("doubleArray[$i] : ") doubleArray[i] = s.nextDouble() } //declare variable for sum of elements var sum: Double=0.toDouble() for (i in doubleArray.indices) { //add array element in sum sum+=doubleArray[i] } //Avg of elements var avg=sum/doubleArray.size //Alternatively we can also use sum() and average() method of Arrays Class in //var sum = doubleArray.sum() //var avg = doubleArray.average() println("Array : ${doubleArray.contentToString()} ") println("Sum of Elements : $sum") println("Average of Elements : $avg") }

Output

Run 1:
-----
Enter number of elements in the array: 7
Enter Arrays Elements:
doubleArray[0] : 4
doubleArray[1] : 56
doubleArray[2] : 7
doubleArray[3] : 8
doubleArray[4] : 43
doubleArray[5] : 2
doubleArray[6] : 3
Array : [4.0, 56.0, 7.0, 8.0, 43.0, 2.0, 3.0]
Sum of Elements : 123.0
Average of Elements : 17.571428571428573
--------
Run 2:
----
Enter number of elements in the array: 6
Enter Arrays Elements:
doubleArray[0] : 45.32
doubleArray[1] : 5.7
doubleArray[2] : 9.21
doubleArray[3] : 9.6
doubleArray[4] : 34.98
doubleArray[5] : 6.54
Array : [45.32, 5.7, 9.21, 9.6, 34.98, 6.54]
Sum of Elements : 111.35000000000001
Average of Elements : 18.558333333333334
Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.