GO Program to check identity matrix

How to check the identity matrix

Here we are explaining how to check the identity matrix 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 check the identity matrix in GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to check the identity matrix in the Go language. Here variable mat is used to hold the matrix elements and iteration elements i,j. Read the size of the matrix into the variables num. After reading elements check the matrix elements for identity matrix using two nested for loops.  For this check, the diagonal elements are 1's and others are 0's. 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

STEP 4: Read the size of the matrix into num

STEP 5: Read the matrix elements and set a flag variable 

STEP 6: Check the diagonal elements are 1's and others are 0's using two nested for loops

STEP 7: Print the result using fmt.print()

 

GO Source Code

                                          package main

import "fmt"

func main() {

    var num, i, j int
    var mat [10][10]int

    fmt.Print("Enter the size of matrix  = ")
    fmt.Scan(#)

    fmt.Print("Enter the matrix items = ")
    for i = 0; i < num; i++ {
        for j = 0; j < num; j++ {
            fmt.Scan(&mat;[i][j])
        }
    }
    flag := 1
    for i = 0; i < num; i++ {
        for j = 0; j < num; j++ {
            if mat[i][j] != 1 && mat[j][i] != 0 {
                flag = 0
                break
            }
        }
    }
    if flag == 1 {
        fmt.Println("It is an Identity matrix")
    } else {
        fmt.Println("It is not an Identity matrix")
    }
}
                                      

OUTPUT

Enter the size of matrix  = 3
1  0  0  0  1  0  0  0  1
It is an Identity matrix

Enter the size of matrix  = 2
1  0  1  0  
It is not an Identity matrix