roncook roncook - 3 months ago 10
C Question

Creating a "Mario Style Pyramid"

I'm going through the Harvard CS50 online course and one of the problems is to create a "mario style pyramid" using spaces and hashes. I've got the spaces solved but the hashes are giving me trouble. Here's the code:

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

int main(void)
{
//get height between 1 and 23
int height;
do
{
printf("Please enter a height: ");
height = GetInt();
}
while (height < 1 || height > 23);

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

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

printf("\n");
}
}


When i run it in the terminal with a height of 5 i'm getting this:

####
###
##
#
<-- space here also


when i want this:

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


Any feedback would be appreciated, thanks

Answer

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 :)