user1767077
user1767077

Reputation: 117

For loop with 2 dimensional array in c++

int count = 0;
for(int x = 1; x < 79; x++)
{
    for(int y = 1; y < 21; y++)
    {
        char surroundingCells[] = {arr[x-1][y-1], arr[x][y-1], arr[x-1][y], arr[x+1][y+1], arr[x+1][y-1], arr[x-1][y+1], arr[x][y+1], arr[x+1][y]};
        for(int z = 0; z < 8; z++)
        {
            if((surroundingCells[z] == 'x' || surroundingCells[z] == 'd') && arr[x][y] == 'x')
                count++;
            else if((surroundingCells[z] == ' ' || surroundingCells[z] == 'l') && arr[x][y] == ' ')
                count++;
        }
        if(arr[x][y] == 'x' && (count != 2 || count != 3))
            arr[x][y] = 'd';
        else if(arr[x][y] == ' ' && count == 3)
            arr[x][y] = 'l';
        count = 0;
    }
}

when i print the array after this code is run all the places where there was an x has a 'd' but that shouldnt occur some instances allow for an 'x' to remain. Can someone see my logical error?

Upvotes: 0

Views: 371

Answers (1)

jonhopkins
jonhopkins

Reputation: 3842

Your code is making it so every instance of 'x' is being changed to 'd'. On the line

if(arr[x][y] == 'x' && (count != 2 || count != 3))

the condition always evaluates to true when arr[x][y] is 'x'. If count is 2, then it is not 3, and if it is 3, then it is not 2. So the program is always entering this block when arr[x][y] is 'x'. If you want it to not change to 'd' whenever count is 2 or 3, then change that line to

if(arr[x][y] == 'x' && (count != 2 && count != 3))

Upvotes: 4

Related Questions