printing a square with diagonals

前端 未结 4 1351
佛祖请我去吃肉
佛祖请我去吃肉 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:12

    To elaborate a bit on @EugeneSh.'s idea: Think of it this way. You have two loops in which you're iterating over (2n+1) x (2n+1) characters in the output. Each of these has to be one of the following: +, -, |, \, /, X or it has to have a (a space character).

    You can't avoid printing all those (2n+1)^2 characters. So - don't try to. Just decide, for each of them, which one it needs to be. Form the appropriate conditions and check for them. You've already done it for 3 of the possible characters - just do the rest.

    The "trick" is that if none of the conditions for the non-space characters is satisfied - you print a space ().

    PS - You might want to consider the switch() { ... } statement for doing this, with default: used for printing the space.

提交回复
热议问题