Print the upper and lower triangular of a java matrix

1

I am trying to print the upper and lower triangular of a matrix. In this case I choose the

1 2 3 
4 5 6 
7 8 9

The code is this:

public class matriztriangular {

public static void main(String args[]) {

    int[][] matriz = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    imprimirMatriz(matriz);
}

public static void imprimirMatriz(int[][] matriz) {
    int lado = matriz.length;
    for (int i = 0; i < lado; i++) {
        for (int j = 0; j <= i; j++) {
            System.out.print(matriz[i][j]);

        }
    }
    System.out.println();
    for (int k = 0; k < lado; k++) {
        for (int l = 0; l <= k; l++) {
            System.out.print(matriz[l][k]);

        }
     }
  }
}

The problem I have is that when I print the upper triangular, it does me wrong, instead of leaving me

  

1 2 3 5 6 9

I get it

  

1 2 5 3 6 9

(the lower triangular if you do it well). Does anyone know where the error is in the code?

    
asked by Fernando 23.01.2017 в 12:03
source

2 answers

3

The problem is how you are going through the matrix.

Try this

for (int i = 0; i < lado; i++) {
    for (int j = i; j < matriz[i].length; j++) {
        System.out.print(matriz[i][j]);
    }
}
    
answered by 23.01.2017 / 12:30
source
1

Try with the help of an accountant:

int[][] matriz = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
    int cont = 0;

    for (int i=0; i<matriz.length; i++){
      for (int j=cont; j<matriz[i].length; j++){
        System.out.print(matriz[i][j] + ",");
      }
      cont++;
    }

The output would be:

  

1,2,3,5,6,9,

    
answered by 23.01.2017 в 12:42