user5815164
user5815164

Reputation: 43

Calculate sum of numbers on matrix diagonal

I have a dynamic matrix and I need to to calculate sum of digits in this way:

0 1 2 3 4 5 6

10 11 12 13 14 15 16

20 21 22 23 24 25 26

30 31 32 33 34 35 36

40 41 42 43 44 45 46

50 51 52 53 54 55 56

60 61 62 63 64 65 66

I can't understand in which way I should compare i and j:

long result = 0;
for (int i = 0; i < len; i++)
{
    for (int j = 0; j < len; j++)
    {
        // only works for diagonal
        if (i == j) // should use j - 1 or i - 1? 
        {
            result += matrix[i][j];
        }
    }
}

Upvotes: 4

Views: 5308

Answers (2)

TJay
TJay

Reputation: 1

    int d1=0;
    int d2=0;
    int arrLength=arr.Count();
    for(int row=0;row<arrLength;row++){
                d1 += arr[row][row];
                d2 +=arr[row][arrLength-row-1];
            }

Upvotes: 0

ASh
ASh

Reputation: 35713

no need to scan full matrix:

long result = 0;
for (int i = 0; i < len; i++)
{
     result += matrix[i][i];      // diagonal
     if (i < len - 1)             // stay within array bounds
        result += matrix[i][i+1]; // next to diagonal
}

modification without index check on every iteration:

// assign corner value from bottom row to result
long result = matrix[len-1][len-1];
// for each row (except last!) add diagonal and next to diagonal values
for (int i = 0; i < len-1; i++)    
     result += matrix[i][i] + matrix[i][i+1];

Upvotes: 7

Related Questions