A chessboard is merely a two-dimensional array — a matrix — one where the rows and columns are the same size. As long as you can write code to output an 8-by-8 board, you can modify the code to reset the board’s size to any value.
When I wrote my solution, I started with code that output a standard 8-by-8 board. I realized that the board was simply the same row repeated 8 times. Here’s the basic row:
--- --- --- --- --- --- --- ---
| | | | | | | | |
A final line is drawn under the last row, which makes the board look better for my chosen approach.
Then I recognized that each cell in the row is basically the same thing over and over:
---
|
The last cell in the row has a right side to it. So the code could just repeat the above cell chunk 8 times, cap the row with another | character. Then repeat that row 8 times, followed by output of the final line:
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
| | | | | | | | |
--- --- --- --- --- --- --- ---
To make the size adjustable, I replaced the value 8 with the variable size. Then I added a simple check to determine whether a command line argument was present:
if(argc <= 1)
When no argument is present, argc equals one, so the value of variable size is set to 8. Otherwise, size is assigned the value of argv[1], the first argument. The atoi() function handles the conversion.
The rest of the code consists of the loops required to output the board. Oh! And I added initial output that announces the board’s dimensions.
Here is my solution:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int size,row,column;
if(argc <= 1)
size = 8;
else
size = atoi(argv[1]);
printf("%d x %d Chessboard:\n",size,size);
for(row=0;row<size;row++)
{
/* Draw the top line */
for(column=0;column<size;column++)
printf(" ---");
putchar('\n');
/* Draw the squares */
for(column=0;column<size;column++)
printf("| ");
printf("|\n");
}
/* Draw the bottom line */
for(column=0;column<size;column++)
printf(" ---");
putchar('\n');
return(0);
}
Your solution doesn’t need to look exactly like this. The output must resemble a chess board in some way, and the code must react properly to the command line option. I tested my code for a 1 square chess board as well as a 40 square board and various values in between. It worked! If your code works as well, then you’re good.