Lisp - dotimes construct



The dotimes construct allows looping for some fixed number of iterations.

Syntax

(dotimes (n range)
   statement1
   ...
)
  • n − initial value, set as 0.

  • range − last value till the end of loop.

  • statement1 − statement(s) to be evaluated.

Example - Square of Numbers

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

main.lisp

; perform a dotimes operation on list of numbers
(dotimes (n 11)
   (print n) (prin1 (* n n)) ; print n and square of n
)

Output

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

0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100

Example - Qube of Numbers

Update the source code file named main.lisp and type the following code in it −

main.lisp

; perform a dotimes operation on list of numbers
(dotimes (n 11)
   (print n) (prin1 (* n(* n n))) ; print n and qube of n
)

Output

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

0 0
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000

Example - Double of a Number

Update the source code file named main.lisp and type the following code in it −

main.lisp

; perform a dotimes operation on list of numbers
(dotimes (n 11)
   (print n) (prin1 (+ n n)); print n and double of n
)

Output

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

0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
lisp_loops.htm
Advertisements