Transpose Matrix using For Loop in Kotlin

thumbnail

In this tutorial, you will learn to print the result of transpose from a given matrix in kotlin. Transpose of a matrix is process to swap the rwos to colums. If we have matrix with size 2×3, then the transpose will be 3×2.

We ill create one extra function to display or print the matrix, named displayMatrix().

Example: Program to Transpose Matrix in Kotlin using For Loop

fun main(args: Array<String>) {
    val row = 2
    val column = 3
    val matrix = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6))
    // Display current matrix
    displayMatrix (matrix)
    // Transpose the matrix
    val transpose = Array(column) { IntArray(row) }
    for (i in 0..row - 1) {
        for (j in 0..column - 1) {
            transpose[j][i] = matrix[i][j]
        }
    }
    // Display transposed matrix
    displayMatrix(transpose)
}

fun displayMatrix (matrix: Array) {
    println("The matrix is: ")
    for (row in matrix) {
        for (column in row) {
            print("$column    ")
        }
        println()
    }
}

The output will be:

The matrix is:
1    2    3    
4    5    6    
The matrix is:
1    4    
2    5    
3    6

Back To Top