C Program to Calculate Grid Size, Initialized Number onto tile, Initialize Tile Loop and If Grid is Even, Swap The Tiles Numbered 1 and 2

How to write a C Program to Calculate Grid Size, Initialized Number onto tile, Initialize Tile Loop and If Grid is Even, Swap The Tiles Numbered 1 and 2 in C Programming Language ?

Solution For C Program:
/*C Program to Calculate Grid Size, Initialized Number onto tile, Initialize Tile Loop and If Grid is Even, Swap The Tiles Numbered 1 and 2*/

void init(int gamegrid[][DIM_MAX], int side_len)
{
    // calculate grid size
    int grid_area = side_len * side_len;
    // number being initialized onto tile
    int tile_num = grid_area - 1;
   
    // initialize tile loop
    for(int y = 0; y < side_len; y++)
    {
        for(int x = 0; x < side_len; x++)
        {
            // initialize tile
            gamegrid[y][x] = tile_num;
            tile_num--;
        }  
    }
   
    // if grid is even, swap the tiles numbered 1 and 2
    if(grid_area % 2 == 0)
        {
            gamegrid[side_len - 1][side_len - 3] = 1;
            gamegrid[side_len - 1][side_len - 2] = 2;
        }
}


Learn More :