Sometimes the value of our variables need to be adjusted. We know that we can update our variables using arithmetic operators like this:
var age = 99 age = age + 1 print(age) // Prints 100
We also have the option of using compound assignment operators, a shorthand method for modifying the value of variables.
If we wanted to rewrite our previous code using a compound assignment operator (
+=), our syntax would look like this:
var age = 99 age += 1 print(age) // Prints 100
Notice that by using a compound assignment operator, we no longer need to reference
Here are some different compound assignment operators we can use:
+=add and assign the sum.
-=subtract and assign the difference.
*=multiply and assign the product.
/=divide and assign the quotient.
%=divide and assign the remainder.
Check out these operators in action as we modify the value of
dollars five times using compound assignment operators:
var dollars = 5 dollars += 4 // same as dollars = 5 + 4 print(dollars) // Prints: 9 dollars -= 3 // same as dollars = 9 - 3 print(dollars) // Prints: 6 dollars *= 5 // same as dollars = 6 * 5 print(dollars) // Prints: 30 dollars /= 6 // same as dollars = 30 / 6 print(dollars) // Prints: 5 dollars %= 2 // same as dollars = 5 % 2 print(dollars) // Prints: 1
While the value of
dollars started out as
5, the value changed every time we used a compound assignment operator; by the end of the program,
dollars had a value of
When using compound assignment operators, be sure to include a space before and after the assignment operator
=; otherwise, we will receive an error.
Imagine being the owner of a small fruit stand. To start the day, there are 16 apples in the inventory.
Suppose a customer comes in and buys
4 apples. Use a compound assignment operator to adjust the value of
Another customer purchases half of the available apples.
Underneath your previous code, change the value of
apples to reflect this exchange using a compound assignment operator.