#include <stdio.h>
#define ROWS 2
#define COLS 5
int main(void)
{
unsigned int rooms[ROWS][COLS] = {0}, selection, building, room;
int i, j;
for(i = 0; i < ROWS; i )
{
for(j = 0; j < COLS; j )
{
if(rooms[i][j] == 0)
{
rooms[i][j] = 1;
printf("\nBuilding[%.2d]|Room[%.2d]: Reservation Succesfull.\n\n", i 1, j 1);
break;
}
}
}
return 0;
}
Note that this is not the full code and i only have a problem with this part.
What i want here is to check the first 0 that comes first and turn it into a 1. This will happen until all the 0 become 1 or until the user exits the program. I already made a "do while" for that. My problem is that when i run this part of the program it puts 1 both on ROWS 0 and ROWS 1 at the same time. I'm looking for why is this happening more than an answer to fix the program.
I made some tests like putting another if for the first loop(i) but that either resulted in the same problem or the whole ROWS 1 was skipped and only the ROWS 0 was filled.
CodePudding user response:
It is because the break statement just gets out of the first outer loop, it seems like you also want to skip the other outer one. You may need to add a flag to check only one 0 element will be changed to 1, or just change break into return to get out of the function as it is said on the comments.
int flag = 0;
for(i = 0; i < ROWS; i )
{
for(j = 0; j < COLS; j )
{
if(rooms[i][j] == 0)
{
flag = 1;
rooms[i][j] = 1;
printf("\nBuilding[%.2d]|Room[%.2d]: Reservation Succesfull.\n\n", i 1, j 1);
break;
}
}
if(flag == 1)
{
break;
}
}
Or with a clear explicit initialization of the matrix,
void func(void)
{
unsigned int rooms[ROWS][COLS] = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0}
}, selection, building, room;
int i, j;
for(i = 0; i < ROWS; i )
{
for(j = 0; j < COLS; j )
{
if(rooms[i][j] == 0)
{
rooms[i][j] = 1;
printf("\nBuilding[%.2d]|Room[%.2d]: Reservation Succesfull.\n\n", i 1, j 1);
return;
}
}
}
}