w3resource

Anonymous Kotlin function: Find maximum element in array


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


Pre-Knowledge (Before You Start!)

Before solving this exercise, you should be familiar with the following concepts:

  • Arrays: An array is a collection of elements of the same type. In this case, we are working with an array of integers.
  • Anonymous Functions: An anonymous function is a function that is defined without being given a name. It is used when you want to define a function at the point where it is used.
  • Iteration: You should understand how to loop through an array using a for loop to process each element.
  • Comparing Values: To find the maximum value in an array, you need to compare each element with the current maximum and update the maximum when a larger value is found.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Use an anonymous function that takes an array as a parameter and returns an integer.
  • Hint 2: Initialize a variable to store the maximum value and set it to Int.MIN_VALUE to ensure that any value from the array will be larger.
  • Hint 3: Loop through each element of the array and compare it with the current maximum. If an element is larger, update the maximum value.
  • Hint 4: After the loop ends, return the maximum value found.

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.