Home »
Java Programs »
Java Array Programs
Java program to read and print a two dimensional array
In this java program, we are going to learn how to read and print a two dimensional array? Here, we are reading number of rows and columns and reading, printing the array elements according to the given inputs.
By IncludeHelp Last updated : December 23, 2023
Problem statement
Read number of rows and columns, array elements for two dimensional array and print in matrix format using java program.
Example
Input:
Enter number of rows: 3
Enter number of columns: 3
Enter elements
1
2
3
4
5
6
7
8
9
Output:
Matrix is:
1 2 3
4 5 6
7 8 9
Program to read and print two dimensional array (Matrix) in java
import java.util.Scanner;
public class Ex2DArray {
public static void main(String args[]) {
// initialize here.
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
// enter row and column for array.
System.out.print("Enter row for the array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter column for the array (max 10) : ");
col = scan.nextInt();
// enter array elements.
System.out.println("Enter " + (row * col) + " Array Elements : ");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
arr[i][j] = scan.nextInt();
}
}
// the 2D array is here.
System.out.print("The Array is :\n");
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Output
Enter row for the array (max 10) : 4
Enter column for the array (max 10) : 4
Enter 16 Array Elements :
1
2
3
4
4
3
2
1
4
5
6
6
5
4
7
8
The Array is :
1 2 3 4
4 3 2 1
4 5 6 6
5 4 7 8
Java Array Programs »