How to insert an element at a specific index in an array with Kotlin

1 Answer

0 votes
fun insertElementAtIndex(arr: Array<Int>, element: Int, index: Int): Array<Int> {
    // Convert the array to a mutable list
    val mutableList = arr.toMutableList()
    
    // Insert the element at the specified index
    mutableList.add(index, element)
    
    // Convert the mutable list back to an array
    return mutableList.toTypedArray()
}

fun main() {
    val arr = arrayOf(4, 9, 8, 6, 5, 7)
    val elementToInsert = 100
    val index = 2
    
    val newArray = insertElementAtIndex(arr, elementToInsert, index)
    
    println(newArray.joinToString(", ")) 
}


   
/*
run:

4, 9, 100, 8, 6, 5, 7
 
*/

 



answered Feb 20, 2025 by avibootz

Related questions

...