Assuming height
is the value entered by the user, and h
is the number of the row, the value for spaces
will be the same for every line.
int spaces = height - 1;
Note that this is a constant expression, which always evaluates to 1 less than height
. So if height
is 5 for example, then spaces
will always have the value of 5 - 1 = 4
.
What you probably want, is for spaces
to relative to the row value h
. There are many ways to calculate this, but suppose you did this instead:
int spaces = height - h;
Now the value of spaces
will increase for each row. For example, again assuming height
is 5, the value in the loop might look like this:
spaces = 5 - 0 = 5
spaces = 5 - 1 = 4
spaces = 5 - 2 = 3
spaces = 5 - 3 = 2
spaces = 5 - 4 = 1
spaces = 5 - 5 = 0
If spaces
is used as the control variable in a loop which prints a single space character, this will print 5 spaces, then 4, then 3, and so on.
Now that you have the correct number of spaces, you can easily calculate the number of sharps in a similar way.
One way would be to just use the row number h
as the loop control variable, e.g.:
for (int sharps = 0; sharps < (h + 2); sharps++)
You may notice that spaces is not included in the loop condition. The reason is that at this point the spaces should have already been printed, so all you need to do is print the additional sharp #
characters.
If it's not clear why the loop uses sharps < (h + 2)
and not just sharps < h
, try both variations, and try different values instead of 2
to see what effect the value has.
A different way to calculate the number of sharps, would be to take into account the fact that the total number of characters for each row, including spaces and sharps, is always the same. So every row has the same number of characters.
If you know how many characters should appear on each row, and you already have the number of spaces, then the remaining characters must be sharps. The trick is calculating the correct number of characters (Hint: It's related to the height
).
h
andheight
refer to. Assumingheight
is the value entered by the user, andh
is the number of the row?