×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to calculate the sum of rows elements of the matrix

Here, we are going to learn how to calculate the sum of rows elements of the matrix in Golang (Go Language)?
Submitted by Nidhi, on March 08, 2021 [Last updated : March 03, 2023]

Calculating the sum of rows elements of the matrix in Golang

Problem Solution:

In this program, we will read elements of the matrix from the user and then calculate the sum of rows elements and print the result on the console screen.

Program/Source Code:

The source code to calculate the sum of rows elements of the matrix is given below. The given program is compiled and executed successfully.

Golang code to calculate the sum of rows elements of the matrix

// Golang program to calculate the sum of rows
// elements of the matrix

package main

import "fmt"

func main() {
	var sum int = 0
	var matrix [2][2]int

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

	fmt.Printf("Matrix elements: \n")
	for i := 0; i < 2; i++ {
		for j := 0; j < 2; j++ {
			fmt.Printf("%d ", matrix[i][j])
		}
		fmt.Printf("\n")
	}

	for i := 0; i < 2; i++ {
		sum = 0
		for j := 0; j < 2; j++ {
			sum = sum + matrix[i][j]
		}
		fmt.Printf("\nSum of row %d: %d", i, sum)
	}
}

Output:

Enter matrix elements:
Elements: matrix[0][0]: 11
Elements: matrix[0][1]: 22
Elements: matrix[1][0]: 33
Elements: matrix[1][1]: 44
Matrix elements:
11 22
33 44

Sum of row 0: 33
Sum of row 1: 77

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 2X2 matrix using two-dimensional array.

    fmt.Printf("Enter matrix elements: \n")
    for i:=0;i<2;i++{
        for j:=0;j<2;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 elements: \n")
    for i:=0;i<2;i++{
        for j:=0;j<2;j++{
            fmt.Printf("%d ",matrix[i][j])
        }
        fmt.Printf("\n")
    }
    
    for i:=0;i<2;i++{
        sum=0
        for j:=0;j<2;j++{
            sum = sum + matrix[i][j]
        }
        fmt.Printf("\nSum of row %d: %d",i,sum)
    }

In the above code, we calculated the sum of rows elements of the matrix and printed the matrix as well as the sum of all rows on the console screen.

Golang Array Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.