Hello everyone
Can anyone help me with codes to calculate sum of numbers in the diagonal of a 2 dimensional matrix array. Please help. (a b c d e
f g h i j
j k l m n
o p q r s)

Recommended Answers

All 5 Replies

Hi FELIGO, welcome :)
Sure we can help!
What have you tried for yourself?If you post code, post it in CODE tags!!!

Is maybe this what you have been looking for:

int[,] array = new int[2, 4] { { 1, 2, 3, 4 }, { 1, 2, 3, 4 } };
            List<int> list = new List<int>();
            for (int i = 0; i < array.GetLength(1); i++)
            {
                int sum = 0;
                for (int j = 0; j < array.GetLength(0); j++)
                {
                    sum += array[j, i];
                }
                list.Add(sum);
            }
            //list now has all sums of 2-d array!
            //result is: 2,4,6 and 8

If not, let me know.

according to you coding for diagonal element i and j will be equal..

lets say i have following matrix:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

sum will be = 1+2+3+4 = 10

Coding for above:

int[,] matA =new int[4,4]  { { 1, 2, 3, 4 }, { 1, 2, 3, 4 }, { 1, 2, 3, 4 }, { 1, 2, 3, 4 } };
            int sum = 0;
            for (int i = 0; i < 4; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    if (i == j)
                    {
                        sum += matA[i, j];
                    }
                }
            }

            Console.WriteLine(sum);

i dont know but when i trouble like this, i use google

Use better see (or use) a doctor, if you are in troubles like you are now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.