I successfully solved a programming project from a book named "C Programming: A modern approach" by K.N. King.
The program works fine but goes into endless loop sometimes. I am not getting the reason behind this.
I used a random function which will give random values ranging from 0 to 3 and I have used sufficient conditions to handle all the four random values.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char walk[10][10];
int direction,currenti=5,currentj=5;
int i,j;
for(i=0; i<10; i++)
{
for(j=0; j<10; j++)
{
walk[i][j]='.';
}
}
srand((unsigned) time(NULL));
for(i=0; i<26;)
{
direction=rand()%4;
printf("%d ",direction);
if(direction==0&&walk[currenti][currentj-1]=='.'&&(currentj-1)>0&&(currentj-1)<10)
{
currentj=currentj-1;
walk[currenti][currentj]='A'+i;
i++;
}
else if(direction==1&&walk[currenti][currentj+1]=='.'&&(currentj+1)>0&&(currentj+1)<10)
{
currentj=currentj+1;
walk[currenti][currentj]='A'+i;
i++;
}
else if(direction==2&&walk[currenti-1][currentj]=='.'&&(currenti-1)>0&&(currenti-1)<10)
{
currenti=currenti-1;
walk[currenti][currentj]='A'+i;
i++;
}
else if(direction==3&&walk[currenti+1][currentj]=='.'&&(currenti+1)>0&&(currenti+1)<10)
{
currenti=currenti+1;
walk[currenti][currentj-1]='A'+i;
i++;
}
}
for(i=0; i<10; i++)
{
for(j=0; j<10; j++)
{
printf("%c ",walk[i][j]);
}
printf("\n");
}
return 0;
}
Only having a quick look, my guess would be because in your main for
loop, you only increment i
on certain conditions, and it is likely that none of them or met, which means i++
would then not be called.
Best way to verify this would be to put an else
clause where you handle the case properly, by printing a message, or putting an assert if you should never reach that case.
As a measure of precaution, when you have if
/else if
clauses, you should always have an else
clause where you handle the "if all else fails" value, where you either handle the error properly, or assert if the code should never reach the else clause.
Also, as a side note, you should consider using spaces in order to make your code a bit easier to read, such as:
if (direction == 3 && walk[currenti + 1][currentj] == '.' && (currenti + 1) > 0 && (currenti + 1) < 10)