Nico Nico - 2 months ago 7
C Question

do-while loop wont exit in C

Ok, I'm sorry in advance, I know there is a thousand examples of how do-while loops work and how to exit them. I swear I've tried them all. For the life of me, I cannot get this to exit when the user enters a 0. There has to be something I'm over-looking. How I got the one to work inside the else if loop but the main one is beyond me. I would appreciate any help or direction.

int main()
{
char connectBoard[6][7];
int i , j;
char c;
int turn = 1;
char player1 = 'x';
char player2 = 'o';
int spot;

for( i = 0; i < 6; i++) //sets up 2D array board
{
for( j = 0; j < 7; j++)
{
c = '.';
connectBoard[i][j] = c;
}
}
for( i = 0; i < 6; i++)// prints out 2D array board
{
for( j = 0; j < 7; j++)
{
printf("%c", connectBoard[i][j]);
}
printf("\n");
}
printf("=======\n");
printf("1234567\n");

do{
if( turn%2 != 0 ) //player1 turn
{
for( i = 5; i < 6; i++)
{
for(j = 0; j < 1; j++)
{
printf(" Player %c, drop your piece in which column (1-7 or 0 to quit): ", player1);
scanf("%d", &spot);
j = spot - 1;
if( connectBoard[i][j] == '.' )
{
connectBoard[i][j] = 'x';
}
else if( connectBoard[i][j] == 'x' || connectBoard[i][j] == 'o' )
{
do
{
i--;
}while(connectBoard[i][j] == 'x' || connectBoard[i][j] == 'o');
connectBoard[i][j] = 'x';
if( i == -1 )
{
printf("***Bad entry, try again: ");
scanf("%d", &spot);
j = spot - 1;
i = 5;
connectBoard[i][j] = 'x';
}
}
turn++;
}
break;
}
printf("\n");
for( i = 0; i < 6; i++)// prints out 2D array board
{
for( j = 0; j < 7; j++)
{
printf("%c", connectBoard[i][j]);
}
printf("\n");
}
printf("=======\n");
printf("1234567\n");
}
if( turn%2 == 0 ) //player2 turn
{
for( i = 5; i < 6; i++)
{
for(j = 0; j < 1; j++)
{
printf(" Player %c, drop your piece in which column (1-7 or 0 to quit): ", player2);
scanf("%d", &spot);
j = spot - 1;
if( connectBoard[i][j] == '.' )
{
connectBoard[i][j] = 'o';
}
else if( connectBoard[i][j] == 'x' || connectBoard[i][j] == 'o' )
{
do
{
i--;
}while(connectBoard[i][j] == 'x' || connectBoard[i][j] == 'o');
connectBoard[i][j] = 'o';
if( i == -1)
{
printf("***Bad entry, try again: ");
scanf("%d", &spot);
j = spot - 1;
i = 5;
connectBoard[i][j] = 'o';
}
}
turn++;
}
break;
}
printf("\n");
for( i = 0; i < 6; i++)// prints out 2D array board
{
for( j = 0; j < 7; j++)
{
printf("%c", connectBoard[i][j]);
}
printf("\n");
}
printf("=======\n");
printf("1234567\n");
}

}while( spot != 0 );




return 0;
}

Answer

After reading the spot variable, you can check if the value is 0 and break:

   printf(" Player %c, drop your piece in which column (1-7 or 0 to quit): ", player2);
   scanf("%d", &spot);
   if (spot == 0)
     return 1;
   j = spot - 1;

and change your do while to a while loop to avoid confusion.