Write a Go Program to Find the Sum of the diagonal items in a Matrix. In this Go example, we use for loop to iterate the row items and add the matrix diagonal items to the sum (sum = sum + dSumMat[i][I]).
package main
import "fmt"
func main() {
var i, j, rows, columns int
var dSumMat [10][10]int
fmt.Print("Enter the Matrix rows and Columns = ")
fmt.Scan(&rows, &columns)
fmt.Println("Enter the Matrix Items to find the Diagonal Sum = ")
for i = 0; i < rows; i++ {
for j = 0; j < columns; j++ {
fmt.Scan(&dSumMat[i][j])
}
}
sum := 0
for i = 0; i < rows; i++ {
sum = sum + dSumMat[i][i]
}
fmt.Println("The Sum of Matrix Diagonal Elements = ", sum)
}
Enter the Matrix rows and Columns = 2 2
Enter the Matrix Items to find the Diagonal Sum =
10 20
30 50
The Sum of Matrix Diagonal Elements = 60
Golang Program to Find the Sum of Diagonal elements in a Matrix using For loop range.
package main
import "fmt"
func main() {
var dSumMat [3][3]int
fmt.Println("Enter the Matrix Items to find the Diagonal Sum = ")
for i, rows := range dSumMat {
for j := range rows {
fmt.Scan(&dSumMat[i][j])
}
}
sum := 0
for k := range dSumMat {
sum = sum + dSumMat[k][k]
}
fmt.Println("The Sum of Matrix Diagonal Elements = ", sum)
}
