Skip to main content

How to find the sum of elements in an array in Kotlin

How to find the sum of elements in an array in Kotlin.

Here's a step-by-step tutorial on how to find the sum of elements in an array in Kotlin.

Step 1: Declare an array

First, you need to declare an array in Kotlin. You can declare an array using the arrayOf() function or the IntArray constructor. For example, let's declare an array of numbers:

val numbers = arrayOf(1, 2, 3, 4, 5)

Step 2: Initialize a variable to store the sum

Next, you need to initialize a variable to store the sum of the elements in the array. Let's name it sum and set its initial value to 0:

var sum = 0

Step 3: Iterate through the array

To calculate the sum of the elements in the array, you need to iterate through each element in the array. There are several ways to iterate through an array in Kotlin, such as using a for loop or the forEach function.

Using a for loop:

for (number in numbers) {
sum += number
}

Using the forEach function:

numbers.forEach { number ->
sum += number
}

Step 4: Print the sum

Finally, you can print the sum of the elements in the array to verify the result. You can use the println() function to output the sum to the console:

println("The sum is: $sum")

Putting it all together, here's the complete code:

fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
var sum = 0

for (number in numbers) {
sum += number
}

println("The sum is: $sum")
}

When you run this code, it will output the sum of the elements in the array:

The sum is: 15

That's it! You've successfully found the sum of elements in an array using Kotlin.