Search code examples
javamatrixdiagonal

Diagonals with Matrices


Currently trying to print a matrix with an output of:

0 0 0 0 4
0 0 0 3 0
0 0 2 0 0
0 1 0 0 0
0 0 0 0 0

This is my code currently:

for(int row=0; row < matrix.length; row++)
        for(int col = 0; col < matrix[row].length; col++)
            if(row+col == matrix[row].length)

Obviously not complete. I'm not even sure my logic behind the code is correct.


Solution

  • This is the code that should work (assuming the matrix is always square):

    for(int row=0; row < matrix.length; row++){
            for(int col = 0; col < matrix[row].length; col++){
                if(row + col == matrix.length - 1){
                    matrix[row][col] = col;
                    System.out.print(col+ " "); // Print value
                } else {
                    matrix[row][col] = 0; // Set value
                    System.out.print("0 ");
                }
            }
            System.out.println("");
        }
    

    We subtracted by 1 in the condition since the length-1 gives us the last index. (reminder that indexes start from 0 and to go length -1)