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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.