Unit 1.6: Compound Assignment Operators
AP Computer Science A
Learning to use shortcuts for common operations
Learning Objective 1.6.A
Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.
What are Compound Assignment Operators?
Compound assignment operators are shortcuts that combine an arithmetic operation with assignment.
Traditional Way:
Compound Assignment Way:
Same result, cleaner code!
The Five Compound Assignment Operators
Addition Assignment
x += 5 means x = x + 5
Subtraction Assignment
x -= 3 means x = x - 3
Multiplication Assignment
x *= 2 means x = x * 2
Division Assignment
x /= 4 means x = x / 4
Modulus Assignment
x %= 3 means x = x % 3
Step-by-Step Example
Let's trace through some compound assignments:
Final value of score: 2
Post-Increment and Post-Decrement Operators
Special operators for adding or subtracting exactly 1:
Post-Increment
x++ means x = x + 1
Post-Decrement
x-- means x = x - 1
AP Exam Note:
Only post-fix form (x++, x--) is tested. Pre-fix form (++x, --x) is outside the scope.
Common Mistakes to Avoid
Wrong
Correct
Remember:
- The variable must be on the LEFT side of the operator
- Don't confuse += with =+
- Compound operators can only be used with variables, not literals
- The result is always stored back in the original variable
Practice Problems
What will be the final values?
Answers:
Problem 1: a = 26 (8+4=12, 12*3=36, 36-10=26)
Problem 2: b = 2 (15%4=3, 3+1=4, 4/2=2)
Problem 3: c = 4 (20-5=15, 15+1=16, 16*2=32, 32%7=4)