GO Program to find the transpose of a matrix

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to find the transpose of a matrix

 

The transpose of a matrix is found by interchanging its rows into columns or columns into rows. The transpose of the matrix is denoted by using the letter “T” in the superscript of the given matrix. For example, if “A” is the given matrix, then the transpose of the matrix is represented by A' or AT.

for example

matrix=

1 2 3            

4 5 6

7 8 9

Transpose= 

1 4 7

2 5 8

3 6 9

 

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