Write a C program that generates a random walk across a 10x10 array. Initially, the array will contain only dot characters. The program must randomly “walk” from element to element, always going up, down, left, or right by one step. The elements visited by the program will be labeled with the letters A through Z, in the order visited.
It doesn't take the walk to an element that has already a letter assigned (blocked element).If all four directions are blocked, the program must terminate.
I wrote the code for the above question but sometimes the output is just blank, it is just showing a black screen.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char visited = 'A';
char a[10][10];
// assigning value '.' to array elements
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
a[i][j] = '.';
// the initial is set for the player.
int playeri, playerj;
srand(time(0));
// assigning numbers between 0-9
playeri = rand() % 10; playerj = rand() % 10;
a[playeri][playerj] = visited++;
int move;
// now to move the player
while (visited <= 'Z') {
// to generate numbers between 1-4
move = rand() % 4 + 1;
// to move up
if (move == 1) {
if (a[playeri - 1][playerj] == '.' && playeri != 0) {
playeri = playeri - 1;
a[playeri][playerj] = visited++;
}
}
// to move down
else if (move == 2) {
if (a[playeri + 1][playerj] == '.' && playeri != 9) {
playeri = playeri + 1;
a[playeri][playerj] = visited++;
}
}
// to move right
else if (move == 3) {
if (a[playeri][playerj + 1] == '.' && playerj != 9) {
playerj = playerj + 1;
a[playeri][playerj] = visited++;
}
}
// to move left
else if (move == 4) {
if (a[playeri][playerj - 1] == '.' && playerj != 0) {
playerj = playerj - 1;
a[playeri][playerj] = visited++;
}
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
printf("%c", a[i][j]);
}
printf("\n");
}
}
My guess is that the program is stuck in an infinte loop, if so, how do I solve this problem?