Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to find the sum of diagonals of a matrix in Go

1 Answer

0 votes
package main

import (
	"fmt"
)

func sumDiagonals(matrix [][]int, rows, cols int) int {
	sumDiagonalLeft := 0
	sumDiagonalRight := 0

	for i := 0; i < rows; i++ {
		for j := 0; j < cols; j++ {
			if i == j {
				sumDiagonalLeft += matrix[i][j]
			}
			if (i + j) == (rows - 1) {
				sumDiagonalRight += matrix[i][j]
			}
		}
	}

	fmt.Printf("sumDiagonalLeft = %d \nsumDiagonalRigth = %d\n", sumDiagonalLeft, sumDiagonalRight)

	return sumDiagonalLeft + sumDiagonalRight
}

func main() {
	matrix := [][]int{
		{ 1,   2,   3,   4,  0 },
        { 5,   6, 100,   8,  1 },
        { 2, 100,   8, 100,  3 },
        { 1,   7, 100,   9,  6 },
        { 9,  10,  11,  12, 13 },
	}
	
	// sumDiagonalLeft = (1 + 6 + 8 + 9 + 13) = 37
    // sumDiagonalRigth = (0 + 8 + 8 + 7 + 9) = 32 
    // 37 + 32 = 69

	rows := len(matrix)
	cols := len(matrix[0])

	fmt.Println(sumDiagonals(matrix, rows, cols))
}



/*
run:
   
sumDiagonalLeft = 37 
sumDiagonalRigth = 32
69
  
*/

 



answered Dec 19, 2024 by avibootz

Related questions

1 answer 70 views
1 answer 75 views
1 answer 64 views
2 answers 111 views
1 answer 96 views
1 answer 139 views
...