Write a Kotlin Program to Find Largest Element in an Array

In Kotlin, finding the largest element in an array is a straightforward process.

In this tutorial, we will discuss a simple program that can be used to find the largest element in an array.

First, we need to declare an array of integers. For the purpose of this example, we will use an array of size 5.

You can modify the size of the array to suit your needs.

val arr = arrayOf(10, 20, 30, 40, 50)

Next, we will initialize a variable max to the first element in the array. We will then loop through the array and compare each element to max.

If the current element is greater than max, we will update the value of max to be the current element.

var max = arr[0]

for (i in 1 until arr.size) {
    if (arr[i] > max) {
        max = arr[i]
    }
}

println("Largest element in the array is: $max")

The for loop iterates through the array from index 1 to arr.size – 1. The until keyword is used to exclude the last index of the array.

The if statement checks if the current element is greater than max. If it is, the value of max is updated to the current element.

Finally, we print the value of max using the println() function.

Here is the complete program:

fun main() {
    val arr = arrayOf(10, 20, 30, 40, 50)
    var max = arr[0]

    for (i in 1 until arr.size) {
        if (arr[i] > max) {
            max = arr[i]
        }
    }

    println("Largest element in the array is: $max")
}

When you run this program, the output should be:

Largest element in the array is: 50

In conclusion, finding the largest element in an array in Kotlin is a simple process.

By initializing a variable to the first element in the array and looping through the array to compare each element to the variable, we can easily find the largest element in an array.