Kotlin example program to find out the largest element in an array :

In this Kotlin example program, we will learn how to find out the largest element in an array of numbers. This is a simple example program that will show you how to find out the largest number in an array. Let’s take a look at the program :

Kotlin Program :

fun main(args: Array) {
    val numberArray: IntArray = intArrayOf(10, 20, 30, 40, 50)

    var largestElement = numberArray[0]

    for (n in numberArray) {
        if (largestElement < n)
            largestElement = n

    println("The largest element in the array is %d".format(largestElement))

Output :

The largest element in the array is 50

Explanation :

The commented numbers in the above program denote the step number below :

1. Create one array of integers with few integer numbers.
2. Create one variable and assign the first element of the array to this number. We will compare this number to all other numbers of the array and find out the largest one.
3. Run one for loop and run each element of the array one by one.
4. Check if the current element is greater than the current largest element or not. If yes, set this value as the largest element.
5. After the loop is completed, print the largest element of the array.

kotlin find largest element in array

You might also like :

Categories: kotlin

1 Comment

Guang · November 12, 2018 at 1:26 pm

thank you, very hard to look for kotlin examples on the net

Leave a Reply

Your email address will not be published. Required fields are marked *