I want to print this if the user typed in for example 2:
+---+
|\\ /|
| X |
|/ \\|
+---+
It\'s a square with a size of 2n+1 for each side of i
Think like this. You only have to worry about the first half plus the middle. This is because the second half is the same as the first but reversed.
Then you figure out a formula for how a specific row should look like, only by which row it is and total number of rows.
The first row is easy. It's a +
, 2n-1 -
and another +
.
Then each row except the middle one will be two |
, with a \
and a /
and a total of 2n-3 spaces. If y is the row and the second row is indexed 0, then (2n-3)-2y spaces in the middle and y spaces outside the middle.
Lastly, we have the middle row that is two |
, n-1 spaces, X
, n-1 spaces, |
.
Putting it all together:
// First row
putchar('+');
for(int i=0; i<2*n-1; i++)
putchar('-');
putchar('+');
putchar('\n');
// Those between
for(int y=0; y
This prints correctly to the middle row. In order to print the rest, just copy the "Those between" for loop, but change to for(int y=n-2; y>0; y--)
and switch places on \
and /
. Lastly, just copy the code for the first row.