Introduction To Programming
10-152-310

Learning Plan 3 : Math and Operators

Compound Assignment Operators

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

Using Compound Assignment Operators

Adding into a variable (+=)

We can add a number to a variable like this:

        
        

        

And we can use a shortcut Compound Assignment Operator too. Since this is less typing we have fewer chances of making an error. Also, this is the way you will see professional programmers do it.

        
        

        

Subtracting into a variable (-= )

We can subtract a number from a variable like this:

        
        

        

We can use a shortcut Compound Assignment Operator too. Since this is less typing we have fewer chances of making an error. Just like with addition.

        
        

        

Multiplying into a variable (*=)

As you might now guess, we can also multiply into a variable like this:

        
        

        

This works too and it the preferred way to do it:

        
        

        

Dividing into a variable (/=)

I think you could figure out that this one was coming! Dividing like this:

        
        

        

But, dividing like this is better: