matrix print 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: Java program to print 3x3 matrix
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaPrint3x3Matrix
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[][] inputNumber = new int[3][3];
int a, b;
String strMatrix;
System.out.println("Please enter elements to print 3x3 matrix: ");
for(a = 0; a <= 2; a++)
{
for(b = 0; b <= 2; b++)
{
strMatrix = br.readLine();
inputNumber[a][b] = Integer.parseInt(strMatrix);
}
}
System.out.println("Elements in 3x3 matrix are: ");
System.out.println("");
for(a = 0; a <= 2; a++)
{
for(b = 0; b <= 2; b++)
{
System.out.print(inputNumber[a][b] + "\t");
}
System.out.println();
}
}
}
Example 3: print 2d array in java
int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));