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

后端 未结 10 1906
灰色年华
灰色年华 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-05 04:55

    This type of small programs are the one which kept fascinating me in my earlier days. I think they play a vital role in building logics and understand how, when, where and in which situation which loop will be perfect one.
    The best way one can understand what happening is to manually debug each and every statement.
    But to understand better lets understand how to build the logic for that, I am making some minor changes so that we can understand it better,

    • n is no of lines to print in pyramid n =5
    • Replacing empty spaces ' ' with '-' (dash symbol)

    Now pyramid will look something like,

                                ----#
                                ---##
                                --###
                                -####
                                #####
    

    Now steps to design the loop,

    • First of all we have to print n lines i.e. 5 lines so first loop will be running 5 times.
      for (int rowNo = 0; rowNo < n; rowNo++ ) the Row number rowNo is similar to tall in your loop
    • In each line we have to print 5 characters but such that we get our desired figure, if we closely look at what logic is there,
      rowNo=0 (Which is our first row) we have 4 dashes and 1 hash
      rowNo=1 we have 3 dashes and 2 hash
      rowNo=2 we have 2 dashes and 3 hash
      rowNo=3 we have 1 dashes and 4 hash
      rowNo=4 we have 0 dashes and 5 hash
    • Little inspection can reveal that for each row denoted by rowNo we have to print n - rowNo - 1 dashes - and rowNo + 1 hashes #,
      Therefore inside our first for loop we have to have two loops, one to print dashes and one to print hashes.
      Dash loop will be for (int dashes= 0; dashes < n - rowNo - 1; dashes ++ ), here dashes is similar to space in your original program
      Hash loop will be for (int hash = 0; hash < rowNo + 1; dashes ++ ),
    • The last step after every line we have to print a line break so that we can move to next line.

    Hope, the above explanation provides a clear understanding how the for loops that you have written will be formulated.

    In your program there are only minor changes then my explanation, in my loops I have used less then < operator and you have used <= operator so it makes difference of one iteration.

提交回复
热议问题