Kotlin Program to insert an element in an array


In this program, You will learn how to insert an element in an array in Kotlin.


List is: 1 2 3 4 5 6

Insert item: 44

Insert location: 7

New list is: 1 2 3 4 5 6 44

Example: How to insert an element in an array in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    val arr = IntArray(100)
    var i: Int
    var n: Int
    var num: Int
    var loc: Int

    val sc = Scanner(System.`in`)

    print("Enter Size of an array:")
    n = sc.nextInt()

    print("Enter $n elements:")

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

    print("Enter element for insert:")
    num = sc.nextInt()

    print("Enter location : ")
    loc = sc.nextInt()

    i = n
    while (i >= loc) {
        arr[i] = arr[i - 1]
        i--
    }
    n++
    arr[loc - 1] = num

    print("New Array List are:")

    for (i in 0 until n)

        print("${arr[i]} ")
}

Output:

Enter Size of an array:5
Enter 5 elements:10 20 30 40 50
Enter element for insert:33
Enter location : 4
New Array List are:10 20 30 33 40 50