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

后端 未结 10 2095
灰色年华
灰色年华 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 05:08

    First off, let's get the body of the loops out of the way. The first one just prints spaces, and the second one prints hash marks.

    We want to print a line like this, where _ is a space:

    ______######
    

    So the magic question is, how many spaces and #s do we need to print?

    At each line, we want to print 1 more # than the line before, and 1 fewer spaces than the line before. This is the purpose "tall" serves in the outer loop. You can think of this as "the number of hash marks that should be printed on this line."

    All of the remaining characters to print on the line should be spaces. As a result, we can take the total line length (which is the number the user entered), and subtract the number of hash marks on this line, and that's the number of spaces we need. This is the condition in the first for loop:

    for ( int space = 0; space <= user_i - tall; space++ )
    //                            ~~~~~~~~~~~~~ 
    // Number of spaces == number_user_entered - current_line
    

    Then we need to print the number of hash marks, which is always equal to the current line:

    for ( int hash = 0; hash <= tall; hash++ )
    //                          ~~~~
    // Remember, "tall" is the current line
    

    This whole thing is in a for loop that just repeats once per line.

    Renaming some of the variables and introducing some new names can make this whole thing much easier to understand:

    #include 
    
    int main ( void )
    {
        int userProvidedNumber;
        printf ( "Hello there and welcome to the pyramid creator program\n" );
        printf ( "Please enter a non negative INTEGER from 0 to 23\n" );
        scanf ( "%d", &userProvidedNumber );
    
        while ( userProvidedNumber < 0 || userProvidedNumber > 23 )
        {
            scanf ( "%d", &userProvidedNumber );
        }
    
        for ( int currentLine = 0; currentLine < userProvidedNumber; currentLine++ )
        {
            int numberOfSpacesToPrint = userProvidedNumber - currentLine;
            int numberOfHashesToPrint = currentLine;
    
            for ( int space = 0; space <= numberOfSpacesToPrint; space++ )
            {
                printf ( " " );
            }
            for ( int hash = 0; hash <= numberOfHashesToPrint; hash++ )
            {
                printf ( "#" );
            }
    
            // We need to specify the printf("\n"); statement here
            printf ( "\n" );
        }
    
        return 0;
    }
    

提交回复
热议问题