Go Program to Print Matrix Lower Triangle

Write a Go Program to print the lower triangle of a Matrix. In this Go Matrix Lower Triangle example, the nested for loops help to iterate the matrix row and columns. Within the loop, if condition (if i >= j) checks whether the row value is greater than or equal to the column value. If True, print that item as the lower triangle matrix item; if the condition results false, print zero.

package main

import "fmt"

func main() {
    var i, j, rows, columns int

    var lowTriangleMat [10][10]int

    fmt.Print("Enter the Lower Matrix rows and Columns = ")
    fmt.Scan(&rows, &columns)

    fmt.Println("Enter Matrix Items to Print Lower Triangle = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&lowTriangleMat[i][j])
        }
    }
    for i = 0; i < rows; i++ {
        fmt.Println()
        for j = 0; j < columns; j++ {
            if i >= j {
                fmt.Print(lowTriangleMat[i][j], " ")
            } else {
                fmt.Print("0 ")
            }
        }
    }
    fmt.Println()
}
Enter the Lower Matrix rows and Columns = 2 2
Enter Matrix Items to Print Lower Triangle = 
1 2
3 4

1 0 
3 4 

Golang Program to print the Lower Triangle Matrix using For loop range.

package main

import "fmt"

func main() {

    var lowTriangleMat [3][3]int

    fmt.Println("Enter Matrix Items to Print Lower Triangle = ")
    for i, rows := range lowTriangleMat {
        for j := range rows {
            fmt.Scan(&lowTriangleMat[i][j])
        }
    }
    for i, rows := range lowTriangleMat {
        fmt.Println()
        for j := range rows {
            if j >= i {
                fmt.Print(lowTriangleMat[i][j], " ")
            } else {
                fmt.Print("0 ")
            }
        }
    }
    fmt.Println()
}
 Golang Program to Print Matrix Lower Triangle 2

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.