Compound Assignment Operators
Compound Assignment Operators: 1.5.0
- Shortcuts to do a math operation in one step
x += 1
adds 1 tox
and assigns it tox
- Same as
x = x + 1
- Same as
+ shortcuts | - shortcuts | * shortcuts | / shortcuts | % shortcuts |
x = x + 1; |
x = x - 1; |
x = x * 1; |
x = x / 1; |
x = x % 1; |
x += 1; |
x -= 1; |
x *= 1; |
x /= 1; |
x %= 1; |
x++; |
x--; |
- Most common shortcut operator is
++
- increment operator
- adds
1
to the current value- Same as
x = x + 1
- Same as
++x
can be used to incrementx
before assigning something to itint y = ++x;
- Otherwise works identically
int y = x++;
sets y to the old value of x, then increments x- This difference is not on the AP Exam
Code Tracing Challenge: 1.5.1
No real notes about the lesson here, just manually debug 1.5.1.
From personal experience, using a whiteboard can be really helpful in code tracing, as you can more easily manipulate and erase your work.
Summary: 1.5.2
- Compound assignment operators can be used in place of the assignment operator
+=
,-=
,*=
,/=
,%=
- The increment and decrement operator can be used to add or subtract 1 from a variable, then store the new result
++
and--
Closing thoughts
None really; this was a very short section.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.