In this Go program, we used the nested for loops to iterate and print the matrix items.
package main
import "fmt"
func main() {
var rows, columns, i, j int
var printmat [10][10]int
fmt.Print("Enter the Matrix Rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Print("Enter the Matrix Items = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&printmat[i][j])
}
}
fmt.Println("**** The List of Matrix Items ****")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Printf("The Matrix Item at [%d][%d] Index Position = %d\n", i, j, printmat[i][j])
}
}
}
Enter the Matrix Rows and Columns = 2 2
Enter the Matrix Items =
10 20
9 33
**** The List of Matrix Items ****
The Matrix Item at [0][0] Index Position = 10
The Matrix Item at [0][1] Index Position = 20
The Matrix Item at [1][0] Index Position = 9
The Matrix Item at [1][1] Index Position = 33
Golang Program to Print Matrix Items
In this Golang example, we used the length of a matrix (for i = 0; i < len(printmat); i++) as the for loop condition.
package main
import "fmt"
func main() {
var i, j int
var printmat [2][2]int
fmt.Print("Enter the Matrix Items = ")
for i = 0; i < 2; i++ {
for j = 0; j < 2; j++ {
fmt.Scan(&printmat[i][j])
}
}
fmt.Println("**** The List of Matrix Items ****")
for i = 0; i < len(printmat); i++ {
for j = 0; j < len(printmat[i]); j++ {
fmt.Printf("The Matrix Item at [%d][%d] Index Position = %d\n", i, j, printmat[i][j])
}
}
}
Enter the Matrix Items =
99 88
77 55
**** The List of Matrix Items ****
The Matrix Item at [0][0] Index Position = 99
The Matrix Item at [0][1] Index Position = 88
The Matrix Item at [1][0] Index Position = 77
The Matrix Item at [1][1] Index Position = 55
In this Golang example, we used the nested for loop range to assign values to printmat matrix. Next, we used another one (for i, row := range printmat { for j, val := range row) to print those matrix items.
package main
import "fmt"
func main() {
var printmat [3][3]int
fmt.Print("Enter the Matrix Items = ")
for k, r := range printmat {
for l := range r {
fmt.Scan(&printmat[k][l])
}
}
fmt.Println("**** The List of Matrix Items ****")
for i, row := range printmat {
for j, val := range row {
fmt.Printf("The Matrix Item at [%d][%d] Index Position = %d\n", i, j, val)
}
}
}
