Search code examples
javaarraysmatrixmultidimensional-array

Printing out a 2D array in matrix format


How can I print out a simple int[][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn't apparently work. If it helps I'm trying to compile this code in a linux ssh terminal.

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        System.out.println(matrix[i][j] + " ");
    }
    System.out.println();
}

Solution

  • final int[][] matrix = {
      { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 }
    };
    
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }
    

    Produces:

    1 2 3
    4 5 6
    7 8 9