Loops/Foreach: Difference between revisions
< Loops
Content added Content deleted
(JavaScript, Logo, Forth) |
m (Added to iteration category) |
||
Line 1: | Line 1: | ||
{{task}}Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. |
{{task}}[[Category:Iteration]]Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
Revision as of 18:31, 14 April 2008
Loops/Foreach
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop.
Common Lisp
(loop for i in list do (print i))
Forth
create a 3 , 2 , 1 , : .array ( a len -- ) cells bounds do i @ . cell +loop ; \ 3 2 1
Java
<java>Collection<Type> collect; ... for(Type i:collect){
System.out.println(i);
}</java>
JavaScript
This works for any object, as well as arrays.
for (var a in o) print(o[a]);
Logo
foreach [red green blue] [print ?]
Perl
<perl>foreach $i (@collect) {
print "$i\n";
}</perl> The keyword for can be used instead of foreach. If a variable ($i) is not given, then $_ is used.
PHP
<php>foreach ($collect as $i) {
echo "$i\n";
}</php>
Python
<python>for i in collect:
print i</python>