Forth/Arithmetics

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Forth brings along all operators common in mathematics. It uses the reverse Polish notation (RPN) when processing calculations. This means that the operands are entered first and then the operator to be applied to them. The operator . outputs the topmost stack entry on the screen as an integer.

Simple examples[edit | edit source]

  • 1 2 + . shows 3 ok
  • 4 2 - . shows 2 ok
  • 1 2 * . shows 2 ok

More complex examples[edit | edit source]

  • 3 5 + 7 * . <cr> 56 ok interactively places first the number 3 on the stack and then the number 5 on it. The + (an elementary continue operation) is called, adds both values and replaces them on the stack with the result (8). Then 7 is placed on the stack and the result is calculated using *. Finally, the operator . outputs the topmost stack entry on the screen as an integer. With the concluding ok, Forth indicates that the line is processed and the system is ready for new tasks.