cfor-loopswitch-statementoffsetalternate

How do I use a switch to offset the start of a for loop?


I am trying to make a game of checkers, and right now I'm building the board. The board is a 2-dimensional array of integers that I'm changing based on where the pieces should be.

    // Sets up Red Pieces
int k = 0;
for (i = 0; i < 3; i++)
{
    
    for (j = k; j < 8; j += 2)
    {
        // Red piece is on square at coords [i][j]
        Board_Squares[i][j] += 2;

    }
    printf("\n");

    // k starts at 0, and in switch should alternate between 1 and 0, 
    switch (k)
    {
    case 0:
        k = 1;
    case 1:
        k = 0;
    }
} 

However, this code only gives me this:

0 2 0 2 0 2 0
0 2 0 2 0 2 0
0 2 0 2 0 2 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

Any help would be dope. Warning: I might be dumb.

Also, is using the switch statement the right move here anyways?


Solution

  • the problem in your code comes from missing break statements: the code for a case fall through to the code for the next case.

    Modify it this way:

        switch (k) {
          case 0:
            k = 1;
            break;
          case 1:
            k = 0;
            break;
        }
    

    The same toggling effect can be obtained with simple expressions:

    Or some more convoluted and obscure ones:

    The checker board cells can also be initialized directly to 0 and 1 as:

    Board_Squares[i][j] = (i + j) & 1;