Java | Ragged Array

05 min read

Ragged Array:

Ragged Arrays is also called as a Jagged array. But 'Jagged array' is the term used commonly in languages like C#. They are of varying length.

How to create Ragged array:

When memory is allocated for a multi-dimensional array, only the first dimension (left most) must be specified compulsorily. Remaining elements can be allocated separately.

Example:

int[ ] [ ] a = new int [3] [ ];
a[0] = new int[4];
a[1] = new int[2];
a[2] = new int[3]; 

It is inconvenient to declare the individual rows explicitly for large number of rows. It can also be written as follows:

int[ ] [ ]  a = new int[3][ ];  -> statement A
for(int i= 0;i<a.length;i++)
{
System.out.println("Enter the number ofcolumns for row"+i);
in x =  sc.nextInt( );
a[i] = new int[x];  - > Statement B
}

When the user gives 4, 2, 3 value tier each iteration, a 2-D array with 3 rows— one with 4 col, another with 2 col and last with 3 col will he created.

The statement marked A creates an array of 3 reference variables and its starting address is assigned to *a'.  Now that we have created 3 reference variables, each one can store a reference or address. Statement B, when executed, creates an array (row) of 'x' elements and its starting address is stored in 0th element of the array of reference variables. When statement B is repeated 3 times inside the loop, 3 arrays with 'x' columns will be created & their addresses stored appropriately inside the elements of the array of references.

Example:

Write a program to find the sum of the elements of a matrix.

int[ ] [ ] matrix ={{ l, 2, 3}, A4, 5, 6), (7, 8, 9));
int sum=0;
for(int=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
sum += matrix[i][j];
}
System.outprintln(sum);
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error