Loops/Foreach: Difference between revisions

From Rosetta Code
Content added Content deleted
(Created task with Java)
 
(added perl and python)
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}}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|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
Line 7: Line 8:
System.out.println(i);
System.out.println(i);
}</java>
}</java>

=={{header|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.

=={{header|Python}}==
<python>for i in collect:
print i</python>

Revision as of 07:09, 13 April 2008

Task
Loops/Foreach
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.

Java

Works with: Java version 1.5+

<java>Collection<Type> collect; ... for(Type i:collect){

  System.out.println(i);

}</java>

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.

Python

<python>for i in collect:

  print i</python>