Kotlin Program to find the second largest element in the array


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


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

Second largest element: 10

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

import java.util.Scanner

fun main(args: Array<String>) {

    var temp: Int
    val arr = IntArray(5)

    val sc = Scanner(System.`in`)
    print("Enter 5 numbers:")

    for (i in 0 until arr.size) {
        arr[i] = sc.nextInt()
    }

    for (i in 0 until arr.size) {
        for (j in i + 1 until arr.size) {
            if (arr[i] > arr[j]) {
                temp = arr[i]
                arr[i] = arr[j]
                arr[j] = temp
            }
        }
    }

    println("Second largest element:${arr[arr.size - 2]}")
}

Output:

Enter 5 numbers:2 3 4 5 6
Second largest element:5