I have a simple program that is setup to create a path labled A-Z. Sometimes it works fine, however the default statement on the switch keeps getting accessed and I don't know why. Also sometimes the program just hangs like its in an endless loop. Any help would be great.
Code:
#include <cstdlib>
#include <ctime>
#include <iostream>
#define N 20
#define ALPHA 26
using namespace std;
int main(void)
{
srand((unsigned) time(NULL));
int step, row, col;
char path [N][N];
for (;;)
{
/**** Section 1: Initializes the array to have character '.' ****/
for (row = 0; row < N; row++)
{
for (col = 0; col < N; col++)
path [row][col]='.';
}
/**** End Section 1 ****/
/**** Section 2: Selects the path using character Capital Letters ****/
path [row = rand() % N] [col = rand() % N]= 'A';
for (step = 1; step < ALPHA;)
{
if (path [row +1][col] != '.' && path [row -1][col] != '.'
&& path [row][col +1] != '.' && path [row][col -1] != '.')
break;
switch (rand() % 4)
{
case 0:
if (path [row + 1][col] =='.' && (row + 1) >= 0 && (row + 1) < N)
{
row++;
path [row] [col] = 'A' + step;
step++;
}
else
{
break;
}
case 1:
if (path [row - 1][col] =='.' && (row - 1) >= 0 && (row - 1) < N)
{
row--;
path [row] [col] = 'A' + step;
step++;
}
else
{
break;
}
case 2:
if (path [row][col + 1] =='.' && (col + 1) >= 0 && (col +1) < N)
{
col++;
path [row] [col] = 'A' + step;
step++;
}
else
{
break;
}
case 3:
if (path [row][col - 1] =='.' && (col - 1) >= 0 && (col -1) < N)
{
col--;
path [row] [col] = 'A' + step;
step++;
}
else
{
break;
}
default: printf("something is wrong here %d\n", step);
}
}
/**** End Section 2 ****/
/**** Section 3: Prints the path using character '.' ****/
for (row = 0; row < N; row++)
{
for (col = 0; col < N; col++)
printf("%c ",path [row][col]);
printf("\n");
}
/**** End Section 3 ****/
system("pause");
}
return(0);
}