Skip to main content

How to count the occurrences of an element in an array in Kotlin

How to count the occurrences of an element in an array in Kotlin.

Here's a step-by-step tutorial on how to count the occurrences of an element in an array using Kotlin.

Step 1: Create an Array

First, you need to create an array in Kotlin. You can create an array using the arrayOf() function, where you pass the elements of the array as arguments.

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

In this example, we have created an array called numbers with some random integers.

Step 2: Initialize a Counter

Next, you need to initialize a variable to keep track of the count of occurrences. In Kotlin, variables are declared using the var keyword.

var count = 0

Here, we have initialized a variable called count with an initial value of 0.

Step 3: Iterate Over the Array

Now, you need to loop through each element in the array and check if it matches the element you want to count. In Kotlin, you can use a for loop to iterate over the elements of an array.

for (number in numbers) {
if (number == 2) {
count++
}
}

In this example, we are looping through each number in the numbers array. If the number is equal to 2, we increment the count variable by 1.

Step 4: Print the Result

Finally, you can print the count of occurrences of the element. In Kotlin, you can use the println() function to print the result.

println("The count of occurrences is: $count")

Here, we are printing the count of occurrences using string interpolation.

Complete Example

Here's the complete example that counts the occurrences of an element in an array:

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

for (number in numbers) {
if (number == 2) {
count++
}
}

println("The count of occurrences is: $count")
}

When you run this code, it will output:

The count of occurrences is: 3

This means that the number 2 occurs 3 times in the numbers array.

That's it! You have successfully counted the occurrences of an element in an array using Kotlin. You can modify the code to count the occurrences of any other element by changing the value being compared in the if statement.