Here, we will write a program to subtract two matrix in go. Given below, you can find algorithm and program.
Here, we are going to learn subtractation of two matrix:
- Take number of rows and columns as input
- Apply nested for loop to take matrix elements as input
- Subtract the matrix elements
- Print the resultant matrix
Example:
Input: row = 2, column = 3
Matrix_1:
[
7, 8, 2
3, 11, 10
]
Matrix_2:
[
1, 2, 3
4, 5, 6
]
Output:
[
6, 6, -1
-1, 6, 4
]
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])
}
}
// Subtracting 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 Subtracting 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:
7
8
2
3
11
10
Enter matrix_2 elements:
1
2
3
4
5
6
After Subtracting Matrix is:
6 6 -1
-1 6 4
To learn more about golang. Please follow given below link.
https://www.techieindoor.com/go-lang/
References:
https://golang.org/doc/ https://golang.org/pkg/