# Mario pyramid loop arithmetic question

So I've got the program up and running, I'm just trying to understand exactly why it is performing correctly. I'm confused on this:

``````for (rows = 0; rows < height; rows++)
{
for (spaces = (height - rows); spaces > 1, spaces--)
{
printf(" ");
}
``````

This gives me the effect I'm looking for, but my math says it shouldn't. When I try to reason it out in order, I end up with the "rows" variable being 1 on the first loop, therefore for a given height (lets say 4) I get:

spaces = (height(4) - rows(1)) which is 3, then decrement "spaces" by 1 and I get 2 spaces for the first line, which is the incorrect amount. However when my program runs, I end up with 3 spaces in the first line which is the correct amount. What am I missing here?

Your math is correct, but your understanding of the variables in the for loop isn't. On the first run, rows = 0, not 1. Look at the for loop setup code: for (rows = 0; rows < height; rows++)

rows is initially set to 0 for the first pass. rows++ only increments when the loop has completed the first pass and returns to the beginning. At that point, rows is incremented and then the test condition is checked. So, when height = 4, the first pass in the inner loop is spaces = (height(4) - rows(0)) = 4. This means that the loop will execute 3 times, with spaces having values of 4, then 3, then 2 in the inner loop. When it hits 1, the test fails and the loop exits, so it has made 3 passes and printed 3 spaces.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)