views:

50

answers:

2

I'm trying to help out a friend understand this but even I don't really get what they're doing here.

Here's the method I'm trying to explain to him:

public void AddDiagonal()
        {
            int Addition;

            for (int f = 0; f < filas; f++)
            {
                for (int c = 0; c < columnas; c++)
                {
                    if (f == columnas - c - 1)
                    {
                        Addition += matriz[f, c];
                    }
                }
            }
        }
+1  A: 

The key to understanding this is the if statement:

if (f == columnas - c - 1)

The two nested loops iterate over rows (using f as an index) and for each row, over columns (using c as an index).

So each iteration, you test if the row number (that is f) is equal to the column number reversed (that is c subtracted from the total number of columns - columnas). The reason you test for the column number reversed is because you want to add from bottom left to top right, which is the same as adding from top-right to bottom left.

One thing to note is that a matrix diagonal only makes sense for a square matrix which means the number of columns needs to be same as the number of rows (in your algorithm filas should equal columnas).

So, assuming a 5x5 matrix:

Row 0 (f = 0) --> Column 4 (c = 5 - 0 - 1)
Row 1 (f = 1) --> Column 3 (c = 5 - 1 - 1)
Row 2 (f = 2) --> Column 2 (c = 5 - 2 - 1)
Row 3 (f = 3) --> Column 1 (c = 5 - 3 - 1)
Row 4 (f = 4) --> Column 0 (c = 5 - 4 - 1)

Miky Dinescu
A: 

There's no need for a double loop.

m x m matrix:

for(int rowNr = 0; rowNr < m; rowNr++)
{
   int colNr = m - rowNr - 1;
   Addition += matrix[rownr, colnr];
}
Carra