![]() |
VOOZH | about |
In this article, we will learn to Print 2 Dimensional Matrix. 2D-Matrix or Array is a combination of Multiple 1 Dimensional Arrays. In this article we cover different methods to print 2D Array. When we print each element of the 2D array we have to iterate each element so the minimum time complexity is O( N *M ) where N is the number of rows in the matrix and M is the number of columns in the matrix.
Prerequisites: Arrays in Java, Array Declarations in Java (Single and Multidimensional)
We can find the number of rows in a matrix mat[][] using mat.length. To find the number of columns in i'th row, we use mat[i].length.
Example 1: Print a 2-dimensional array using nested for-loop.
1 2 3 4 5 6 7 8 9 10 11 12
Complexity of the above method:
Example 2: Printing the 2D Array using the nested for-each loop.
1 2 3 4 5 6 7 8 9 10 11 12
Complexity of the above method:
Example 3: Converts row into a string using Arrays.toString(row) then each row is printed in a separate line.
[1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12]
Complexity of the above method:
Example 4: Using Arrays.deepToString(int[][]) converts the 2D array to a string in a single step.
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Complexity of the above method: