0

I don't understand the logic behind this code please explain it.

class TwoDAgain { 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]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<i+1; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<i+1; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } }

18th Apr 2019, 5:41 AM
Abhinav Joshi
Abhinav Joshi - avatar
1 Answer
+ 1
// Create a 2 dimension array with 4 rows // each row has different number of column int twoD[][] = new int[4][]; twoD[0] = new int[1]; // row 0 - 1 column twoD[1] = new int[2]; // row 1 - 2 column twoD[2] = new int[3]; // row 2 - 3 column twoD[3] = new int[4]; // row 3 - 4 column int i, j, k = 0; /* * <i> and <j> are loop iterators * <k> is the number to print * Outer loop goes from 0 to 3 (rows) * Inner loop goes from 0 to <i> (columns) <i> = 0, <j> ranges from 0 to 0 i j k twoD[0][0] = 0 <i> = 1, <j> ranges from 0 to 1 i j k twoD[1][0] = 1 twoD[1][1] = 2 <i> = 2, <j> ranges from 0 to 2 i j k twoD[2][0] = 3 twoD[2][1] = 4 twoD[2][2] = 5 <i> = 3, <j> ranges from 0 to 3 i j k twoD[3][0] = 6 twoD[3][1] = 7 twoD[3][2] = 8 twoD[3][3] = 9 */ for(i=0; i<4; i++) for(j=0; j<i+1; j++) { twoD[i][j] = k; k++; } // Next loops uses similar logic, but for showing values.
18th Apr 2019, 8:32 AM
Ipang