GO Program to find the transpose of a matrix

How to find the transpose of a matrix

Here we are explaining how to find the transpose of a matrix in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

for initialization; condition; post{
       // statements....
} 

The initialization statement is executed before for loop starts and it is optional. The condition statement has a boolean expression. The post statement is executed after the body of the for-loop.

 

How to find the transpose of a matrix in GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to find the transpose of a matrix in the Go language. Here variable mat,TMat are used to hold the matrix elements and iteration elements i,j. Read the number of rows and columns for reading matrix elements into the variables row, col. After reading elements find the transpose of a matrix elements using two nested for loops as TMat[j][i] = mat[i][j]. Finally, print the result matrix TMat. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the matrix variables mat,TMat and iteration variables i,j

STEP 4: Read the number of rows and columns into row, col

STEP 5: Read the matrix for finding the transpose

STEP 6: Find the transpose of matrices using two nested for loops as TMat[j][i] = mat[i][j]

STEP 7: Print the transpose matrix using fmt.print()

 

GO Source Code

                                          package main

import "fmt"

func main() {
    var i, j, row, col int

    var mat [10][10]int
    var TMat [10][10]int

     fmt.Print("Enter the number of rows and columns = ")
     fmt.Scan(&row;, &col;)

    fmt.Println("Enter the matrix items = ")
    for i = 0; i < row; i++ {
        for j = 0; j < col; j++ {
            fmt.Scan(&mat;[i][j])
        }
    }
    for i = 0; i < row; i++ {
        for j = 0; j < col; j++ {
            TMat[j][i] = mat[i][j]
        }
    }
    fmt.Println("*** The Transpose Matrix ***")
    for i = 0; i < col; i++ {
        for j = 0; j < row; j++ {
            fmt.Print(TMat[i][j], "  ")
        }
        fmt.Println()
    }
}
                                      

OUTPUT

Enter the number of rows and columns = 2 3
Enter the matrix items =
1  2  3
4  5  6
*** The Transpose Matrix ***
1  4
2  5
3  6