Can you please tell me what this code does specifically? How does it work?

void init(void) {

int total = d * d; 

for (int i = 0; i < d; i++)
    for (int j = 0; j < d; j++)
        board[i][j] = --total;


I'm really struggling with Game of Fifteen.

I just don't know where to start so I found the first part of a solution and have decided to make sure I know it in and out before moving on. I need to understand it as opposed to just copying it.

I don't understand how this works though.

I'm assuming this populates the array with variables, but I'm not sure how. On the first pass through the for loop, both i and j will be 0 right? So the first value will be: board[0][0] which if --total (assuming total is 9), it will be value no. 8?

But then on the second pass through, if both i and j are incremented by 1, then the next array value is board[1][1], as opposed to [0][1] or even [1][0] right? I'm really confused, please walk me through this code!


You're mostly right, but have a couple of misconceptions.

First --total. The two minus signs that precede it mean to decrement it by 1 before processing the rest of the line. If the two minus signs had followed it instead, it would mean to process the line with the current value of the variable and then decrement. So, that means that the value used is 8, not 9.

Next, you need to better understand the concept of nested for loops. The inner loop will execute completely before the outer loop increments to the next value. Then, the inner loop will cycle through again. In this case, assuming d=3, the i,j progression is 00, 01, 02, 10, 11, 12, 20, 21, 22, end. It is not 00,11,22... or anything else. If you still don't follow, a review of the class lectures and the shorts on for loops would be useful.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • So if after the inner gets incremented first, it becomes board[0][1] and then it has --total (7) assigned to it. Then the outer loop is then incremented so it now becomes [1][1], which surely skips [1][0], how does [j] get decremented back to zero for [1][0] and [2][0]? Sorry for the hassle. – gloopit Jul 6 '16 at 16:29
  • no, the inner loop increments from 0 to 1 to 2 and exits. When it exits the inner loop, the outer loop increments once and the inner loop starts over, 0,1,2,exit, and so on. Put the following statement inside your inner loop following the board[][] assignment, compile and run: printf("i=%i, j=%i, total = %i\n", i, j, total); – Cliff B Jul 6 '16 at 16:34
  • awesome, thank you so much, Cliff – gloopit Jul 6 '16 at 16:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .