So I logically figured out everything but the hashes.
I mean it executes correctly, but why??
Why does the first line start with two hashes??? Isn't the initial value zero? It increments by one, but why is the starting point two?
Other ways that seemed like great logic to me did not work. (set initial value to 2, set it to (row + 2), ...)
I really can't wrap my head around it and it's driving me crazy.
What am I missing here?
Where is the flaw?

        for (int row = 0; row < height; row++)

        // spaces left of pyramid

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

        // hashes of pyramid

        for (int hash = 0; hash < (row + 2); hash++)

        // new line after each row 


1 Answer 1


Your initial value is zero, and you increment the variable hash by one each time you run your code through. So if you were to run your "hash loop" only once with height = 5, you would have a starting line with four spaces and only one hash.

However, you set the for loop to run for as long as hash < (row + 2). So no matter what you will always be printing a number of hashes that is less than the row number plus 2. If we skip the first line for a second, this would result in a hash increase of one per new row because row is getting increased by one and thus your upper bound for the number of hashes gets increased by one. Where your bound was 2, now it is 3, and now you can pop another hash in there.

So what gives with the first run through the loop? Why does every other iteration of the big for loop give only one additional hash, but the first one gives two? Well, you initialize your variable hash and set it equal to zero in your for loop. If you were to set it equal to 1, then you would only have one hash printed out. But, since you made it zero, you run through the for loop twice. Once when hash = 0 and then another time when hash = 1. This totals two hash marks. It can't iterate a third time because then hash would be 2 which is not less than 2.

Each line after that repeats those first two hashes and the adds another one on there because you reinitialize hash with each iteration of the loop.

  • Omg the sudden clarity!!! I feel stupid now.. Thank you so much for your time and the explanation! :)
    – s0y
    Oct 13, 2015 at 15:45
  • No problem! Glad to have helped :)
    – peachykeen
    Oct 13, 2015 at 16:34

You must log in to answer this question.

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