Write a Kotlin Program to Check if An Array Contains a Given Value

As a Kotlin programmer, you may often need to check if an array contains a certain value.

In this Kotlin tutorial, we will discuss how to do that using Kotlin programming language.

To check if an array contains a given value, we can use the in operator in Kotlin.

This operator checks if the specified value is present in the given array or not. Here is the code snippet to do so:

val array = arrayOf(1, 2, 3, 4, 5)
val value = 3

if (value in array) {
println("The array contains $value")
} else {
println("The array does not contain $value")
}

In the above code snippet, we have defined an array of integers and a variable to store the value we want to check.

We then use the in operator to check if the value is present in the array or not.

If the value is present in the array, the first condition will be executed and it will print “The array contains 3”.

If the value is not present in the array, the second condition will be executed and it will print “The array does not contain 3”.

We can also use the contains() function to check if an array contains a given value. Here is the code snippet to do so:

val array = arrayOf(1, 2, 3, 4, 5)
val value = 3

if (array.contains(value)) {
println("The array contains $value")
} else {
println("The array does not contain $value")
}

In the above code snippet, we have used the contains() function to check if the value is present in the array or not.

If the value is present in the array, the first condition will be executed and it will print “The array contains 3”.

If the value is not present in the array, the second condition will be executed and it will print “The array does not contain 3”.

In conclusion, Kotlin provides an easy way to check if an array contains a given value.

We can use the in operator or the contains() function to check if the value is present in the array or not.

By using these simple methods, we can easily check if an array contains a given value in our Kotlin programs.