Q: What is wrong with my "won" function I am working on PSET3 of Harvard CS50 online and having problems with the "won" function for CS50 game of fifteen.
The function works fine with a 4x4 grid puzzle but not with 3x3 
The function returns true a couple of steps too early in case of a 3x3.
The function is required to look through a 2D array for numbers in ascending order from 1 to 8 for a 3x3 size game and 1 to 15 in a 4x4 size game with the last element of the array being zero.
My thought process for the code is that i set the counter initially to 1 and check it against the first element of the array. If it matches then increase the counter by 1 and repeat for the next element.
If the counter reaches the total number of elements in the array it returns true and, if the counter does not match the corresponding array element at any time it returns false. 
Can you see what I am doing wrong?
/**
 * Returns true if game is won (i.e., board is in winning configuration)
 * else false.
 */
bool won(void)
{
    // TODO

    int counter = 1;

    for (int i=0; i < d; i++)
    {
        for (int j=0; j < d; j++)
        {
            if (board[i][j] == counter) 
            {
                counter++;
            }
            if (counter == (d*d)) 
            {
                return true;
            }
        }
    }
    return false;
}


A: Your won routine returns true if all the elements are in order, ignoring the element with value zero. Thus, if the elements are:
1 2 3
_ 4 5
6 7 8

Then your code will increment counter when it sees 1, 2, and 3. It will not increment counter when it sees the 0 where _ is shown above. Then it will increment counter when it sees 4, 5, 6, 7, and 8. Then counter is 9, so it equals d*d, and won returns true.
Fundamentally, your won routine is too flexible. At each step, it increments counter if the current element equals counter—but it is passive otherwise. That is, it continues examination even if the desired condition was not met. Since there is only one "winning" position, if any element is out of position, you can return false as soon as you see it.
