Golang Program to check identity matrix


February 22, 2022, Learn eTutorial
1399

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to check the identity matrix

 

An identity matrix is a given square matrix of any order which contains on its main diagonal elements with value of one, while the rest of the matrix elements are equal to zero.

for example

1 .0 0

0 1 0

0 0 1

How to check the identity matrix in Go Program

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()

 

Golang 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