A particular element of a 2 D array table is referenced by specifying its row

# A particular element of a 2 d array table is

This preview shows page 5 - 8 out of 12 pages.

A particular element of a 2-D array, table, is referenced by specifying its row and column indexes: table[RowIndex][columnIndex] For example, given the declaration: int table[3][4]; The following stores 64 in the cell with row index 1, column index 3. table[1][3] = 64; We use the same format to refer to an element in an expression: table[2][3] = table[1][3] + 2;
6 Initialization of 2-D Arrays As with 1-D arrays, if we already have the values to assign to the array at the point of declaration, then we can declare and initialize the 2-D array at the same time. The format is similar to 1-D array initialization except that a nested list is used, where each inner list represents a row. For example, the following declares and initializes our table. int table[3][4] = { {1,2,2,1}, {3,4,4,3}, {5,6,6,5} } Like 1-D array, if you provide less values than the declared size, the remaining cells are set to zero. However, unlike 1-D array where you can skip the size, here you must give at least the number of columns. int table[][4] = { {1,2,2,1}, {3,4,4,3}, {5,6,6,5} } //OK int table[][] = { {1,2,2,1}, {3,4,4,3}, {5,6,6,5} } //WRONG!
7 Processing 2-D Arrays To process 2-D array, we need to extend the loop we normally use with 1-D array to nested loops. This can be done either row-wise or column-wise. To process the elements row-wise, we use: for(int rowIndex = 0; rowIndex < ROWS; rowIndex++){ //process row# rowIndex; } But processing a row involves processing each element of that row; so the complete algorithm is: for(int rowIndex = 0; rowIndex < ROWS; rowIndex++){ // process row# rowIndex for(int columnIndex = 0; columnIndex < COLUMNS; columnIndex++) //process element array[rowIndex][columnIndex] } To process elements of a 2-D array column-wise, we use: for(int columnIndex = 0; columnIndex < COLUMNS; columnIndex++){ // process column# columnIndex for(rowIndex = 0; rowIndex < ROWS; rowIndex++) process element array[rowIndex][columnIndex] }

#### You've reached the end of your free preview.

Want to read all 12 pages?

• Spring '10
• baleh
• Array, #include, #define, The Elements, actual size, 2-d array