Multidimensional Arrays
Can someone explain these to me please. int[][] arr = new int[5][10] I understand the above but I dont understand what comes after that. When you iterate through the array to get certain values I get very confused. Please help, thx
3/10/2018 12:07:42 AM
Tim Millar
9 Answers
New AnswerIt's just the initialisation of multidimentionnal array. 5 and 10 is the length of array. For now, array are empty.
int[][] arr = new int[5][10] Creates an array of 5 rows and 10 columns. To search the array for a certain value, you loop over the rows, then the columns: for(int r=0; r<5; r++) { for(int c=0; c<10; c++) { if(arr[r][c] == value) { //do something } //else keep looking } //end of columns } //end of rows You use the same kind of loop to fill the array, print out every value of the array, any sort of processing of data in the array.
think of it like arr[rows][columns] 5 rows of 10 values for ( int i = 0; i < 5; i++ ) for ( int j = 0; j < 2; j++ ) { cout << "arr[" << i << "][" << j << "]: "; cout << a[i][j]<< endl; }
java is similar I guess, was looking for java answer but the loop process is the same just not the cout stuff. iam still confused but thx to all who helped thus far
think of it as a list inside a list. So, int[][]_2D_array = new int[m][n] would mean an (empty) array (_2D_array) of size m*n that will contain two lists/arrays. You'll need 2-loops (for loop is common) to access elements in _2D_array. The first tracks indices of first list ([m]) and the second loop handles that of [n]. You could print a matrix of M x N with this logic