printing a square with diagonals

前端 未结 4 1350
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 07:44

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

4条回答
  •  无人及你
    2021-01-23 08:07

    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.

提交回复
热议问题