Program Logic

Unit 3 Index

Compound Assignment Operators

Compound Assignment Operators

We have already studied the basic assignment operator, now let's look at a few other assignment operators that are useful. Notice the compound assignment operators are a combination of the equals sign and a math operator. Compound operators are used by many professional programmers. As you will see, we get the same answer with less typing!

Compound Assignment Operators

Please study the table of compound operators below.

Operator Function
+= Add into a variable
-= Subtract into a variable
*= Multiply into a variable
/= Divide into a variable

Adding into a Variable ( += )

We can add a number to a variable like this:

// The old way...Adding with +
int myNumber = 0;
myNumber = myNumber + 10; 
//increases myNumber by 10

We can also use a compound assignment operator.

// The new way...Adding with +=
int myNumber = 0;
myNumber += 10; 
//increases myNumber by 10

The code myNumber += 10; means the same as myNumber = myNumber + 10;

Please note, if I give you an assignment that says, “get a running total” or “use a compound operator to get a running total”, then make sure you use the += compound assignment operator.

Subtracting into a Variable ( -= )

We can subtract a number from a variable like this:

// Subtracting with -
int myNumber = 100;
myNumber = myNumber - 10;
//decreases the value of myNumber by 10

However, it is more efficient to use a compound assignment operator.

// Subtracting with -=
int myNumber = 100;
myNumber -= 10; 
//decreases the value of myNumber by 10

Multiplying into a Variable ( *= )

As you might have guessed, we can also multiply with a compound assignment operator

// Multiplying with *=
int myNumber = 10;
myNumber *= 2;

Dividing into a Variable ( /= )

I think you figured out this one was coming! Dividing with a compound assignment operator looks this this:

// Dividing with /=
int myNumber = 100;
myNumber /= 2;

What you Learned

  • When a math operator is used in conjunction with the assignment operator, you have a compound operator
  • Using this technique is an efficient shortcut used by many developers
  • You will use compound assignment operators in an assignment

What's next?

The next chapter in Math Operators is The Modulo Operator.