Skip to main content

How to find the first occurrence of an element in an array in Kotlin

How to find the first occurrence of an element in an array in Kotlin.

Here's a step-by-step tutorial on how to find the first occurrence of an element in an array using Kotlin:

Step 1: Declare and initialize an array

Start by declaring and initializing an array in Kotlin. You can use either the arrayOf function or the array constructor to create an array. For example:

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

Step 2: Define the element to search for

Next, define the element that you want to find the first occurrence of in the array. For example, let's say we want to find the first occurrence of the number 3 in the array.

val target = 3

Step 3: Use the indexOf() function

To find the first occurrence of the element in the array, you can use the indexOf() function. This function returns the index of the first occurrence of the specified element in the array, or -1 if the element is not found. For example:

val index = numbers.indexOf(target)

Step 4: Check if the element is found

After calling the indexOf() function, you can check if the element is found by comparing the returned index with -1. If the index is -1, it means that the element was not found in the array. Otherwise, it represents the index of the first occurrence of the element. For example:

if (index != -1) {
println("The first occurrence of $target is at index $index")
} else {
println("The element $target is not found in the array")
}

Step 5: Run the code

Finally, run the code to see the result. If the element is found in the array, it will print the index of the first occurrence. If the element is not found, it will print a message indicating that the element is not present in the array.

Here's the complete code example:

fun main() {
val numbers = arrayOf(1, 2, 3, 4, 5)
val target = 3

val index = numbers.indexOf(target)

if (index != -1) {
println("The first occurrence of $target is at index $index")
} else {
println("The element $target is not found in the array")
}
}

Output:

The first occurrence of 3 is at index 2

That's it! You have successfully found the first occurrence of an element in an array using Kotlin.