In this Go Program to Add Two Matrices, we used two nested for loops. The first for loop will add the two matrices and assign them to the addition matrix. The second nested for loop ((for i = 0; i < rows; i++ { for j = 0; j < columns; j++)) prints the addition matrix items.
package main
import "fmt"
func main() {
var rows, columns, i, j int
var addmat1 [10][10]int
var addmat2 [10][10]int
var additionmat [10][10]int
fmt.Print("Enter the Addition Matrix Rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Print("Enter the First Matrix Items to Add = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&addmat1[i][j])
}
}
fmt.Print("Enter the Second Matrix Items to Add = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&addmat2[i][j])
}
}
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
additionmat[i][j] = addmat1[i][j] + addmat2[i][j]
}
}
fmt.Println("The Sum of Two Matrices = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Print(additionmat[i][j], "\t")
}
fmt.Println()
}
}
Enter the Addition Matrix Rows and Columns = 2 2
Enter the First Matrix Items to Add =
10 20
30 40
Enter the Second Matrix Items to Add =
3 9
14 22
The Sum of Two Matrices =
13 29
44 62
Golang Program to Add Two Matrices Example
In this example, we used the nested for loop range to assign values to addmat1 and addmat2. Next, we used another nested for loop range to perform matrix addition and print the same.
package main
import "fmt"
func main() {
var addmat1 [2][3]int
var addmat2 [2][3]int
var additionmat [2][3]int
fmt.Print("Enter the First Matrix Items to Add = ")
for k, r := range addmat1 {
for l := range r {
fmt.Scan(&addmat1[k][l])
}
}
fmt.Print("Enter the Second Matrix Items to Add = ")
for k, r := range addmat2 {
for l := range r {
fmt.Scan(&addmat2[k][l])
}
}
fmt.Println("*** The Sum of Two Matrices ****")
for i, row := range additionmat {
for j := range row {
additionmat[i][j] = addmat1[i][j] + addmat2[i][j]
fmt.Print(additionmat[i][j], "\t")
}
fmt.Println()
}
}
