Arithmetic
Simply moving numbers around on a stack can be a lot of fun. Eventually, however, you'll want to do something useful with them. This section describes how to perform arithmetic operations in Forth.
The Forth arithmetic operators work on the numbers currently on top of the stack. If you want to add the top two numbers together, use the Forth word +, pronounced plus. Enter:
2 3 + .
2 3 + 10 + .
This style of expressing arithmetic operations is called Reverse Polish Notation, or RPN. It will already be familiar to those of you with HP calculators. In the following examples, I have put the algebraic equivalent representation in a comment.
Some other arithmetic operators are - * /. Enter:
30 5 - . | 25=30-5
30 5 / . | 6=30/5
30 5 * . | 150=30*5
30 5 + 7 / . | 5=(30+5)/7
One thing that you should be aware of is that when you are doing division with integers using /, the remainder is lost. Enter:
15 5 / .
17 5 / .
This is true in all languages on all computers. When you need to know the remainder of a divide operation. /mod will return the remainder as well as the quotient, whereas mod will only return the remainder. Enter:
53 10 /mod .s
7 5 mod .s
Some other math words to try out:
negate ( a -- -a )
<< ( a n -- (a<<n) ) | Shift bits left
>> ( a n -- (a>>n) ) | Shift bits right
Convert Algebraic Expressions to Forth
How do we express complex algebraic expressions in Forth? For example: 20 + (3 * 4)?
To convert this to Forth you must order the operations in the order of evaluation. In Forth, therefore, this would look like:
3 4 * 20 +
Evaluation proceeds from left to right in Forth so there is no ambiguity. Compare the following algebraic expressions and their Forth equivalents: (Do not enter these!)
(100+50)/2 ==> 100 50 + 2 /
((2*7) + (13*5)) ==> 2 7 * 13 5 * +
If any of these expressions puzzle you, try entering them one word at a time, while viewing the stack with .s