# init and draw not working properly in pset3 fifteen

I can not find my mistake, but there is something wrong obviously either with init or with draw:

My code for init is:

``````void init(void)
{
if (d%2 != 0)
{
for (int i = 0; i < d; i++)
{
int z = (d*d) - 1;
for (int j = 0; j < d; j++)
{
board[i][j] = z;
z--;
}
}
}
else
{
int temp = board[d-1][d-2];
board[d-1][d-2] = board[d-1][d-3];
board[d-1][d-3] = temp;
}
}
``````

then my draw code is:

``````void draw(void)
{
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == 0)
{
printf("%2c", '_');
}
else
{
printf("%2d", board[i][j]);
}
}
printf("\n");
}
}
``````

then the output for fifteen 3 is:

``````8 7 6
8 7 6
8 7 6
``````

Not sure what is wrong...

Also, not sure how to insert properly my code in the questions sections, so that to be displayed correctly....

Thanks!

your init function is incorrect as noted @Matt Obert.

``````if (d%2 != 0)
{
for ....
}
``````

if d = 4, for example, your function init will not doing nothing at all, since board [d-1] [d-2]; It not even initialized to a valid value.

``````int z = (d*d) - 1;
``````

Nor is housed in the right place, at each iteration of i (suppose the loop has three iterations) you do z = 8, in the innermost loop you decrement z into three units, hence your output 8 7 6, 8 7 6 ....., you must initialize z outside for. Ultimately in init you should only use two FOR loops, not an IF-ELSE condition, in the innermost loop impose a condition

``````if ((d * d)% 2 == 0)
``````

where we swap the desired values, not a literal swapped is necessary, a simple assignment is sufficient

Your `init()` function is to blame. (I think `draw()` looks OK.) Make sure that your `for (int i)` and `for (int j)` loops execute whether your grid is even or odd. I recommend moving the test for modulo 2 inside the `for()` loops.

• got it, thanks! Jul 29 '16 at 13:30