So this has been a little frustrating. Even though the rest of the problem went well I cannot figure out where I went wrong. Here's the idea; set a counter called value that increments by every time to check for numbers 1, 2, 3, 4 ... in the correct order. There is an exception that, once reaching the bottom right corner (the blank) simply returns true. This is based one the assumption that once the for-loop gets to that point, everything else must be sorted. If the loop encounters a number on board [i][j] that is not equal to the value it should have, it returns false. When I test this with ./fifteen 3 < ~cs50/pset3/3x3.txt I get stuck in an infinite loop. All the other functions work properly. I have tested them all separately in a test file. Any pointers would be greatly appreciated!

bool won(void)
    int value = 1;
    for (int i = 0; i < d; i++){
        for (int j = 0; j < d - 1; j++){
            if (i == d-1 && j == d-1){
                goto true_statement;
            } else if (board[i][j] != value){
                return false; 
            } else{
    return true;

1 Answer 1


Why do you loop till j < d - 1 not j < d? For board 3*3, you miss board[0][2] so should return false for board[1][0].

However, I do not understand why you are stack in an infinite loop. You should return false. I suspect that something else might be wrong with your code.

Also, please note that by most programmers goto is considered as bad style.

  • That was simple, yet very effective advice. Thank you so much. The d-1 was a remnant of an earlier version of my code, where I interated over the array up to, but not including the the last entry, since I knew that had to be blank. That code was, however (for obvious reasons) defective, so I changed it to the "if (i == d-1 && j == d-1)" solution. I must have simply forgotten to delete the d - 1. Sometimes it's really helpful to have a second pair of eyes to detect these kind of silly mistakes. I was only stuck in an infinite loop when feeding the program the solution, like so: Commented Jul 8, 2017 at 9:22
  • ./fifteen 3 < ~cs50/pset3/3x3.txt Hence, this problem was solved as well. As for the goto. That was a simple solution I found to exiting out of both for-loops at the same time. What would be a better way to do so? Would I simply but the "return true;" there? Again, thank you so much for your help! Commented Jul 8, 2017 at 9:24
  • yes, just simple "return true". and "return false" in the very end, to avoid compiling error.
    – obesman
    Commented Jul 8, 2017 at 9:51

You must log in to answer this question.

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