Tutorial: Basic Math

This tutorial will introduce you to basic, simple math.

Mathematical Operations

The four basic mathematical operations are : addition, subtraction, multiplication and division.

Addition

Addition uses a + :

Print 4 + 2

Sync
WaitKey

Subtraction

Subtraction uses a - :

Print 4 - 2

Sync
WaitKey

Multiplication

Multiplication uses a * :

Print 4 * 2

Sync
WaitKey

Division

Division uses a / :

Print 4 / 2

Sync
WaitKey

Using Variables

Variables can be used in math :

score = 4

Print score + 2
Sync
WaitKey
score = 4
bonus = 2

Print score + bonus

SyncWaitKey
myVar1 = 4
myVar2 = 2
myVar3 = myVar1 + myVar2

Print myVar3

Sync
WaitKey

Learn more about variables in our Variables tutorial.

Incrementing Variables

Incrementing a variable is adding 1 to it's current value.

coins = 42
coins = coins + 1

Print coins

Sync
WaitKey

You can also use the Inc function to increment a variable.

coins = 42
Inc coins

Print coins

Sync
WaitKey

Decrementing Variables

Decrementing a variable is subtracting 1 from it's current value.

health = 42
health = health - 1

Print health

Sync
WaitKey

You can also use the Dec function to decrement variables.

health = 42
Dec health

Print health

Sync
WaitKey

The - Operator

The - operator can be used for subtraction, or to reverse the sign of a number.

Reversing the sign of a number is to change a negative number into a positive number and change a positive number into a negative number. This is commonly used to reverse the speed, and therefore the direction of a game object.

xSpeed# = 5
xSpeed# = -xSpeed#

Print xSpeed#

Sync
WaitKey
xSpeed# = -5
xSpeed# = -xSpeed#

Print xSpeed#

Sync
WaitKey

- changes a positive to a negative and a negative to a positive. To ensure the result is negative, see How To: Make a Variable Negative or the Absolute Value section below.

Absolute Value

Occasionally it's useful to know the absolute value of a number.

The absolute value of a number is it's distance from 0. The absolute value of -5 and 5 is 5.

The Abs() function returns the absolute value of a number.

x# = -15
absVal = Abs( x# )

Print absVal

Sync
WaitKey

Expressions

Expressions evaluate to numbers.

42 is an expression.

21 + 21 is an expression.

True and False are expressions because they are actually numbers.

Next Steps

Categories: Beginner Tutorials : Math : Math Tutorials : Programming Tutorials : Tutorials