Calculate sum of all elements in an array in Kotlin
This post will discuss how to calculate the sum of all elements in an array in Kotlin.
1. Using sum() function
You can easily get the sum of all elements in the array using the sum() function. It is available for arrays of Int, Double, Float, Long, Short, Byte.
|
1 2 3 4 5 6 |
fun main() { val nums: IntArray = intArrayOf(2, 4, 9, 3, 7) val sum = nums.sum() println("The sum is $sum") // The sum is 25 } |
The following code example demonstrates the usage of the sum() function for a “typed” array.
|
1 2 3 4 5 6 |
fun main() { val nums: Array<Int> = arrayOf(2, 4, 9, 3, 7) val sum = nums.sum() println("The sum is $sum") // The sum is 25 } |
Another alternative is to use reduction to perform the addition, as shown below:
|
1 2 3 4 5 6 7 |
fun main() { val nums = intArrayOf(2, 4, 9, 3, 7) val sum = nums.reduce { x, y -> x + y } println("The sum is $sum") // The sum is 25 } |
2. Using SummaryStatistics
If you don’t mind using the Java Stream API, you can get the sum of all array elements using the summaryStatistics() function. You can also use it to get other stats like min, max, count, and average. A typical invocation for this function would look like:
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays fun main() { val nums = intArrayOf(2, 4, 9, 3, 7) val sum = Arrays.stream(nums).summaryStatistics().sum println("The sum is $sum") // The sum is 25 } |
The following example demonstrates its usage for a “typed” array.
|
1 2 3 4 5 6 7 8 9 |
import java.util.Arrays fun main() { val nums: Array<Int> = arrayOf(2, 4, 9, 3, 7) val sum = Arrays.stream(nums).mapToInt { it }.summaryStatistics().sum println("The sum is $sum") // The sum is 25 } |
Finally, you can always iterate over the array using the for loop and accumulate the sum of all elements. That’s all about calculating the sum of all elements in an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)