Print star ('*') diamond in C with nested loops?

前端 未结 10 1981
醉酒成梦
醉酒成梦 2021-01-07 14:41

I want to be able to print a diamond like this when the user enters 5 for the diamond. But also will work for any value that is odd and greater than 0.

10条回答
  •  日久生厌
    2021-01-07 15:31

    There are two things that occur here:

    1. Indent changes (-1 to "mid", +1 "after")

    2. Star count changes (+2 to "mid", -2 "after")

    Now, this could be done with two loops (one for the top to "mid" and one "after"), but the values can also be determined with a little math. Let's explore that :-)

    Here are the numbers:

            s(spaces)  x(stars) n(line number)
    __X          2        1        0
    _XXX         1        3        1
    XXXXXX       0        5        2
    _XXX         1        3        3
    __X          2        1        4

    Start by noting that s is symmetrical about the "mid":

    • s = abs(2 - n)

    And then that x is related to s (by 2 as noted in deltas above):

    • x = 5 - (s * 2) = 5 - (abs(2 - n) * 2)

    Hope that gives some insight!

提交回复
热议问题