# Proceeding in fifteen move function with five if and else-if segments?

I am at the move function within fifteen. I plan to do four if, else-if functions for each of four possible moves. The first

``````bool move(int tile)
{
for (int i=0; i < d; i++ )
{
for (int j=0; j<d; j++, k--)
{
if(board[i][j]==tile)
{
if (board[i-1][j]==0) \\ for situation that there is a blank to the left of the chosen tile
{
tile2 = board[i-1][j];
board[i-1][j]=tile;
board[i][j]= tile2
}

else if (board[i+1][j]==0) \\ for situation that there is a blank to the right of chosen tile
{
\\same code as above
}
.
.
.
\\ check other two directions and use fifth else if for situation that an invalid tile was chosen.
``````

Before I proceed, I would like to know if there are any glaring errors in my plan?

Overall, you have the right idea, but there are is a major issue in your code.

`if (board[i-1][j]==0)` There's an issue with this and every other `if` statement you use to check the tiles. To find this issue, think of what the board looks like when `d` is equal to 3.

``````     
 8   7   6
 5   4   3
 2   1   _
``````

After a few moves, the player's board looks like this:

``````     
 8   _   7
 5   4   6
 2   1   3
``````

The player wants to swap the underscore with 8, which is to the left of the underscore. Assuming you checked for the left-swapping the same you did with your other checks, the result of inputting 8 as the tile to move would be:

``````     
 _   _   7
 5   4   6
 2   1   3
``````

Now we have two underscores when we should only have one. The tile 8 was at board. When you wanted to swap to the left, `board[i - 1][j]` would've equaled `board[-1]`, which is out of the board's constraints. Most of the time, the system won't generate an error, and it'll try to find data in that memory location, which is not inside the array. If that data happens to pass your `if` statement, it will actually swap a tile out of your array. See Game of Fifteen - Move function issue for more.

This is because the swapping doesn't satisfy the board's constraints. Checking to make sure the swapping works with the board's constraints should fix the issue.

If you still have questions, comment below.

• Thanks for the tip. One question that I have is regarding the last scenario, where the 8 is in the position board. Your output suggests that in this instance board[i-1][j] will == 0. Why is this true? – Haim May 22 '17 at 3:49
• Most of the time, the system won't generate an error, but it will try and find the element at board[i-1][j] (which we're saying here is equal to board[-1]). It's going to look at data in that memory location. If that data passes the `if` statement, it will do a swap and actually swap a tile out of the array! (See cs50.stackexchange.com/questions/16339/… if you still have questions.) – SuperNovaCoder May 22 '17 at 11:38