2D Arrays


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 {
	EMPTY,
	X,
	O
} 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.

Take a Study Break

SparkLife

Star Trek gets SEXY

Chris Pine and Zoe Saldana heat up the red carpet!

SparkLife

Are you afraid of relationships?

Auntie SparkNotes can help!

SparkLife

Wanna get JLaw's gorgeous glow?

Click here for simple, sexy makeup tricks!

SparkLife

Sexy starlet style

See every single look from the Met Gala!

SparkLife

Who'd be on your zombie-apocalypse crew?

We already dib'sed Genghis Khan.

Geek out!

The MindHut

Geeky Actresses: Then and Now

Before the fame!

The MindHut

9 Scientific Inaccuracies in Iron Man 3

Click to see what they got wrong.

The MindHut

Top 10 Predictions Sci-Fi Got WRONG

So wrong, they're WRONG.

The MindHut

The 15 Most Awesome Robots, Ever

These Robots Rock!

The MindHut

If You Like Game of Thrones...

...Then you'll LOVE these books!

The Book

Cover image

Read What You Love, Anywhere You Like

Get Our FREE NOOK Reading Apps