• Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result

Assignment

Extra Practice


Compound Assignment Operators

We’ve seen code to update the value of a variable. The code below will add five to the value of x.

1
x = x + 5;

For actual legitimate reasons, a briefer expression was developed.

1
x += 5;

This works will all the operators, too.

1
2
3
4
x -= 5;
x *= 5;
x /= 5;
x %= 5;

Just be aware of your types, since in those examples 5 is an integer meaning your new value will also be an integer.

You do not have to use the abbreviated form, but you’ll see it on the exam. Best to use it so you get comfortable reading it.

Increment and Decrement Operator

Programmers are really lazy. Adding or subtracting by one is so common, we needed to drop one more character from the expression. The below lines will add and subtract one from x.

1
2
x++;
x--;