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();
}
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].
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.
Java provides multiple ways to print a 2d array, for example nested for-loop, for-each loop, Arrays. deepToString() method, etc.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With