In this Go matrix multiplication program, we used two for loops. The first for loop performs the matrix multiplication and assigns the values to the multiplication matrix. The second for loop prints the items in that matrix.
package main
import "fmt"
func main() {
var rows, columns, i, j int
var multimat1 [10][10]int
var multimat2 [10][10]int
var multiplicationnmat [10][10]int
fmt.Print("Enter the Multiplication Matrix Rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Print("Enter the First Matrix Items to Multiplication = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&multimat1[i][j])
}
}
fmt.Print("Enter the Second Matrix Items to Multiplication = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&multimat2[i][j])
}
}
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
multiplicationnmat[i][j] = multimat1[i][j] * multimat2[i][j]
}
}
fmt.Println("The Go Result of Matrix Multiplication = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Print(multiplicationnmat[i][j], "\t")
}
fmt.Println()
}
}
Enter the Multiplication Matrix Rows and Columns = 2 2
Enter the First Matrix Items to Multiplication =
10 20
30 40
Enter the Second Matrix Items to Multiplication =
3 4
5 6
The Go Result of Matrix Multiplication =
30 80
150 240
Go Program to Multiply Two Matrices Example
In this example, we used the for loop range to assign values to multimat1 and multimat2. Next, we used another one to perform matrix multiplication and print the same. You can also use another for loop to print the matrix items.
package main
import "fmt"
func main() {
var multimat1 [2][3]int
var multimat2 [2][3]int
var multiplicationnmat [2][3]int
fmt.Print("Enter the First Matrix Items to Multiplication = ")
for k, r := range multimat1 {
for l := range r {
fmt.Scan(&multimat1[k][l])
}
}
fmt.Print("Enter the Second Matrix Items to Multiplication = ")
for m, rr := range multimat2 {
for n := range rr {
fmt.Scan(&multimat2[m][n])
}
}
fmt.Println("The Go Result of Matrix Multiplication = ")
for i, row := range multiplicationnmat {
for j := range row {
multiplicationnmat[i][j] = multimat1[i][j] * multimat2[i][j]
fmt.Print(multiplicationnmat[i][j], "\t")
}
fmt.Println()
}
}
