How does this C for-loop print text-art pyramids?

后端 未结 10 1909
灰色年华
灰色年华 2021-02-05 04:24

This is my first time posting in here, hopefully I am doing it right.

Basically I need help trying to figure out some code that I wrote for class using C. The purpose o

10条回答
  •  -上瘾入骨i
    2021-02-05 04:58

    A few things:

    • Consider "bench checking" this. That is, trace through the loops yourself and draw out the spaces and hash marks. Consider using graph paper for this. I've been doing this for 15 years and I still trace things out on paper from time to time when they're hairy.

    • The magic in this is the value "user_i - tall" and "hash <= tall". Those are the conditions on the two inner for loops as the middle values in the parenthesis. Note what they are doing:

    • Because tall is "going up" from the outer-most loop, by subtracting it from user_i, the loop that prints the spaces is "going down". That is, printing fewer and fewer spaces as it goes.

    • Because tall is "going up", and because the hash loop is just basically using it as-is, it's going up too. That is, printing more hash marks as you go.

    So really ignore most of this code. It's generic: the outer loop just counts up, and most of the inner loops just do basic initialization (i.e. space = 0 and hash = 0), or basic incrementation (space++ and hash++).

    It is only the center parts of the inner loops that matter, and they use the movement of tall from the outermost loop to increment themselves down and up respectively, as noted above, thus making the combination of spaces and hash marks needed to make a half-pyramid. Hope this helps!

提交回复
热议问题