GO Program to add two matrices

How to add two matrices

Here we are explaining how to add two matrices in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

for initialization; condition; post{
       // statements....
} 

The initialization statement is executed before for loop starts and it is optional. The condition statement has a boolean expression. The post statement is executed after the body of the for-loop.

 

How to add two matrices in GO Program

We are using fmt.println() function for printing the string to the output screen. 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