0

I'm havin' a little tough time with Mario's pyramid. Well the essence of this question is I don't get some of the "triggers" and signs on the code. I mean, I don't understand some signs, e.g. the i++, s-- and their respective function in the following code. With the "get height" logic I'm OK. Really need some help please, thank you in advance:


for (int i = 1; i <= height; i++)

Why does "i" have to be "less than or equals" height? what does i++ mean?

for (int s = height - i; s > 0; s--)

Same here, why does "int s" "equal" height, why does height have to be "minus i", s "less than" 0 and what's the role of "s--"?

1
  • Thank you both! Now it is clear for me. :-)
    – Paul_1898
    Jul 29 '15 at 21:35
0

what does i++ mean?, what's the role of "s--"?

The ++ and -- are called unary operators, and that's because they operate on a single variable instead of two variables, like binary operators do. The ++ operator increments the variable it is applied to by 1, and -- decrements the variable by 1. More info here: http://www.codingunit.com/unary-and-binary-operator-table

Why does "i" have to be "less than or equals" height?, Same here, why does "int s" "equal" height, why does height have to be "minus i", s "less than" 0

The = operator in C doesn't mean equality, but variable assignment. The equality is checked by the == operator. So the first part of the for loop, makes the initial assignment, that is at what value will the variable start. The second part in the for loop, is the condition, that as long as it's true, the for loop will continue to execute. Lastly the third part in the for loop is the part where you update the variable controlling the loop. In your first example we have

  • start i from 1
  • keep executing the loop as long as i is less or equal than height
  • increment i by one at the end of the loop

In your second example we have

  • start s from height - 1
  • keep executing the loop as long as s is greater than 0
  • decrement s by one at the end of the loop
0

For the case of the first for loop, for (int i = 1; i <= height; i++) { some code }.
int i = 1 assigns 1 to i just before the loop is executed.
i <= height just means keep doing the code enclosed in the loop while it is true.
i++ mean i = i + 1 and when placed in this part of the loop means to increment i every time the code in the loop is completed.

More info on loops can be found at http://www.cprogramming.com/tutorial/c/lesson3.html

You must log in to answer this question.

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