Task

Build an   identity matrix   of a size known at run-time.



An identity matrix is a square matrix of size n × n,

where the diagonal elements are all 1s (ones),

and all the other elements are all 0s (zeroes).







I

n


=


[



1


0


0


⋯


0




0


1


0


⋯


0




0


0


1


⋯


0




⋮


⋮


⋮


⋱


⋮




0


0


0


⋯


1



]




{\displaystyle I_{n}={\begin{bmatrix}1&0&0&\cdots &0\\0&1&0&\cdots &0\\0&0&1&\cdots &0\\\vdots &\vdots &\vdots &\ddots &\vdots \\0&0&0&\cdots &1\\\end{bmatrix}}}





Related tasks

   Spiral matrix
   Zig-zag matrix 
   Ulam_spiral_(for_primes)


// version 1.0.6
 
fun main(args: Array<String>) {
    print("Enter size of matrix : ")
    val n = readLine()!!.toInt()
    println()
    val identity = Array(n) { IntArray(n) } // create n x n matrix of integers
 
    // enter 1s in diagonal elements
    for(i in 0 until n) identity[i][i] = 1
 
    // print identity matrix if n <= 40
    if (n <= 40) 
        for (i in 0 until n) println(identity[i].joinToString(" "))
    else 
        println("Matrix is too big to display on 80 column console")
}