2D Arrays
To find the highest (or lowest) value in a 2D array you keep track of two things at once: the best value found so far, and the position it sits at — its row index and its column index. Begin by copying the very first element into a variable, for example topPoints = points[0][0], and set topRow = 0 and topCol = 0.
Starting from a real element matters. If you started from 0 and every value in the grid were negative, 0 would beat them all and you would report a value — and a position — that never appears in the array.
Nested loops visit each element in turn: the outer loop over the rows, the inner loop over the columns of that row. A single loop only walks along one row, or down one column, so on its own it can never reach every element of the grid. At each element, compare it with the stored value using if. When the new element is higher, replace the stored value and update the row and column indexes in the same step — updating the value but forgetting the indexes leaves you pointing at the wrong cell.
In this program the array holds the scores of three players at an arcade machine over three rounds.
points = [[18, 24, 9], [31, 12, 40], [7, 26, 15]]
topPoints = points[0][0]
topRow = 0
topCol = 0
for r in range(len(points)):
for c in range(len(points[r])):
if points[r][c] > topPoints: # found a bigger score
topPoints = points[r][c]
topRow = r
topCol = c
print("Best score:", topPoints, "at row", topRow, "column", topCol)Output:
Best score: 40 at row 1 column 2The 40 in row 1, column 2 is never beaten, so the program reports 40 at row 1, column 2. The first element only sets the starting values, so it is never higher than itself; after that, each element is compared with the best score so far.
| Element checked | Index | Higher than stored? | Stored value | Stored position |
|---|---|---|---|---|
| 18 | [0][0] | no | 18 | row 0, column 0 |
| 24 | [0][1] | yes | 24 | row 0, column 1 |
| 9 | [0][2] | no | 24 | row 0, column 1 |
| 31 | [1][0] | yes | 31 | row 1, column 0 |
| 12 | [1][1] | no | 31 | row 1, column 0 |
| 40 | [1][2] | yes | 40 | row 1, column 2 |
| 7 | [2][0] | no | 40 | row 1, column 2 |
| 26 | [2][1] | no | 40 | row 1, column 2 |
| 15 | [2][2] | no | 40 | row 1, column 2 |
For the lowest value, use exactly the same structure with < instead of >, and still start from the first element rather than from zero.
OCR GCSE Computer Science · 2D Arrays