Here is an example of a Go program that transposes a matrix:
package main
import (
"fmt"
)
func main() { var n, m int
fmt.Print("Enter the number of rows: ")
fmt.Scan(&n)
fmt.Print("Enter the number of columns: ")
fmt.Scan(&m)
// Creating a matrix of size n x m
matrix := make([][]int, n)
for i := range matrix {
matrix[i] = make([]int, m)
}
// Populating the matrix
fmt.Println("Enter the elements of the matrix:")
for i := range matrix {
for j := range matrix[i] {
fmt.Scan(&matrix[i][j])
}
}
// Transposing the matrix
transposedMatrix := make([][]int, m)
for i := range transposedMatrix {
transposedMatrix[i] = make([]int, n)
}
for i := range matrix {
for j := range matrix[i] {
transposedMatrix[j][i] = matrix[i][j]
}
}
// Printing the transposed matrix
fmt.Println("Transposed matrix:")
for i := range transposedMatrix {
for j := range transposedMatrix[i] {
fmt.Printf("%d ", transposedMatrix[i][j])
}
fmt.Println()
}
}
The program starts by prompting the user to enter the number of rows and columns of the matrix. Then it creates a matrix of size n x m
and populates it with the elements entered by the user.
Then it creates a new matrix transposedMatrix
of size m x n
and populates it with the transposed elements of the original matrix.
Finally, it prints the transposed matrix.
Note that this program uses the make
function to create the matrices, which is the idiomatic way to create a 2D slice in Go.
As a reminder, Transpose of a matrix is a new matrix whose rows are the columns of the original matrix and columns are the rows of the original matrix.