Mathematical Operators

# Math Operators Introduction

As anyone will tell you, math is important. Since computer do nothing but crunch numbers all day, math is very important to the computer, and to programmers.

# Basic Math Operators

## Addition

Addition uses the + sign to add two values

````iSum:= iSum + 1`
```

## Subtraction

Subtraction uses the - sign to take a value away from another

````iDifference := iDifference - 1`
```

## Multiplication

Multiplication uses the * sign to multiply two numbers together

````iProduct := 2 * 4`
```

## Division

Division uses the / sign to divide one number by another

````iHalf := 4 / 2`
```

One thing to notice is that division can have two integer numbers, but the result can be a real number. E.g:
````iHalf := 1 / 2`
```

The value of iHalf is 0.5. This is a problem, because iHalf is a variable of an integer type, not a real type. If this was done in Turing, it would crash, and leave you with a lot of confusion. Beware of this property of division.

# Advanced Math Operators

## Exponentiation

To do an exponent, use '**' like so:

````iSquare := iNumber**2`
```

You can think of the '**' operator as a 'to the power of' operator.

## DIV

When you DIV one number by another, you get the quotient of the division. Say we did:

````iNumber := 6 DIV 4`
```

Then iNumber would have a value of 1, because 4 divides into 6 only 1 time.
Keep in mind that you will always get an integer result with DIV.

The result of 12 DIV 4 is 3
The result of 10 DIV 5 is 2
The result of 2 div 3 is 0

Remember The Golden Rule:

DIV is not Division

## MOD

MOD is often called the opposite of DIV, but that is not exactly the case. While DIV will return the quotient of a division, MOD returns the remainder of a division. Say we did:

````iNumber := 6 MOD 4`
```

Then iNumber would have a value of 2. This is because 4 divides once into 6, and the ammount left over is 2.
Just like DIV, you will always get an integer when you MOD two numbers together.

The result of 12 MOD 4 is 0
The result of 2 MOD 3 is 2
The result of 18 MOD 5 is 3

MOD has a special attribute that programmers can use to their advantage. Say you have two numbers, A and B. If A MOD B = 0, then you know that A is a multiple of B, since B was able to divide into A with no remainder.
E.g:

The result of 8 MOD 2 is 0, so that means 8 is a multiple of two
The result of 12 MOD 4 is 0, so that means 12 is a multiple of 4
The result of 10 MOD 3 is not 0, so 10 is not a multiple of 3

This is used very frequently in Computer Science, because you can easily tell if a number is Odd or Even. All you need to do is see if it is a multiple of 2.

page revision: 9, last edited: 09 Dec 2008 17:34
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License