Skip to main content
Logo image

Section 13.4 Compound Assignment Operators

In programming we often update the values of variables using statements such as:
i = i + 1;fac = fac * i;num = num - 1;
These common coding tasks, where a certain operation (i.e. addition, subtraction, etc.) is being done to one variable itself (so the variable appears on both sides of the assignment operation), can be written in a shorthand using compound assignment operators.
In the first example above, we want to increment i by one, meaning we take the old value of i, add one to it, and store the new value back in i. However, we can achieve the same result using a compound assignment operator!
In the following video, we’ll learn about this shorthand notation for such variable updates.

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

Please complete the following program by creating a loop that adds up the numbers from n to 2n (have the user enter the number n). Save the result of this addition in the variable sum (which has already been declared) and print it out. Be sure to declare any other additional variables you might need for your loop.

admin.....open in new window

When your program performs correctly you’ll be given a keyword to enter in Canvas.