Golang program to print the Transpose of a matrix

Here, we are going to learn how to print the Transpose of a matrix in Golang (Go Language)?
Submitted by Nidhi, on March 08, 2021 [Last updated : March 03, 2023]

Printing the Transpose of a matrix in Golang

Problem Solution:

In this program, we will read elements of the matrix from the user and then print the transpose of the matrix on the console screen.

Program/Source Code:

The source code to print the Transpose of the matrix is given below. The given program is compiled and executed successfully.

Golang code to print the Transpose of a matrix

// Golang program to print the Transpose of a matrix

package main

import "fmt"

func main() {
	var matrix [2][3]int

	fmt.Printf("Enter matrix elements: \n")
	for i := 0; i < 2; i++ {
		for j := 0; j < 3; j++ {
			fmt.Printf("Elements: matrix[%d][%d]: ", i, j)
			fmt.Scanf("%d", &matrix[i][j])
		}
	}

	fmt.Printf("Matrix: \n")
	for i := 0; i < 2; i++ {
		for j := 0; j < 3; j++ {
			fmt.Printf("%d ", matrix[i][j])
		}
		fmt.Printf("\n")
	}

	fmt.Printf("Transpose of Matrix: \n")
	for i := 0; i < 3; i++ {
		for j := 0; j < 2; j++ {
			fmt.Printf("%d ", matrix[j][i])
		}
		fmt.Printf("\n")
	}
}

Output:

Enter matrix elements:
Elements: matrix[0][0]: 10
Elements: matrix[0][1]: 20
Elements: matrix[0][2]: 30
Elements: matrix[1][0]: 40
Elements: matrix[1][1]: 50
Elements: matrix[1][2]: 60
Matrix:
10 20 30
40 50 60
Transpose of Matrix:
10 40
20 50
30 60

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created 2X3 matrix using a two-dimensional array.

fmt.Printf("Enter matrix elements: \n")
for i:=0;i<2;i++{
    for j:=0;j<3;j++{
        fmt.Printf("Elements: matrix[%d][%d]: ",i,j)
        fmt.Scanf("%d",&matrix[i][j])
    }
}

In the above code, we read matrix elements from the user.

fmt.Printf("Matrix: \n")
for i:=0;i<2;i++{
    for j:=0;j<3;j++{
        fmt.Printf("%d ",matrix[i][j])
    }
    fmt.Printf("\n")
}
    
fmt.Printf("Transpose of Matrix: \n")
for i:=0;i<3;i++{
    for j:=0;j<2;j++{
        fmt.Printf("%d ",matrix[j][i])
    }
    fmt.Printf("\n")
}

In the above code, we printed the matrix and its transpose on the console screen.

Golang Array Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.