GO Program to find sum of matrix diagonal

How to find the sum of matrix diagonal

Here we are explaining how to find the sum of matrix diagonal in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

for initialization; condition; post{
       // statements....
} 

The initialization statement is executed before for loop starts and it is optional. The condition statement has a boolean expression. The post statement is executed after the body of the for-loop.

 

How to find the sum of matrix diagonal in GO Program

We are using fmt.println() function for printing the string to the output screen. 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