In Java, a multi-dimensional array is nothing but an array of arrays. 2D array − A two-dimensional array in Java is represented as an array of one-dimensional arrays of the same type. Mostly, it is used to represent a table of values with rows and columns − Int[][] myArray = {{10, 20, 30}, {11, 21, 31}, {12, 22, 32} }
Program 1:
package demo;
public class Twodimensional1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] arr=new int[3][3];
for(int row=0;row<arr.length;row++)
{
for(int col=0;col<arr.length;col++)
{
arr[row][col]=1;
}
}
for(int row=0;row<arr.length;row++)
{
for(int col=0;col<arr.length;col++)
{
System.out.print(arr[row][col]+" ");
}
System.out.println();
}
}
}
output:
1 1 1
1 1 1
1 1 1
Program 2:
package demo;
public class twodimensional2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] arr=new int[3][3];
int value=1;
for(int row=0;row<arr.length;row++)
{
for(int col=0;col<arr.length;col++)
{
arr[row][col]=value;
value++;
}
}
for(int row=0;row<arr.length;row++)
{
for(int col=0;col<arr.length;col++)
{
System.out.print(arr[row][col]+" ");
}
System.out.println();
}
}
}
output:
1 2 3
4 5 6
7 8 9
Program 3:
package demo;
import java.util.Scanner;
public class twodimensional3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int value=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number");
int row=sc.nextInt();
int col=sc.nextInt();
int[][] arr=new int[row][col];
for(int r=0;r<arr.length;r++)
{
for(int c=0;c<arr.length;c++)
{
arr[r][c]=value;
value++;
}
}
for(int r=0;r<arr.length;r++)
{
for(int c=0;c<arr.length;c++)
{
System.out.print(arr[r][c]+" ");
}
System.out.println();
}
}
}
output:
3
3
1 2 3
4 5 6
7 8 9