Creating a “Mario Style Pyramid” [duplicate]

雨燕双飞 提交于 2019-11-29 14:35:19

Just try it with the following code:

int main(void)
{
    int height;
    printf("Please enter a height: ");
    scanf("%d", &height);

    //build pyramid
    for (int i = height; i >= 1; i--)
    {
        //add spaces
        for (int space = 1; space < i; space++)
            printf(" ");

        //add hashtags
        for (int hash = height; hash >= i-1; hash--)
            printf("#");

        printf("\n");
    }
}

when the value of height is 5, you get the desired output:

    ##
   ###
  ####
 #####
######

See the Working Fiddle.


In your code, when the value of i is 0 in:

for (int i = 0; i < height ; i++)
         ^^^^^^

the other loops executes as follows:

for (int space = height - 1 - i; space >= 0; space--)
    printf(" ");

here, the loop initializes space = 4 (when height is 5) and the loop condition is valid till space >= 0, so it prints the first 4 characters as " ".

And, Finally when it comes to this loop:

for (int hash = 2 + i; hash <= height; hash++)
    printf("#");

here, the loop initializes hash = 2 (i was 0 in the first loop, remember that?) and the loop conditions continues till hash <= height. So, it prints the next 4 characters as "#" as the above condition evaluates to 2,3,4,5 in:

(int hash = 2; hash <= 5; hash++)
           ^^^        ^^^

and the rest of the code carries on and produces the output as:

     ####
    ###
   ##
  #

If you are able to understand the above logic, then you'd be able to decode my solution as well :)

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