Write a Kotlin Program to Find Transpose of a Matrix

In Kotlin, a matrix is a two-dimensional array.

The transpose of a matrix is a new matrix formed by exchanging the rows and columns of the original matrix.

In other words, if A is a matrix of size m x n, then the transpose of A is a matrix of size n x m, in which the element in the i-th row and j-th column is the same as the element in the j-th row and i-th column of A.

To find the transpose of a matrix in Kotlin, we can use a nested loop to swap the rows and columns.

Here is a Kotlin program that finds the transpose of a matrix:

fun main(args: Array<String>) {
    val matrix = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(4, 5, 6),
        intArrayOf(7, 8, 9),
    )
    val rows = matrix.size
    val cols = matrix[0].size
    val transpose = Array(cols) { IntArray(rows) }

    for (i in 0 until rows) {
        for (j in 0 until cols) {
            transpose[j][i] = matrix[i][j]
        }
    }

    println("Original Matrix:")
    for (row in matrix) {
        println(row.joinToString())
    }

    println("Transpose Matrix:")
    for (row in transpose) {
        println(row.joinToString())
    }
}

In this program, we first define a matrix as a two-dimensional array of integers.

We then calculate the number of rows and columns in the matrix using the size property of the first row.

We create a new array called transpose to store the transpose of the matrix.

The size of transpose is cols x rows, where cols is the number of columns in the original matrix and rows is the number of rows.

We then use nested loops to iterate through the elements of the original matrix and copy them to the transpose matrix, swapping the rows and columns.

Finally, we print both the original and transpose matrices to the console.

We can run this program and see the following output:

Original Matrix:
1, 2, 3
4, 5, 6
7, 8, 9
Transpose Matrix:
1, 4, 7
2, 5, 8
3, 6, 9

This program demonstrates how to find the transpose of a matrix in Kotlin using nested loops and a new two-dimensional array.

The transpose of a matrix can be useful in a variety of applications, such as linear algebra and image processing.