In the previous blog I showed you how you can add one to a variable. You can use the ++ operator. I also showed you what to do if you wanted to add more than one to a variable. For example, we can have something like this:
The left side of this will evaluate to 200 and then that will be assigned to pizzasToEat. The = here is actually an operator of its own. It’s a binary operator because it takes some value on the right and assigns to the variable on the left.
There is actually a collection of operators that exist to make this a whole lot easier. The syntax is a bit odd at first, but you will get used to it.
This will actually add 100 to the variable.
The name for this operator sounds just like it looks. It’s called the plus equals operator.
There are a multitude of assignment operators. The most important ones to know are =, +=, -=, /=, *=, and %=. There are some others but they are very complicated compared to where we are right now, so we’ll ignore those for now. The thing to keep in mind, though, is that these are assignment operators, so they are all going to change the value of the variable.
Let’s go through some more examples.
pizzasToEat -= 100 will subtract the value of the variable by 100.
pizzasToEat /= 5 will divide the value by 5
pizzasToEat *= 2will multiply the value by 2.
pizzasToEat %= 2 will give the remainder when divided by 2.
These operators are great because once you are familiar with them they more clearly express what you are trying to do. They also reduce the chance of errors because you only have to type a particular variable one time, not twice.
In the next blog we are going to be discussing all of the Operator Precedence. Check it out!