# Common Lisp's Loop Macro Examples for Beginners

• Iteration for each element in a list:
```> (loop for i in '(1 2 3) do (print i))
1
2
3
```
• Iteration for each cdr of a list:
```> (loop for i on '(1 2 3) do (print i))
(1 2 3)
(2 3)
(3)
```
• Iteration for each element in a vector:
```> (loop for i across #(1 2 3) do (print i))
1
2
3
```
• Iteration for each key of a hashtable:
```> (setf h (make-hash-table))
> (setf (gethash 'a h) 1)
> (setf (gethash 'b h) 2)
> (loop for k being the hash-key of h do (print k))
b
a
```
• Iteration for each value of a hashtable:
```> (loop for v being the hash-value of h do (print v))
2
1
```
• Iteration for each key-value pair of a hashtable:
```> (loop for k being the hash-key using (hash-value v) of h do (format t "~a ~a~%" k v))
b 2
a 1
```
• i=1, while i <= 3:
```> (loop for i from 1 to 3 do (print i))
1
2
3
```
• i=1, while i <= 3: (different step)
```> (loop for i from 1.0 to 3.0 by 0.5 do (print i))
1.0
1.5
2.0
2.5
3.0
```
• i=3, while i >= 1:
```> (loop for i from 3 downto 1 do (print i))
3
2
1
```
• i=3, while i >= 1: (different step)
```> (loop for i from 3.0 downto 1.0 by 0.5 do (print i))
3.0
2.5
2.0
1.5
1.0
```
• i=1, while i < 3:
```> (loop for i from 1 below 3 do (print i))
1
2
```
• i=3, while i > 1:
```> (loop for i from 3 above 1 do (print i))
3
2
```
• Adding initialization:
```> (loop with a = '(1 2 3) for i in a do (print i))
1
2
3
```
• Adding subordinate variables:
```> (loop for i from 1 to 3 for x = (* i i) do (print x))
1
4
9
```
• Adding conditional branch for each element:
```> (loop for i from 1 to 3 when (oddp i) do (print i))
1
3
```
• Adding a termination condition (while):
```> (loop for i from 1 to 3 while (< i 2) do (print i))
1
```
• Adding a termination condition (until):
```> (loop for i from 1 to 3 until (< 2 i) do (print i))
1
2
```
• Collecting results as an element of a list:
```> (loop for i from 1 to 3 collect (* i i))
(1 4 9)
```
• Concatenating results as a list:
```> (loop for i from 1 to 3 append (list i i))
(1 1 2 2 3 3)
```
• Counting:
```> (loop for i from 1 to 3 count (oddp i))
2
```
• Summation:
```> (loop for i from 1 to 3 sum (* i i))
14
```
• Taking the maximum value:
```> (loop for i from 1 to 3 maximize (mod i 3))
2
```
• Taking the minimum value:
```> (loop for i from 1 to 3 minimize (mod i 3))
0
```

Yusuke Shinyama