I am having trouble getting the pyramid to print anything more than the first row of spaces, and the number of spaces it prints is not correct; for example, for a height of 4, it prints 4 spaces, not 3. It will also not print the hashtags.

Any advice on how to fix these problems would be greatly appreciated. Thank you!

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

int main(void)
int h;
int row;
int space;
int hash;

    printf("Height: ");
    h = get_int();
while (h > 23 || h < 0);

for (row = 0; row < h; row++)
    for (space = h - 1; space >= 0; space--)
    for (hash = 2; hash <= (row + 1); hash++)
  • I'm not sure that it will help with your question, but I would suggest that you consider abstracting your code by creating functions. I see that you currently have everything under Main, and I think it is better design to use Main to simply call those functions. You may also want to consider indenting everything between the first two braces to make your code easier to read.
    – EJ Mak
    Commented Apr 26, 2017 at 16:26

1 Answer 1


For h = 4, the space loop will execute 4 times and the hash loop will execute 0 times when row is 0. Here's why:

space: for (space = h - 1; space >= 0; space--) is the same as for (space = 3; space >= 0; space--). space >=0 is true for space in {3, 2, 1, 0}, a total of 4 iterations. Since h is constant in this loop, it will always print h spaces.

hash: for (hash = 2; hash <= (row + 1); hash++) is the same as for (hash = 2; hash <= (0 + 1); hash++). Since 2 > 1, it will not execute; 0 iterations.

Work the rest of the rows out in your head or on paper, and you will see it matches the results produced. The next step is to figure out the relationship of space and hash to row and h. That will help you determine the proper number of iterations for each loop.

  • Thank you! This got me on the path to rewriting the 'space' and 'hash' loops, and the program is now running as it should. I also forgot that you have to re-compile the code every time you make updates, so that was also holding me back.
    – dmz
    Commented Apr 27, 2017 at 19:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .