GO Program to find sum of matrix diagonal

How to find the sum of matrix diagonal

Calculate the sums across the two diagonals of a square matrix. Along the first diagonal of the matrix, row index = column index i.e mat[i][j] lies on the first diagonal if i = j. Along the other diagonal, row index = n – 1 – column index i.e mat[i][j] lies on the second diagonal if i = n-1-j.

for example

matrix=

1 2 3

4 5 6

7 8 9

diagonal sum = 1=5=9 = 15

2nd diagonal sum= 3+5+7 = 15

How to find the sum of matrix diagonal in Go Program

Here we are showing how to find the sum of matrix diagonal in the Go language. Here variable mat is used to hold the matrix elements and iteration elements i,j. The variable sum holds the sum of diagonal elements. Read the number of rows and columns of the matrix into the variables row, col. After reading elements, find the sum of diagonal elements using for loop.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 mat, and iteration variables i,j, and sum variable sum

STEP 4: Read the number of rows and columns into row, col

STEP 5: Read the matrix elements  

STEP 6: Find the sum of diagonal elements using for loops

STEP 7: Print the result sum using fmt.println()

 

GO Source Code

                                          package main

import "fmt"

func main() {
    var i, j, row, col int
    var mat [10][10]int

    fmt.Print("Enter the number of rows and columns = ")
    fmt.Scan(&row;, &col;)

    fmt.Println("Enter the matrix items = ")
    for i = 0; i < row; i++ {
        for j = 0; j < col; j++ {
            fmt.Scan(&mat;[i][j])
        }
    }
    sum := 0
    for i = 0; i < row; i++ {
        sum = sum + mat[i][i]
    }     fmt.Println("The sum of matrix diag sum)
}
                                      

OUTPUT

Enter the number of rows and columns = 2  2
Enter the matrix items = 
25  18
40  12 The sum of matrix diag