int[ ][ ] num=new int[5][ ];
num[0]=new int[1];
num[1]=new int[5];
num[2]=new int[];
num[3]=new int[3];
Can a jagged array be printed in one loop or are two loops needed ?
int[ ][ ] num=new int[5][ ];
num[0]=new int[1];
num[1]=new int[5];
num[2]=new int[];
num[3]=new int[3];
Can a jagged array be printed in one loop or are two loops needed ?
You could avoid writing the inner loop by using Arrays.toString()
.
for(int[] row: num) {
System.out.println(Arrays.toString(row));
}
But your code isn't actually faster. Its still using a for loop under the hood.
void printRaggedArray(int[][] ragged) {
int outer = 0;
int inner = 0;
while(outer < ragged.length) {
if(inner >= ragged[outer].length) {
inner=0;
outer++;
continue;
}
System.out.println[outer][inner++];
}
}
This works, but 2 loops is better. This is no faster, in fact it's probably slower.
public class Main {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
for (int i = 0; i < 4; i++){
for (int j = 0; j < i + 1; j++) {
twoD[i][j] = i + j;
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < i + 1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Two loops are needed; one to loop over the array of arrays and one to loop over each nested array and print the appropriate element. You can also simply use
Arrays.deepToString()
(which uses loops internally):