revised: 01/13/2008, 07/04/2017
These puzzles involve 2D arrays. The dimensions of an array are given as row followed by column. A 3x5 array has 3 rows and 5 columns. Conceptually a 3x5 array looks like this:
Column | |||||
---|---|---|---|---|---|
row | 0 | 1 | 2 | 3 | 4 |
0 | 0 | 1 | 2 | 3 | 4 |
1 | 5 | 6 | 7 | 8 | 9 |
2 | 10 | 11 | 12 | 13 | 14 |
If an array has R rows, the rows are indexed 0 ... R-1
.
And if it has C columns, the columns are indexed 0 ... C-1
.
Of course, row and column numbers are not stored as part of the array in main memory.
Arrays are stored in main memory in row-major order,
which means that the elements of a row are stored in sequence
in memory.
The elements of the array are stored in a contiguous
block of memory, as follows
(assume that memory addresses increase to the right):
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
Because of this, code that accesses every element of a 2D array should be written so that elements are accessed in sequence through memory:
for ( r=0; r<Number_Of_Rows; r++ ) { for ( c=0; c<Number_Of_Columns; c++ ) { ... do something with element[r][c] ... } }