Skip to main content

How to find the minimum element in an array in Kotlin

How to find the minimum element in an array in Kotlin.

Here's a detailed step-by-step tutorial on how to find the minimum element in an array in Kotlin:

Step 1: Declare and initialize the array

Start by declaring and initializing an array with some elements. For example, let's create an array of integers:

val numbers = arrayOf(5, 2, 9, 1, 7)

Step 2: Initialize the minimum value

Create a variable to store the minimum value and initialize it with the first element of the array:

var min = numbers[0]

Step 3: Iterate through the array

Use a loop to iterate through the array and compare each element with the current minimum value. If an element is smaller than the current minimum, update the minimum value:

for (num in numbers) {
if (num < min) {
min = num
}
}

Step 4: Print the minimum value

After the loop ends, you will have the minimum element stored in the min variable. You can then print it:

println("The minimum element is: $min")

Here's the complete code:

val numbers = arrayOf(5, 2, 9, 1, 7)
var min = numbers[0]

for (num in numbers) {
if (num < min) {
min = num
}
}

println("The minimum element is: $min")

This will output:

The minimum element is: 1

Alternatively, you can use the min() function provided by Kotlin's standard library to find the minimum element in an array. Here's an example:

val numbers = arrayOf(5, 2, 9, 1, 7)
val min = numbers.min()

println("The minimum element is: $min")

This will also output:

The minimum element is: 1

Note that using the min() function is more concise and readable, but it may have a slight performance overhead compared to the manual loop method for larger arrays.

That's it! You've learned how to find the minimum element in an array using Kotlin.