GO Program to add two matrices

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

A matrix can only be added to (or subtracted from) another matrix if the two matrices have the same dimensions . To add two matrices, just add the corresponding entries, and place this sum in the corresponding position in the matrix which results.

How to add two matrices in GO Program

Here we are showing how to add two matrices in the Go language. Here variable mat1, mat2, sum is 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 add the matrix elements using two `nested for loops`.  Finally, print the result matrix sum. 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 mat1, mat2, sum, and iteration variables i,j

STEP 4: Read the number of rows and columns into row, col

STEP 5: Read the two matrices for finding the sum

STEP 6: Find the sum of matrices using two nested `for loops`

STEP 7: Print the sum matrix using `fmt.print()`

GO Source Code

```                                          ```package main

import "fmt"

func main() {
var row, col, i, j int

var mat1 [10][10]int
var mat2 [10][10]int
var sum [10][10]int

fmt.Print("Enter the number of rows and columns = ")
fmt.Scan(&row;, &col;)

fmt.Print("Enter the first matrix= ")
for i = 0; i < row; i++ {
for j = 0; j < col; j++ {
fmt.Scan(&mat1;[i][j])
}
}

fmt.Print("Enter the second matrix = ")
for i = 0; i < row; i++ {
for j = 0; j < col; j++ {
fmt.Scan(&mat2;[i][j])
}
}

for i = 0; i < row; i++ {
for j = 0; j < col; j++ {
sum[i][j] = mat1[i][j] + mat2[i][j]
}
}
fmt.Println("The sum of two matrices = ")
for i = 0; i < row; i++ {
for j = 0; j < col; j++ {
fmt.Print(sum[i][j], "\t")
}
fmt.Println()
}
}```
```

OUTPUT

```Enter the number of rows and columns = 2 2
Enter the first matrix=
15 14
10 20
Enter the second matrix =
5 12
13 7
The sum of two matrices =
20 26
23 27
```
VIEW ALL
VIEW ALL
VIEW ALL