Menu Close

Go – Program to add two matrix in go

Here, we will write a program to add two matrix in go. Given below, you can find algorithm and program.

Here, we are going to learn addition of two matrix:

  • Take number of rows and columns as input
  • Apply nested for loop to take matrix elements as input
  • Add the matrix elements
  • Print the resultant matrix

Example:

Input: row = 2, column = 3

Matrix_1:
[
1, 2, 3
4, 5, 6
]

Matrix_2:
[
7, 8, 9
10, 11, 12
]

Output:
[
8, 10, 12
14, 16, 18
]

Code:

package main

import (

 "fmt"

)

func main() {

  var row, col int

  var mat_1, mat_2, result [10][10]int

  fmt.Print("Enter no of rows: ")

  fmt.Scanln(&row)

  fmt.Print("Enter no of column: ")

  fmt.Scanln(&col)


  fmt.Println("\nEnter matrix_1 elements: ")

  for i := 0; i < row; i++ {

    for j := 0; j < col; j++ {

      fmt.Scanf("%d ", &mat_1[i][j])

    }

  }

  fmt.Println("\nEnter matrix_2 elements: ")

  for i := 0; i < row; i++ {

    for j := 0; j < col; j++ {

      fmt.Scanf("%d ", &mat_2[i][j])

    }

  }

 // Adding two matrix

  for i := 0; i < row; i++ {

    for j := 0; j < col; j++ {

      result[i][j] = mat_1[i][j] + mat_2[i][j]

    }

  }

  fmt.Println("\nAfter adding Matrix is: \n")

  for i := 0; i < row; i++ {

    for j := 0; j < col; j++ {

      fmt.Printf("%d ", result[i][j])

    }
    fmt.Println("\n")

  }

}

Output:

Enter no of rows: 2
Enter no of column: 3

Enter matrix_1 elements:
1
2
3
4
5
6
Enter matrix_2 elements:
7
8
9
10
11
12

After adding Matrix is:
8 10 12
14 16 18

To learn more about golang. Please follow given below link.

https://techieindoor.com/go-lang/

References:

https://golang.org/doc/
https://golang.org/pkg/

Posted in golang, golang program

Leave a Reply

Your email address will not be published. Required fields are marked *