Search Menu


Looping Constructs for Two-Dimensional Arrays

Like one dimensional arrays, arrays of multiple dimensions easily lend themselves to use in loops to access the data elements in the array. Rather than using a single loop to access the data it will usually help to use a nested loop. More generally, you will normally use n loops for an n-dimensional array.

To illustrate how you might use a nested loop construct to go through all of the data a two-dimensional array, we will show how you might initialize a tic-tac-toe board. First assume that you have the following type defined for piece.

typedef enum {
} ttt_piece_t;

Now we can declare an array to represent the board. It should have the appropriate number of rows and columns.

piece_t board[NUM_ROW][NUM_COL]

What remains is to loop through all of the cells in the array. You can imagine doing this by going through each row successively and within each row going across each of the columns and initializing each cell. If this is the approach you might use an outer for loop to iterate through the rows. Whatever is inside that for loop will be done on each row. The action we want to perform on each row is to iterate across each column. This action corresponds to the inner for loop below:

for (r = 0; r < NUM_ROW; r) {
	for (c = 0; c < NUM_COL; c) {
		board[r][c] = EMPTY;

We could just as easily have had the outer loop iterate across the columns and the inner loop iterate down the rows. Both work just as well when you merely want to perform some action on all of the cells. There are other cases where you might want to go through the two dimensional array in one manner as opposed to the other, depending on the task.