- Java

2-Dimensional array in java.

Two dimensional array is nothing but set of many one-dimensional array which is represented in usually rows and columns but they are stored in the continuous memory location. The syntax of the 2-D array is

int twoD[][] = new int[4][5];
It allocates 4×5 int elements in an array which internally stores 80 bytes of memory(If one int takes 4 bytes of memory).
We can also assign the elements to an array dynamically and the syntax goes like this :
int[][] a={{1,2,3},{4,5,6},{8,9,10}};
We can also allocate row with different columns and this type of an array is called as a jagged array.
int[][] a={{1,2,3},{5,6},{8,9,10,11}};


Sample code goes here:

import java.util.*;
class arraydemo
{
    public static void main(String args[])
    {
        Scanner scan=new Scanner(System.in);
        int r,c,a[][];
        System.out.println("Enter the number of rows");
        r=scan.nextInt(); //Number of rows in an array
        System.out.println("Enter the number of columns");
        c=scan.nextInt(); //number of columns in an array
        a=new int[r][c]; //To initialize two dimensional array
        System.out.println("Enter the elements in an array");
       for(int i=0;i<r;i++)
       {
           for(int j=0;j<c;j++)
           {
               a[i][j]=scan.nextInt(); //To input the elements from an user
           }
       }
       System.out.println("The elements in an array");
       for(int i=0;i<r;i++)
       {
           for(int j=0;j<c;j++)
           {
                System.out.print(a[i][j]+"  "); //Display the elements in a matrix form
           }
           System.out.println("");
       }
    }
}

Leave a Reply