Mathematical Expressions


Mathematical expressions allow you to make calculations. The results of a calculation can either be printed to the screen using the PRINT statement or stored in the computers memory for later use. Let us look at using it in a PRINT statement. In a later section entitled Variables we will talk about storing results of a calculation in the computers memory.

Mathematical expressions contain both numbers and operators. Operators are the mathematical symbols that tell us what to do with the number. For example the + operator tells us to add the numbers together. Therfore, it is called the Addition Operator. In mathematics we sometimes use different operator symbols than are used on the computer. For example, to multiply a number together we might write down 5 x 2 on paper, but on the computer we would write 5 * 2. Here are a list of common operators and their computer equivalent:

Operator Symbol Name of Symbol Example Result
Addition
Subtraction
Multiplication
Division
Exponent
+
-
*
/
^
Plus Sign
Minus Sign
Asterisk
Forward Slash
Caret
5+2
5-2
5*2
5/2
5^2
7
3
10
2.5
25

Calculations in Liberty BASIC also follow the Order of Operations defined in mathematics. Therefore all calculations are done in the following order (from left to right):

  1. Brackets
  2. Exponents
  3. Division and Multiplication
  4. Addition and Subtraction

Therefore, the expression

3 + 2 * 4

gives a result of

11

We got a result of 11 and not 20. This is because according to the Order of Operations Division and Multiplication are done before Addition and Subtraction. If we had wanted the addition to be done first we would need to enclose it in brackets.

(3 + 2) * 4

now gives a result of

20

Now we get a result of 20 because according to the Order of Operations Brackets come before Divsion and Multiplication.

Using Mathematical Expressions in a PRINT Statement

You may simply put mathematical expressions in a print statement the same way you did for printing numerics and strings. For example,

print 5 * (4 + 6)

gives the following result in the run window:

50

You may also use the semi-colon to join a mathematical expression with numeric and string data. For example, consider the following program code with its run screen:


Notice that when we run our code we do not see the calculation on the run screen and would not even realize one was being made.

As a side note, there is a slight problem with the above code. Notice that the above example takes the current year and subtracts from it the year you were born. The code assumes that you have had your birthday already. Therefore if you have it gives you the correct answer, however, if your birthday is in another month or two (or even tomorrow) it will be out by one. This is because we did not take into account the month and day, but only the year.