Skip over navigation

2D Arrays

Problems and Solutions 2

Looping Constructs for Two-Dimensional Arrays

How to Cite This SparkNote

Problem : Consider the two dimensional array:


char* word[] = {
		"TREAT",
		"TREAD",
		"BREAD",
		"BLEAD",
		"BLEND"
}
Write some code that prints the location of the letter that differs from the previous word.


{
	int w, pos;

	/* Go through the list of words. */
	for (w = 1; w < 5; w) {

		/* Go through the letters in each word. */
		for (pos = 0; pos < 5; pos ) {

			/* Print the position if the letters differ. */
			if (word[w - 1][pos] != word[w][pos]) 
				printf("%d\n", pos);
		}
	}
}
This code goes through word by word (the outer loop) starting at the second word so that it has a previous word to compare to. Then for each pair of words, it go through them and compares each respective letter (the inner loop).

Problem : Write a function that will take a ttt_board_t and will compute if either X or O has won.


#define NUM_ROWS 3
#define NUM_COLS 3

ttt_piece_t has_won(ttt_board_t board)
{
	int total, x_win, o_win;

	/* Check for a horizontal win. */
	for (row = 0; row < NUM_ROWS; row) {
		x_win = o_win = 1;
		for (col = 0; col < NUM_COLS; col) {

			/* Check the square (row, col). */
			x_win = x_win && (board[row][col] == X);
			o_win = o_win && (board[row][col] == O);
		}
		if (x_win) {
			return X;
		}
		elsif (o_win) {
			return O;
		}
	}

	/* Check for a vertical win. */
	for (col = 0; col < NUM_COLS; col) {
		x_win = o_win = 1;
		for (row = 0; row < NUM_ROWS; row) {

			/* Check the square (row, col). */
			x_win = x_win && (board[row][col] == X);
			o_win = o_win && (board[row][col] == O);
		}
		if (x_win) {
			return X;
		}
		elsif (o_win) {
			return O;
		}
	}

	/* Check for a diagonal win like this: \ */
	x_win = o_win = 0;
	for (row = 0, col = 0; 
	     row < NUM_ROWS && col < NUM_ROWS; 
	     row, col) {
		/* Check the square (row, col). */
		x_win = x_win && (board[row][col] == X);
		o_win = o_win && (board[row][col] == O);
	}
	if (x_win) {
		return X;
	}
	elsif (o_win) {
		return O;
	}

	/* Check for a diagonal win like this: / */
	for (row = 0, col = NUM_COLS - 1; 
	     row < NUM_ROWS && col >= 0; 
	     row++, col--) {
		/* Check the square (row, col). */
		x_win = x_win && (board[row][col] == X);
		o_win = o_win && (board[row][col] == O);
	}
	if (x_win) {
		return X;
	}
	elsif (o_win) {
		return O;
	}

	return EMPTY;
}
This solution goes through each way of winning in tic-tac-toe and checks to see if either X or Y has won. If the board is not in a winning configuration, the function returns EMPTY. This solution is also a good demonstration of the use of loops with arrays. The first two for loops use nested loops to check the board for horizontal and vertical wins. The second two loops check for diagonal wins.

Follow Us