Go Program to Find Sum of Matrix Upper Triangle

Write a Go Program to Find the Sum of the upper triangle items in a Matrix. In this Go sum of Matrix Upper Triangle example, the nested for loops iterate the matrix row and columns items. Within the loop, the if statement (if j > i) checks whether the column value is greater than the row. If True, add that item value to the matrix upper triangle sum.

package main

import "fmt"

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

    var upTriSumMat [10][10]int

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

    fmt.Println("Enter Matrix Items to find Upper Triangle Sum = ")
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            fmt.Scan(&upTriSumMat[i][j])
        }
    }
    upTriSum := 0
    for i = 0; i < rows; i++ {
        for j = 0; j < columns; j++ {
            if j > i {
                upTriSum = upTriSum + upTriSumMat[i][j]
            }
        }
    }
    fmt.Println("The Sum of Upper Triangle Matrix Elements  = ", upTriSum)
}
Enter the Matrix rows and Columns = 3 3
Enter Matrix Items to find Upper Triangle Sum = 
10 20 30
40 50 90
10 11 44
The Sum of Upper Triangle Matrix Elements  =  140

Golang Program to Find the Sum of Upper Triangle items in a Matrix using For loop range.

package main

import "fmt"

func main() {

    var upTriSumMat [3][3]int

    fmt.Println("Enter Matrix Items to find Upper Triangle Sum = ")
    for i, rows := range upTriSumMat {
        for j := range rows {
            fmt.Scan(&upTriSumMat[i][j])
        }
    }
    upTriSum := 0
    for i, rows := range upTriSumMat {
        for j := range rows {
            if j > i {
                upTriSum = upTriSum + upTriSumMat[i][j]
            }
        }
    }
    fmt.Println("The Sum of Upper Triangle Matrix Elements  = ", upTriSum)
}
Golang Program to Find Sum of Matrix Upper Triangle 2