AbdElrahman Usama
AbdElrahman Usama

Reputation: 121

How can sum the elements in array in kotlin language?

package sum

fun sum(a: IntArray): Int {
  return 0
}

Upvotes: 5

Views: 17285

Answers (7)

TCest
TCest

Reputation: 1

It works like this:

fun main() {
    val myArray = arrayOf(6, 5, 8, 2, 11, 25)
    var sum = 0
    for (number in myArray) {
        sum += number
    }
    println(sum)
}

Upvotes: 0

lenooh
lenooh

Reputation: 10682

You can also use fold. The advantage is more freedom with data handling.

For example, if you have nested arrays, and want the sum of the nested array sizes, you can do something like this:

val totalSize = array1.fold(0) { acc, i -> acc + i.array2.size }

In case of array with just integers:

val sum = array.fold(0) { acc, i -> acc + i }

Upvotes: 0

Andres Ausecha
Andres Ausecha

Reputation: 21

This is the solution I prefer

array.reduce { acc, l -> acc + l }

If you've got an object instead of a primary data for example, you can access it and sumup

Upvotes: 2

Iker Solozabal
Iker Solozabal

Reputation: 1402

fun sum(numbers: IntArray) = numbers.sum()

Upvotes: 0

Christopher
Christopher

Reputation: 186

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
}

Upvotes: 16

Drew Stephens
Drew Stephens

Reputation: 17827

You could do it as a stream

val sum = arrayOf(7, 9).fold(0) { acc, e -> acc + e }

Upvotes: 4

s1m0nw1
s1m0nw1

Reputation: 81939

You can use sum directly:

val sum = arrayOf(12, 33).sum()

Upvotes: 5

Related Questions