This is all about noticing patterns in a pyramid. The comment for the first for loop says that it is printing the correct number of spaces before the actual pyramid (i.e. the asterisks).
Let’s look at how many spaces there are at each level:
* level 0 - 4 spaces
*** level 1 - 3 spaces
***** level 2 - 2 spaces
******* level 3 - 1 space
********* level 4 - 0 spaces
Notice how as the level number increases, the number of spaces decreases? They are inversely proportional. What would be a function that maps the level number n
into the number of spaces? It would be
f(n) = 4 - n
Or more generally,
f(n) = k - n - 1
where k
is the number of levels.
This is why we wrote 5 - row - 1
. It maps row
(i.e. n
) into the number of spaces that should be printed!
The same goes for the second for loop, which figures out how many asterisks should be printed.
* level 0 - 1 asterisks
*** level 1 - 3 asterisks
***** level 2 - 5 asterisks
******* level 3 - 7 asterisk
********* level 4 - 9 asterisks
This time the pattern is even simpler. It is just an arithmetic sequence. The function that maps the level number into the number of asterisks is
f(n) = 2 * n + 1
This explains the 2 * row + 1
in the second for loop.
solved For-loop condition mechanic for Pyramid code