Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out a 2D array in matrix format

Tags:

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();
}
like image 397
dawnoflife Avatar asked Feb 21 '11 03:02

dawnoflife


People also ask

How do you print a 2D array in matrix form?

public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].

How do you create a 2D matrix?

To declare a 2D array, specify the type of elements that will be stored in the array, then ( [][] ) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference.

Can you print a 2D array in Java?

Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays. deepToString() method, etc.


1 Answers

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
like image 121
Tyler Treat Avatar answered Oct 23 '22 09:10

Tyler Treat