So I was able to set up the prompt and the left aligned pyramid correctly, but really started struggling when trying to right-align it with dots in front of the hashes. For whatever reason, its printing extra dots in between the hashes on each line. The hashes and rows are correct. I thought the third nested loop should have space = row - hash to get the correct amount of dots before the hashes, but it still prints the wrong amount of dots and places them between hashes. Has anyone else experienced this problem? My code for that section of the problem is below:

for (int row = 0; row < height; row++)
    for (int hash = height - row; hash <= height; hash++)
        for (int space = height - row; space >= 0; space--)

The output looks something like this for a height = 5: ......# .....#.....# ....#....#....# ...#...#...#...# ..#..#..#..#..#

1 Answer 1


The problem is your nesting of loops. For each row, you print height-row+1 dots/spaces and one hash, and this whole thing row+1 times.

Place your two inner loops on the same level, one after the other, inside the outer loop, not nested inside each other.

Edit to address the comment: The "normal" form of a loop (the one where it's easiest to see the number of iterations) would be

for (int counter = 0; counter < repetitions; counter++)


for (int counter = repetitions; counter > 0; counter--)

Number of repetitions would stay same when adding to both sides, and <= instead of < increases number of repetitions by one. So your

for (int hash = height - row; hash <= height; hash++)

runs (height) - (height - row) + 1, or row + 1 times.

for (int space = height - row; space >= 0; space--)

runs (height - row) - (0) + 1 times (again +1 for the >=)

  • Got it to work now by un-nesting the loops as you suggested and subtracting two from space, ie space = height - row - 2 but I'm not quite sure how I was printing height-row+1 in the first place? Appreciate your help!!
    – Angus
    Feb 15, 2019 at 1:04
  • Added a bit on number of iterations, hope this helps. Try this with pen and paper if you need to, or make an excel spreadsheet showing values before/after each iteration and whether it will enter the loop.
    – Blauelf
    Feb 15, 2019 at 9:54

You must log in to answer this question.

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