Reputation:
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
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
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