# Basic Math

## How to Add, Subtract, Multiply, and Divide Numbers with ActionScript in Flash

Often times you need to perform simple math operations in ActionScript. The symbols for common operations are as follows:

- Subtract

* Multiply

/ Divide

In math class, you may have been asked to create two variables and assign a value for each. Then run them through and equation and calculate a solution. It might look like this.

a = 5

b = 6

a + b = 11

To accomplish the same thing in ActionScript, the code would look a little different.

var a:Number=5;

var b:Number=6;

var c:Number=0;

c=a+b;

It is helpful to see the equals sign as the statement "is replaced by" when evaluating an equation. The following example uses parentheses to determine the order that the equation is solved.

#### Step One

Name the default layer, Actions.

#### Step Two

Option double-click (PC - Alt double click) the first keyframe of the Actions layer to open the ActionScript panel.

#### Step Three

Copy/Paste the following code in the ActionScript Panel:

var a:Number=40;

var b:Number=5;

var c:Number=14;

var d:Number=6;

var totalValue:Number=0;

totalValue=(a * b)/(c + d);

trace(totalValue);

#### Step Four

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). The value of totalValue appears in the Output panel.

#### Dissecting the Code

The first five lines at Step Three establish five new variables and set a value for each.

To solve for totalValue, 40 is multiplied by 5 (200), then 14 is added to 6 (20). Finally, 200 is divided by 20, giving us a total of 10. The last line displays the value of totalValue in the Output window.

#### Math Shortcuts

There are multiple ways to add a value to a number variable. For instance, you may want to add two to a number variable each time a function is run. You could write the code using Method One or Method Two.

#### Method One (10 + 2 = 12)

var baseNumber:Number=10;

baseNumber=baseNumber+2;

#### Method Two (10 + 2 = 12)

var baseNumber:Number=10

baseNumber+=2;

The second method is easier than the first. The same is true for subtraction, multiplication and division.

#### Subtraction (10 - 2 = 8)

var baseNumber:Number=10

baseNumber-=2;

#### Multiplication (10 * 2 = 20)

var baseNumber:Number=10

baseNumber*=2;

#### Division (10 / 2 = 5)

var baseNumber:Number=10

baseNumber/=2;