Reputation: 173
Write the code required to allocate a ragged 2-D int array such that the first row has space to store 1 value, the second row can store 2 values, the third row has space to store 3 values, etc. up until the 50th row which has space to store 50 values.
I know for the above question I have to essentially create a pyramid with a 2 dimensional array. I don't really know how to manipulate 2D arrays, any help will be great. This is my code thus far, not sure how to allocate space like the question above says:
import java.util.Arrays;
public class Ragged2D {
public static void main(String[] args) {
int[][] boo = new int[50][];
for(int i = 0; i < boo.length; i++){
for(int k = 0; k< boo[i].length; k++){
}
}
System.out.println(Arrays.toString(boo));
}
}
Upvotes: 2
Views: 2552
Reputation: 539
I guess this is what you need
int[][] boo = new int[50][];
for (int i=0;i<50;i++) {
boo[i] = new int[i+1];
}
This way boo[0] can contain 1 element (boo[0][0]), boo[1] can contain 2 elements (boo[0][0] and boo[0][1]) etc.
Upvotes: 1
Reputation: 393936
This is how you initialize a row of the 2D array:
public static void main(String[] args) {
int[][] boo = new int[50][];
for(int i = 0; i < boo.length; i++){
boo[i] = new int[i+1]; // initialize the i'th row to have i+1 elements
for(int k = 0; k< boo[i].length; k++){
boo[i][k] = ...
}
}
System.out.println(Arrays.deepToString(boo)); // this change is required to print 2D array
}
Upvotes: 1