Kotlin Program to swap adjacent elements of an array


In this program, You will learn how to swap adjacent elements of an array in Kotlin.


List is: 1 2 3 4 5 6

After swap: 2 1 4 3 6 5

Example: How to swap adjacent elements of an array in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    val arr = IntArray(6)
    var i = 0
    var t: Int
    val sc = Scanner(System.`in`)

    print("Enter 6 elements:")

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

    while (i < arr.size - 1) {
        t = arr[i]
        arr[i] = arr[i + 1]
        arr[i + 1] = t
        i += 2;
    }

    print("Array list after swapping:")

    for (n in arr) {
        print("$n ")
    }
}

Output:

Enter 6 elements:10 20 30 40 50 60
Array list after swapping:20 10 40 30 60 50