Skip to main content

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

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

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

Step 1: Create an ArrayList

First, we need to create an ArrayList and populate it with some elements. You can create an ArrayList and add elements to it using the ArrayList constructor or the add method. Here's an example:

val numbers = ArrayList<Int>()
numbers.add(1)
numbers.add(2)
numbers.add(3)
numbers.add(4)
numbers.add(5)

In this example, we created an ArrayList called numbers and added five elements to it (1, 2, 3, 4, and 5).

Step 2: Initialize a variable for the sum

Next, we need to initialize a variable to hold the sum of the elements in the ArrayList. You can create a variable and set its initial value to 0. Here's an example:

var sum = 0

In this example, we created a variable called sum and set its initial value to 0.

Step 3: Iterate through the ArrayList

To calculate the sum of the elements in the ArrayList, we need to iterate through each element and add it to the sum variable. There are multiple ways to iterate through an ArrayList in Kotlin, such as using a for loop or the forEach method. Here are examples of both approaches:

Using a for loop:

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

Using the forEach method:

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

In both examples, we iterate through each element in the numbers ArrayList and add it to the sum variable.

Step 4: Print the sum

Finally, we can print the sum of the elements in the ArrayList. You can use the println function to display the sum in the console. Here's an example:

println("The sum of the elements is: $sum")

In this example, we use the println function to display the sum of the elements in the numbers ArrayList.

Here's the complete code:

val numbers = ArrayList<Int>()
numbers.add(1)
numbers.add(2)
numbers.add(3)
numbers.add(4)
numbers.add(5)

var sum = 0

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

println("The sum of the elements is: $sum")

When you run this code, it will calculate the sum of the elements in the numbers ArrayList and display it in the console.