Go Program to Check Sparse Matrix

Write a Go program to check whether the given matrix is sparse or not. Any matrix is a sparse matrix if it contains a large number of zeros. The mathematical formula for Golang sparse matrix is the number of zeros > (m * n)/2.

Within the nested for loop, we used the if statement (if sparseMat[i][j] == 0) to count the total number of zeros in a matrix. The last If else statement (if count > ((i * j) / 2)) checks other the total zeros are greater than the row * columns/2. If True, it is a sparse matrix.

package main

import "fmt"

func main() {
    var num, i, j int

    var sparseMat [10][10]int

    fmt.Print("Enter the Sparse Matrix Size = ")
    fmt.Scan(&num)

    fmt.Print("Enter the Sparse Matrix Items = ")
    for i = 0; i < num; i++ {
        for j = 0; j < num; j++ {
            fmt.Scan(&sparseMat[i][j])
        }
    }
    count := 0
    for i = 0; i < num; i++ {
        for j = 0; j < num; j++ {
            if sparseMat[i][j] == 0 {
                count++
            }
        }
    }
    if count > ((i * j) / 2) {
        fmt.Println("It is a Sparse Matrix")
    } else {
        fmt.Println("It is Not a Sparse Matrix")
    }
}
Go Program to Check Sparse Matrix 1

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.