Kotlin Program to reverse array elements


In this program, You will learn how to reverse array elements in Kotlin.


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

After reverse list is: 10 9 8 7 6 5 4 3 2 1

Example: How to reverse array elements in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    var i = 0
    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()
    }

    var j = arr.size - 1;
    while (i < j) {
        temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
        j--
        i++
    }

    print("After reverse list are:")
    for (n in arr) {
        print("$n ")
    }
}

Output:

Enter 5 numbers:10 20 30 40 50
After reverse list are:50 40 30 20 10