Lisp - Arithmetic Operators



The following table shows all the arithmetic operators supported by LISP. Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example
+ Adds two operands (+A B) will give 30
- Subtracts second operand from the first (- A B) will give -10
* Multiplies both operands (* A B) will give 200
/ Divides numerator by de-numerator (/ B A) will give 2
mod,rem Modulus Operator and remainder of after an integer division (mod B A )will give 0
incf Increments operator increases integer value by the second argument specified (incf A 3) will give 13
decf Decrements operator decreases integer value by the second argument specified (decf A 4) will give 9

Example - Arithmetic Operators

Create a new source code file named main.lisp and type the following code in it.

main.lisp

; set a as 10
(setq a 10)
; set b as 20
(setq b 20)
; perform sum 
(format t "~% A + B = ~d" (+ a b))
; perform substraction
(format t "~% A - B = ~d" (- a b))
; perform product
(format t "~% A x B = ~d" (* a b))
; perform multiplication
(format t "~% B / A = ~d" (/ b a))

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

A + B = 30
A - B = -10
A x B = 200
B / A = 2

Example - Increment/Decrement Operators

Update main.lisp and type the following code in it.

main.lisp

; set a as 10
(setq a 10)
; increment a by 3
(format t "~% Increment A by 3 = ~d" (incf a 3))
; decrement a by 4
(format t "~% Decrement A by 4 = ~d" (decf a 4))

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

Increment A by 3 = 13
Decrement A by 4 = 9

Example - Mod/Rem Operators

Update main.lisp and type the following code in it.

main.lisp

; set a as 10
(setq a 10)
; Modulus of a by 3
(format t "~% Mod A by 3 = ~d" (mod a 3))
; Remainder of a by 3
(format t "~% Rem A by 3 = ~d" (rem a 3))

Output

When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −

Mod A by 3 = 1
Rem A by 3 = 1
lisp_operators.htm
Advertisements