Tuesday, November 2, 2010

2D Array Practice

In the book C Programming a Moder Approach Second Edition there is a programming project at the end of chapter 8 that asks you to write a program that creates a randomized walk across a 10x10 field, where each step is shown as a letter from the alphabet, and each blank space is shown as a period. The end result should look something like this:

a . . . . . . . . .
b c . . . . . . . .
e d . . . p q r . .
f . . . . o . s . .
g h i j . n u t . .
. . . k l m v . . .
. . . . . . w . . .
. . . . z y x . . .
. . . . . . . . . .
. . . . . . . . . .

In order to do this, you initialize a 2D array, fill it with periods, randomly choose a number between 0-3 to represent a direction to move, detect if the move was a valid move (and re-randomize the move if it wasn't), then make the move chosen. Each time a move is chosen, use a new letter from the alphabet.

Overall, this was extremely simple. If I were writing this program without such specific rules as the programming book gave me, I would have made the array 12x12 instead of 10x10. This would allow me to line the edges with a value other than ".", and I could use that value on the edges to detect collision. This is a lot simpler than detecting if it is the edge of the array, since I can't simply use if board[y][x + 1] != '.', as a period can't exist out of the edge of the arrays.

I'll post the source code the most interesting part of the program:

for (column = 0; column < 10; column++)
  for (row = 0; row < 10; row++)
    printf("%c ", board[column][row]);

This cycles through the first row, and prints out all the contents. It does this by adding one to column during each iteration, and printing out a piece of the board using the token column as a coordinate. The same thing happens with the row token as well. Then, the next row, and the next row. Just before these two for loops I modify the current field and place a letter in wherever the current coordinates are, so that these two loops print out the move that just occurred as a letter.

Overall I didn't learn anything new, but I still needed to write this program in order to get used to the syntax of C. Here is the source and .exe for the full program.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.