I'm a new C learner and currently solving problems from
"C Programming: A Modern Approach "
The goal of the problem is to write a program that print a 10*10 array.
Starting from the up left corner , take one step at a time in only four directions(up, down, left, right),and can't go outside the 10*10 nor going backwards. The steps are represented by A~Z.
Here is my code:
Code:
#include<stdio.h>#include<stdlib.h>
#include<time.h>
#define ROW 10
#define COLUMN 10
int main()
{
char board[ROW][COLUMN], movement;
int n, i, j, current_row = 0, current_column = 0, randnum, step;
//Building board
for (i = 0; i < ROW; i++) {
for (j = 0; j < COLUMN; j++) {
board[j] = '.';
}
}
srand((unsigned) time(NULL));
movement = 'A';
board[current_row][current_column] = movement;
//Moves
while (movement < 'Z') {
for (;;) {
randnum = rand() % 4;
switch (randnum) {
case 0:
if ((current_row - 1) < 0
|| board[current_row - 1][current_column] != '.')
break;
else
current_row -= 1;
break;
case 1:
if ((current_row + 1) > 9
|| board[current_row + 1][current_column] != '.')
break;
else
current_row += 1;
break;
case 2:
if ((current_column - 1) < 0
|| board[current_row][current_column - 1] != '.')
break;
else
current_column -= 1;
break;
case 3:
if ((current_column + 1) > 9
|| board[current_row][current_column + 1] != '.')
break;
else
current_column += 1;
break;
default:
break;
}
if (board[current_row][current_column] == '.')
break;
if (board[current_row - 1][current_column] != '.'
&& board[current_row + 1][current_column] != '.'
&& board[current_row][current_column - 1] != '.'
&& board[current_row][current_column + 1] != '.')
goto PRINT;
}
++movement;
board[current_row][current_column] = movement;
}
//Print board
PRINT:
for (i = 0; i < ROW; i++) {
for (j = 0; j < COLUMN; j++) {
printf(" %c", board[j]);
if ((j + 1) % 10 == 0)
printf("\n");
}
}
return 0;
}
One out of five times i run the program, it stops as if it can't jump out of the loop and freezes. I've reread the code several times but still couldn't spot the problem. Can any help?