Go Program to Transpose a Matrix

Write a Go program to transpose a matrix, converting rows to columns and columns to rows. In this Go example, we used the first nested for loop to convert rows to columns (transposeMat[j][i] = orgMat[i][j]) and vice versa. The next loop prints the elements in that transposed matrix.

package main

import "fmt"

func main() {
    var i, j, rows, columns int

    var orgMat [10][10]int
    var transposeMat [10][10]int

    fmt.Print("Enter the Matrix rows and Columns = ")
    fmt.Scan(&rows, &columns)

    fmt.Println("Enter Matrix Items to Transpose = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&orgMat[i][j])
        }
    }
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            transposeMat[j][i] = orgMat[i][j]
        }
    }
    fmt.Println("*** The Transpose Matrix Items are ***")
    for i = 0; i < columns; i++ {
        for j = 0; j < rows; j++ {
            fmt.Print(transposeMat[i][j], "  ")
        }
        fmt.Println()
    }
}
Enter the Matrix rows and Columns = 2 3
Enter Matrix Items to Transpose = 
1 2 3
4 8 7
*** The Transpose Matrix Items are ***
1  4  
2  8  
3  7  

Golang Program to Transpose a Matrix using For loop range.

package main

import "fmt"

func main() {

    var orgMat [3][3]int
    var transposeMat [3][3]int

    fmt.Println("Enter Matrix Items to Transpose = ")
    for i, rows := range orgMat {
        for j := range rows {
            fmt.Scan(&orgMat[i][j])
        }
    }
    for i, rows := range orgMat {
        for j := range rows {
            transposeMat[j][i] = orgMat[i][j]
        }
    }
    fmt.Println("*** The Transpose Matrix Items are ***")
    for i, rows := range orgMat {
        for j := range rows {
            fmt.Print(transposeMat[i][j], "  ")
        }
        fmt.Println()
    }
}
Go Program to Transpose a Matrix 2