Kotlin Program to find the largest and smallest element in the array


In this program, You will learn how to find the largest and smallest element in the array in Kotlin.


List is: 3 4 5 6 7 8 9 10 11 12

Largest & smallest element is: 12 3

Example: How to find the largest and smallest element in the array in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    var lg = 0
    var sm = 0

    val arr = IntArray(5)
    val sc = Scanner(System.`in`)

    print("Enter 5 numbers:")
    for (i in 0 until arr.size) {
        arr[i] = sc.nextInt()
    }

    lg=arr[0]
    sm=arr[0]

    for (n in arr) {
        if (lg < n) {
            lg = n
        }
        if (sm > n) {
            sm = n
        }
    }

    println("Largest element:$lg")
    println("Smallest element:$sm")
}

Output:

Enter 5 numbers:3 4 2 6 5
Largest element:6
Smallest element:2