how to displays the elements of 2D arrays in java code example
Example 1: how to print a 2d array in java
for (int row = 0; row < arr.length; row++)
{
for (int col = 0; col < arr[row].length; col++)
{
System.out.printf("%5d", arr[row][col]);
}
System.out.println();
}
Example 2: print 2d array in java
int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));
Example 3: adding elements in a specified column or row in a two dimensional array java
for (int row = 0; row < matrix.length; row++) {
int rowSum = 0;
for (int col = 0; col < matrix[row].length; col++) {
rowSum += matrix[row][col];
}
System.out.println("Sum of the elements at row " + row + " is: " + rowSum);
}
for (int col = 0; col < matrix[0].length; col++) {
int colSum = 0;
for (int row = 0; row < matrix.length; row++) {
colSum += matrix[row][col];
}
System.out.println("Sum of the elements at col " + col + " is: " + colSum);
}