# Golang program to print the sum of left diagonal elements of the matrix

Here, we are going to learn how to print the sum of left diagonal elements of the matrix in Golang (Go Language)?
Submitted by Nidhi, on March 08, 2021

Problem Solution:

In this program, we will read elements of the matrix from the user and then calculate the left diagonal of the matrix and also print the matrix on the console screen.

Program/Source Code:

The source code to print the sum of left diagonal elements of the matrix is given below. The given program is compiled and executed successfully.

```// Golang program to print the
// sum of left diagonal elements of the matrix

package main

import "fmt"

func main() {
var sum int = 0
var matrix int

fmt.Printf("Enter matrix elements: \n")
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
fmt.Printf("Elements: matrix[%d][%d]: ", i, j)
fmt.Scanf("%d", &matrix[i][j])
}
}

fmt.Printf("Matrix: \n")
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
if i == j {
sum = sum + matrix[i][j]
}
fmt.Printf("%d ", matrix[i][j])
}
fmt.Printf("\n")
}
fmt.Printf("\nSum of left diagonal elements is: %d", sum)
}
```

Output:

```Enter matrix elements:
Elements: matrix: 11
Elements: matrix: 22
Elements: matrix: 33
Elements: matrix: 44
Elements: matrix: 55
Elements: matrix: 66
Elements: matrix: 77
Elements: matrix: 88
Elements: matrix: 99
Matrix:
11 22 33
44 55 66
77 88 99

Sum of left diagonal elements is: 165
```

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created 3X3 matrix using a two-dimensional array.

```fmt.Printf("Enter matrix elements: \n")
for i:=0;i<3;i++{
for j:=0;j<3;j++{
fmt.Printf("Elements: matrix[%d][%d]: ",i,j)
fmt.Scanf("%d",&matrix[i][j])
}
}
```

In the above code, we read matrix elements from the user.

```fmt.Printf("Matrix: \n")
for i:=0;i<3;i++{
for j:=0;j<3;j++{
if(i==j){
sum=sum+matrix[i][j];
}
fmt.Printf("%d ",matrix[i][j])
}
fmt.Printf("\n")
}
}
fmt.Printf("\nSum of left diagonal elements is: %d",sum)
```

In the above code, we calculated the sum of left diagonal elements and printed the matrix on the console screen.