Advertisement

Java Program for 2D Array with Variable Memory Allocation Columnwise

JAVA 2D Array Column-wise variable size

Java Program for 2D Array with Variable Memory Allocation Columnwise

In Java programs, 2-dimensional arrays are more dynamic than in other languages. Here we can allocate variable lengths of column-wise memory for 2D arrays. 

For 2D arrays, we need to mention the sizes of rows and columns while declaring arrays. If we provide fixed values for rows and columns then the array will be of table-like structure or we can say like matrices. 

But, if we use variable length for column size then the array will be created with a custom structure. Basically, to print different types of patterns in Java, we use 2D arrays of variable memory allocation of column-wise. 

Now, here's a program that'll demonstrate the usability of the variable-length columns. 

Java Program for 2D Array with Variable Memory Allocation Columnwise

Save the file with the name Var_Array.java

class Var_Array{
public static void main (String args[])
{
int i, j, k=0; //variable decleration
int twoDim[][] = new int[4][]; //2D array declare + row-wise memory allocation
twoDim[0] = new int[1]; //specifying column wise memory allocation , here 1st row=1 column
twoDim[1] = new int[2]; //specifying column wise memory allocation , here 2nd row=2 columns
twoDim[2] = new int[3]; //specifying column wise memory allocation , here 3rd row=3 columns
twoDim[3] = new int[4]; //specifying column wise memory allocation , here 4th row=4 columns
for ( i= 0; i <4 ; i++) //initialise the 2D array
 {
 for (j = 0; j<=i; j++)
 {
    twoDim[i][j] = k; //initialise the cells with the values of k variable
    k++; //increase k by 1
 }
 }
 for (i= 0; i <4 ; i++) //display the 2D array
 {
 for (j = 0; j<=i; j++)
 {
    System.out.print(twoDim[i][j] + " "); //print
 }
System.out.println(); //for newline
}
}
}

Output:

Java 2D Array variable length columns

Here the workings of the lines is given in the form of comments of this program. The Output of this program shall be look like this:

when i=0, j=0              k=0
when i=1, j=0,1           k=1 2
when i=2, j=0,1,2        k=3 4 5
when i=3, j=0,1,2,3     k=6 7 8 9



Post a Comment

0 Comments