The loop for construct in common LISP is used to iterate over an iterable, similar to the for loop in other programming languages. It can be used for the following:
- This is used to set up variables for iteration.
- It can be used for conditionally terminate the iteration.
- It can be used for operating on the iterated elements.
The loop For construct can have multiple syntaxes.
Syntaxes:
(loop for variable in input_list
do (statements/conditions)
)
Here,
- input_list is the list that is to be iterated.
- The variable is used to keep track of the iteration.
- The statements/conditions are used to operate on the iterated elements.
- To iterate over the given range:
(loop for variable from number1 to number2
do (statements/conditions)
)
Here,
- The number1 is the starting number and number 2 is the ending number from the range.
- The variable is used to keep track of the iteration.
- The statements/conditions are used to operate on the iterated elements.
Example: LISP Program to print numbers in a range
Lisp
;range from 1 to 5
(loop for i from 1 to 5
;display each number
do (print i)
)
|
Output:
1
2
3
4
5
Example 2: LISP Program to iterate elements over a list.
Lisp
;list with 5 numbers
(loop for i in '(1 2 3 4 5)
;display each number
do (print i)
)
;list with 5 strings
(loop for i in '(JAVA PHP SQL HTML CSS)
;display each string
do (print i)
)
|
Output:
1
2
3
4
5
JAVA
PHP
SQL
HTML
CSS
Example 3: LISP Program to iterate each number from range and perform increment and decrement operations.
Lisp
;list with 5 numbers
(loop for i in '(1 2 3 4 5)
;display each number by incrementing each number by 5
do (print (incf i 5))
)
;list with 5 numbers
(loop for i in '(1 2 3 4 5)
;display each number by decrementing each number by 5
do (print (decf i 5))
)
|
Output:
6
7
8
9
10
-4
-3
-2
-1
0
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
04 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...