Making a Hash Pyramid

一个人想着一个人 提交于 2019-11-27 23:24:13

Here is a way you can implement this. Basically, you need to build the pyramid from the bottom up. The task is easy once you see the loop structure, its just tricky to get the math down for printing the correct number of spaces and hash symbols:

#include <stdio.h>

int main(void)
{ 
    int height, i, j;
    do
    {
        printf("please give me a height between 1-23: ");
        height = GetInt();
    }    
    while (height < 1 || height > 23);

    printf("\n");    
    for (i = 0; i < height; i++) {

        for (j = 0; j < height - i - 1; j++)
            printf(" ");
        for (j = 0; j < i + 2; j++)
            printf("#");

        printf("\n");
    }
}

For more clarification on whats going on, and why each loop is necessary:

  1. Outer for loop: the variable i corresponds to a row in the pyramid. the value of i will remain constant for each of the second two loops

  2. First inner for loop: for any row, there needs to be height - i - 2 spaces. You can figure this out because the total row width will be height, and any row has i + 2 hash symbols, so there needs to be height - (i + 2) = height - i - 1 spaces. So basically, this loop just prints the required spaces. You can track this with the variable j

  3. Second inner for loop: This loop is similar to the first inner loop, but you need to now print the hash marks. At the beginning of the loop you reset j and count up to the required number of hash marks

Here is a version that may offer some insight:

#include <stdio.h>
#include <cs50.h>

int main(void) {
    //initialize variables
    int height, n, j, k, i;

    printf("Height: \n");
    // Get user input
    height = GetInt();
    n = height;
    for(i = 0; i < height; i++) {
        // create n spaces based off height
        for(k = n; k > i; k--)
            printf("%c", ' ');      

        // create hash tags
        for(j = 0; j < i+2; j++)
            printf("#");

        printf("\n");
    }
    return 0;
}

Result if user entered a height of 5:

Height: 
     ##
    ###
   ####
  #####
 ######
  • The 1st for loop essentially prints the number of rows matching the height entered

  • The 2nd for loop involves printing the number of spaces based on the height entered

  • The 3rd for loop involves printing the number of hashes (with respect to the height value) after the amount of spaces on the same line

Cheers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!