How can sum the elements in array in kotlin language?
package sum
fun sum(a: IntArray): Int {
return 0
}
There's a built in function to sum an IntArray in Kotlin
val numbers: IntArray = intArrayOf(10, 20, 30, 40, 50)
val sum = numbers.sum()
Or to do it yourself...
fun sumArray(array: IntArray): Int{
var sum = 0
for(number in array){
sum += number
}
return sum
}
You can use sum
directly:
val sum = arrayOf(12, 33).sum()
You could do it as a stream
val sum = arrayOf(7, 9).fold(0) { acc, e -> acc + e }