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,907 questions

51,839 answers

573 users

How to find the sum of boundary elements of a matrix in C#

1 Answer

0 votes
using System;

public class Program
{
	private static int sumDiagonals(int[,] matrix) {
		int rows = matrix.GetLength(0);
        int cols = matrix.GetLength(1);
		int sumDiagonalLeft = 0, sumDiagonalRigth = 0;
		int indexleft = 0, indexright = cols;

		for (int i = 0; i < rows; i++) {
			sumDiagonalLeft += matrix[i,indexleft++];
			sumDiagonalRigth += matrix[i,--indexright];
		}

		Console.WriteLine("sumDiagonalLeft = " + sumDiagonalLeft);
		Console.WriteLine("sumDiagonalRigth = " + sumDiagonalRigth);

		return sumDiagonalLeft + sumDiagonalRigth;
	}
	
	public static void Main(string[] args)
	{
	    int[,] matrix = { {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

		Console.Write(sumDiagonals(matrix));
	}
}




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

 



answered Jun 17, 2023 by avibootz
edited Jun 19, 2023 by avibootz

Related questions

1 answer 120 views
1 answer 155 views
1 answer 100 views
1 answer 80 views
1 answer 80 views
...