Topic 1.6 — Compound Assignment Operators
Goal: use compound assignment operators (like +=, -=, *=, /=, %=)
to update variables efficiently and accurately.
The big idea
Compound assignment operators are shorthand for “update this variable using its current value.” They are equivalent to longer assignment statements, but easier to read and write.
Example: x += 3; means “add 3 to x and store it back into x.”
Common compound operators
+= -= *= /= %=
These work with numeric types (and you’ll also see += with Strings in Topic 1.15).
Equivalences (what they really mean)
Each one matches a longer statement:
x += 5; // x = x + 5;
x -= 2; // x = x - 2;
x *= 3; // x = x * 3;
x /= 4; // x = x / 4;
x %= 6; // x = x % 6;
Why this matters (AP skill)
- Reading code faster (you’ll see this a lot).
- Writing updates quickly and cleanly.
- Tracing values accurately in multi-line code segments.
Example: tracing updates
Follow the variable value after each line.
int x = 10;
x += 4; // 14
x *= 2; // 28
x -= 5; // 23
Watch out: integer division with /=
If the variable is an int, division truncates.
int a = 9;
a /= 2; // a becomes 4 (not 4.5)
Common mistake: assuming rounding
With int values, division always truncates. Compound division does the same.
int n = 7;
n /= 3; // 2 (not 2.33)
Using %= (remainder updates)
Useful for “wrap around” behaviors and remainder tracking.
int t = 17;
t %= 5; // t becomes 2
Exam mindset
- Mentally expand compound operators when tracing:
x += k→x = x + k. - Remember type rules: int math stays int.
/=with an int truncates.%=stores the remainder back into the variable.
Quick self-check
- If
x = 6, what is x afterx += 3;? - If
y = 10, what is y aftery /= 4;(int)? - If
z = 14, what is z afterz %= 5;? - Rewrite
a *= 2;as a full assignment statement. - Why is
/=sometimes surprising withintvariables?