how to add the diagonal from right to left in a matrix

0

Good evening, I managed to add the left-right diagonal, that is, from position 0,0, but I have not managed to add the diagonal from right to left in an example of a 3 x 3 matrix. The code that I am going to show it's just the sum of the diagonal, please can you advise me how to add the other diagonal. Grace.

Console.WriteLine("sumadiagonal de izuierda  a derecha");
  for (j = 0; j < matriz.GetLength(0); j++)
    {
      for (i = 0; i < matriz.GetLength(1); i++)
        {
          if (i == j)
            {
              sumadiagonal1 += matriz[i, j];
            }
        }
    }
Console.WriteLine("La suma de la diagonal 1 es =" + sumadiagonal1);
    
asked by jorge 24.08.2017 в 02:26
source

2 answers

1

To calculate the diagonal from left to right, you do not need a for anidado , since it is a square matrix with only one for is enough

int suma = 0;
for(int i = 0; i < matriz.length; i++){
   suma += matriz[i][i];
}

and for the sum of the diagonal from right to left of a square matrix you can do it like this

int suma = 0;

for(int f = 0, c = matriz.length - 1; f < matriz.length && c >= 0 ; f++, c--){
   suma += matriz[f][c];
}
    
answered by 24.08.2017 в 03:27
1

Advising you

Being your 3x3 matrix, the logic to consider would be, for example:

+---+---+---+   Valor   [i , j]       i + j
| 1 | 2 | 1 |     1   = [0 , 2]  =>     2
+---+---+---+
| 3 | 4 | 1 |     4   = [1 , 1]  =>     2
+---+---+---+
| 5 | 6 | 3 |     5   = [2 , 0]  =>     2
+---+---+---+

1 + 4 + 5 = 10

Where, i and j are indexes of your rows and columns respectively.

Also, you will appreciate that the sum of both i + j = 3 - 1 .

For example:

int[,] matriz = new int[3, 3] { { 1, 2, 1 }, { 3, 4, 1 }, { 5, 6, 3 } };    

int cantFilas = matriz.GetLength(0);
int cantColumnas = matriz.GetLength(1);

if(cantFilas != cantColumnas){
    Console.WriteLine("No es una matriz cuadrada");
    return;
}

for (int i = 0; i < cantFilas; i++)
{            
    int j = ((cantFilas - 1) - i);

    Console.WriteLine("{0} = [{1} , {2}]", matriz[i, j], i , j);                
}

You'll get:

1 = [0 , 2]
4 = [1 , 1]
5 = [2 , 0]

DEMO

    
answered by 24.08.2017 в 03:12