w3resource

Anonymous Kotlin function: Find maximum element in array

Kotlin Lambda: Exercise-10 with Solution

Write an anonymous Kotlin function to find the maximum element in an array.

Sample Solution:

Kotlin Code:

fun main() {
    val numbers = arrayOf(5, 7, 8, 3, 2, 4, 12, 6)

    val maxNumber: (Array<Int>) -> Int = fun(array: Array<Int>): Int {
        var max = Int.MIN_VALUE
        for (number in array) {
            if (number > max) {
                max = number
            }
        }
        return max
    }

    val maximum = maxNumber(numbers)
    println("The maximum number is: $maximum")
}

Sample Output:

The maximum number is: 12

Explanation:

In the above exercise -

  • We define an anonymous function maxNumber with the type (Array<Int>) -> Int. The function takes an array of integers as an argument and returns the maximum element. The function implementation iterates through the array and keeps track of the maximum value encountered.
  • The function is assigned to the variable maxNumber, and we can call it like any other function. In the example, we pass the numbers array to the maxNumber function and store the result in the max variable. Finally, we print the maximum number using println.

Kotlin Editor:


Previous: Calculate a factorial.
Next: Count vowels in a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.