C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Kotlin

Program to implement an array in Kotlin

Here, we are implementing an array program in Kotlin. Here, we are declaring and initializing arrays with different methods.
Submitted by Aman Gautam, on December 02, 2017

Prerequisite: Arrays in Kotlin

This program will demonstrate how we can declare and initialize an array using different methods?

package includeHelp

fun main(args: Array<String>) {
    var arr=arrayOf(5,3,4,5)

    println("Using ArrayOf() ")
    for(a in arr)
        print(" $a")

    var arr1= arrayOfNulls<Int>(5)
    println("\nUsing ArrayOfNuls() ")
    for(a in arr1)
        print(" $a")

    var arr2= intArrayOf(5,3,4,5)
    println("\nUsing intArrayOf() ")
    for(a in arr2)
        print(" $a")

    var arr3= doubleArrayOf(5.3,3.2,4.3,5.4)
    println("\nUsing doubleArrayOf() ")
    for(a in arr3)
        print(" $a")

    var arr4= Array<Int>(5,{0})
    println("\n Using Array() initialize with 0 ")
    for(a in arr4)
        print(" $a")


    var arr5= Array<Int>(5,{it*it})
    println("\nUsing Array() with index square")
    for(a in arr5)
        print(" $a")

    var arr6= IntArray(5,{it*it})
    println("\nUsing IntArray() with index square ")
    for(a in arr6)
        print(" $a")

}

Output

Using ArrayOf() 
 5 3 4 5
Using ArrayOfNuls() 
 null nullnullnullnull
Using intArrayOf() 
 5 3 4 5
Using doubleArrayOf() 
 5.3 3.2 4.3 5.4
 Using Array() initialize with 0 
 0 0 0 0 0
Using Array() with index square
 0 1 4 9 16
Using IntArray() with index square 
 0 1 4 9 16








COMMENTS