Reputation: 121
package sum
fun sum(a: IntArray): Int {
return 0
}
Upvotes: 5
Views: 17285
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
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
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
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
Reputation: 17827
You could do it as a stream
val sum = arrayOf(7, 9).fold(0) { acc, e -> acc + e }
Upvotes: 4