Trying to understand `w = w + 1` from a math perspective?

Just looking at the first line in the example, and I don’t agree with the syntax of “w=w+1” as this implies that w=w+1 which it isn’t. Doesn’t anyone think it should be written as w sub 1 “so a little 1 at the bottom right of the w”?

1 Like

To anyone first exposed to programming this is a head turner, to be sure. It looks nothing like any math we learned in school.

Break it down though…

w + 1

will be one more than what w is currently.

w = w + 1

is the reassignment of the new outcome to the original variable. Now w is one more than it was, previously.

This is not a formula but an assignment statement that assigns the value of the expression on the right of the equal sign to the variable on the left side. Evaluation of the expression occurs first, then the assignment.

Once we can grasp what is happening, and see that it is perfectly logical, and practical (as it increments w) we can appreciate the shorthand operator that many languages have to simplify the above statement… Augmentation assignment.

w += 1

Like above, the current value a w is increased by 1, then reassigned. The operation occurs before the assignment.

When you get into loops, you will see another operator introduced that shortens the expression even more… ++

w++

increments w in place. That will come up, so don’t tarry on this problem but push ahead.

69 Likes

Great explanation, thank you!

6 Likes