How to show matrix top right triangular java

0

Hello, good as I show the upper triangle of this matrix, thank you!

System.out.println("Mostra la matriu");

        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                System.out.print(mat[i][j] + "\t");

            }
            System.out.println();

        }

I would like the upper right triangle, the diagonal of the matrix up.

Given the matrix:

1234
5678
9012
3456

I would like to get the matrix:

1234
 678
  12
   6
    
asked by Iron Man 22.02.2018 в 20:00
source

2 answers

2

To do what you want, you must paint blanks in the positions of the matrix you are discarding. So you should check if the current cell of the matrix you want to paint or discard.

   for (int i = 0; i < mat.length; i++) {
        for (int j = 0; j < mat[i].length; j++) {
            if (j < i) {
                System.out.print(" ");
            } else {
                System.out.print(mat[i][j]);
            }
        }
        System.out.println();           
    }
    
answered by 22.02.2018 / 20:48
source
4

With this should be enough:

System.out.println("Mostra la matriu");        
    for (int i = 0; i < mat.length; i++) {
        for (int j = i; j < mat[i].length; j++) {
            System.out.print(mat[i][j] + "\t");             
        }
        System.out.println();           
    }

What you do is initialize the second for in the horizontal position equal to the vertical, which will generate the upper triangle.

  

If you would like to generate the lower triangle , the for should be for (int j = 0; j < i;j++)

    
answered by 22.02.2018 в 20:08