user6794537
user6794537

Reputation:

2D array in Java with incremental column number that increase in each row

How Can I create a Java 2 Dimensional array whose output will be like:

0
0 0
0 0 0
0 0 0 0

I know how to declare a 2 dimensional array.But don't know how to implement that. Sp need some help here. Thanks

Upvotes: 0

Views: 736

Answers (2)

ValarDohaeris
ValarDohaeris

Reputation: 649

Here no of zeros you want to put in each row is equals to the sequence no of that row eg 1st row has 1 0,2nd has 2 and so on. It can be done as follows:

int[][] arr = new int[5][];
for (int i = 0; i < arr.length; i++)
{
  arr[i]=new int[i+1];
  for (int j = 0; j <= i; j++)
    arr[i][j] = 0; //or whatever you want to store
}

Upvotes: 0

Eritrean
Eritrean

Reputation: 16498

Java is considered "row major", meaning that it does rows first. So if you know the number of rows you can do something like:

    int[][] myArr = new int [4][];
    for(int i = 0; i < myArr.length; i++){
        myArr[i]= new int[i+1];
    }
    System.out.println(Arrays.deepToString(myArr));

Upvotes: 4

Related Questions