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

后端 未结 10 1904
灰色年华
灰色年华 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:13

    #include 
    
    // Please note spacing of
    // - functions braces
    // - for loops braces
    // - equations
    // - indentation
    int main(void)
    {
        // Char holds all the values we want
        // Also, declaire all your variables at the top
        unsigned char user_i;
        unsigned char tall, space, hash;
    
        // One call to printf is more efficient
        printf("Hello there and welcome to the pyramid creator program\n"
               "Please enter a non negative INTEGER from 0 to 23\n");
    
        // This is suited for a do-while. Exercise to the reader for adding in a
        // print when user input is invalid.
        do scanf("%d", &user_i);
        while (user_i < 0 || user_i > 23);
    
        // For each level of the pyramid (starting from the top)...
        // Goes from 0 to user_i - 1
        for (tall = 0; tall < user_i; tall++) {
    
            // We are going to make each line user_i + 2 characters wide
    
            // At tall = 0,          this will be user_i + 1                characters worth of spaces
            // At tall = 1,          this will be user_i + 1            - 1 characters worth of spaces
            // ...
            // At tall = user_i - 1, this will be user_i + 1 - (user_i - 1) characters worth of spaces
            for (space = 0; space <= user_i - tall; space++)
                printf(" "); // no '\n', so characters print right next to one another
    
            //                 because of using '<=' inequality
            //                                                \_  
            // At tall = 0,          this will be          0 + 1 characters worth of hashes
            // At tall = 1,          this will be          1 + 1 characters worth of hashes
            // ...
            // At tall = user_i - 1, this will be user_i - 1 + 1 characters worth of spaces
            for (hash = 0; hash <= tall; hash++)
                printf("#");
    
            // Level complete. Add a newline to start the next level
            printf("\n");   
        }
    
        return 0;
    }
    

提交回复
热议问题