Loops/Foreach: Difference between revisions

From Rosetta Code
Content added Content deleted
(add link to Delphi for pascal)
Line 818: Line 818:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>for(i=1,#v,print(v[i]))</lang>
<lang parigp>for(i=1,#v,print(v[i]))</lang>

=={{header|Pascal}}==
See [[Loops/Foreach#Delphi | Delphi]]


=={{header|Perl}}==
=={{header|Perl}}==

Revision as of 20:17, 27 October 2011

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.


Ada

arrays

<lang Ada>with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure For_Each is

  A : array (1..5) of Integer := (-1, 0, 1, 2, 3);

begin

  for Num in A'Range loop
     put( A (Num) );
  end loop;

end For_Each;</lang>

doubly linked lists

Works with: Ada 2005

<lang Ada>with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists; use Ada.Integer_Text_IO, Ada.Containers;

procedure Doubly_Linked_List is

  package DL_List_Pkg is new Doubly_Linked_Lists (Integer);
  use     DL_List_Pkg;
  procedure Print_Node (Position : Cursor) is
  begin
     Put (Element (Position));
  end Print_Node;
  
  DL_List : List;
  

begin

  DL_List.Append (1);
  DL_List.Append (2);
  DL_List.Append (3);
  
  -- Iterates through every node of the list.
  DL_List.Iterate (Print_Node'Access);
  

end Doubly_Linked_List;</lang>

vectors

Works with: Ada 2005

<lang Ada>with Ada.Integer_Text_IO, Ada.Containers.Vectors; use Ada.Integer_Text_IO, Ada.Containers;

procedure Vector_Example is

  package Vector_Pkg is new Vectors (Natural, Integer);
  use     Vector_Pkg;
  procedure Print_Element (Position : Cursor) is
  begin
     Put (Element (Position));
  end Print_Element;
  
  V : Vector;
  

begin

  V.Append (1);
  V.Append (2);
  V.Append (3);
     
  -- Iterates through every element of the vector.
  V.Iterate (Print_Element'Access);
  

end Vector_Example;</lang>

Aikido

Aikido's foreach loop allows iteration through multiple value types.

strings

<lang aikido> var str = "hello world" foreach ch str { // you can also use an optional 'in'

   println (ch)   // one character at a time

} </lang>

vectors

<lang aikido> var vec = [1,2,3,4] foreach v vec { // you can also use an optional 'in'

   println (v)

}

</lang>

maps

<lang aikido> var cities = {"San Ramon": 50000, "Walnut Creek": 70000, "San Francisco": 700000} // map literal foreach city cities {

   println (city.first + " has population " + city.second)

}

</lang>

integers

<lang aikido> foreach i 100 {

   println (i)    // prints values 0..99

}

foreach i 10..20 {

   println (i)     // prints values 10..20

}

var a = 20 var b = 10 foreach i a..b {

   println (i)   // prints values from a to b (20..10)

}

</lang>

Objects

Aikido allows definition of a foreach operator for an object. In this example we define a single linked list and a foreach operator to iterate through it <lang aikido> class List {

   class Element (public data) {
       public var next = null
   }
   var start = null
   public function insert (data) {
       var element = new Element (data)
       element.next = start
       start = element
   }
   public operator foreach (var iter) {
       if (typeof(iter) == "none") {   // first iteration
           iter = start
           return iter.data
       } elif (iter.next == null) {    // check for last iteration
           iter = none
       } else {
           iter = iter.next      // somewhere in the middle
           return iter.data
       }
   }

}

var list = new List() list.insert (1) list.insert (2) list.insert (4)

foreach n list {

   println (n)

}


</lang>

Coroutines

Aikido supports coroutines. The foreach operator may be used to iterate thorough the generated values. <lang aikido>

// coroutine to generate the squares of a sequence of numbers function squares (start, end) {

   for (var i = start ; i < end ; i++) {
       yield i*i
   }

}

var start = 10 var end = 20

foreach s squares (start, end) {

   println (s)

}

</lang>

Files

If you open a file you can iterate through all the lines <lang aikido> var s = openin ("input.txt") foreach line s {

   print (line)

}

</lang>

Enumerations

<lang aikido> enum Color {

  RED, GREEN, BLUE

}

foreach color Color {

   println (color)

}


</lang>

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386

<lang algol68>[]UNION(STRING, INT, PROC(REF FILE)VOID) collection = ("Mary","Had",1,"little","lamb.",new line);

FOR index FROM LWB collection TO UPB collection DO

 print((collection[index]," "))

OD</lang> Output:

Mary Had          +1 little lamb.

Note: ALGOL 68S actually has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel.

AmigaE

<lang amigae>PROC main()

 DEF a_list : PTR TO LONG, a
 a_list := [10, 12, 14]
 FOR a := 0 TO ListLen(a_list)-1
   WriteF('\d\n', a_list[a])
 ENDFOR
 -> if the "action" fits a single statement, we can do instead
 ForAll({a}, a_list, `WriteF('\d\n', a))

ENDPROC</lang>

AutoHotkey

<lang AutoHotkey>string = mary,had,a,little,lamb Loop, Parse, string, `,

 MsgBox %A_LoopField%</lang>

AWK

The for (element_index in array) can be used, but it does not give elements' indexes in the order inside the array (AWK indexes in array are indeed more like hashes).

<lang awk>BEGIN {

 split("Mary had a little lamb", strs, " ")
 for(el in strs) {
   print strs[el]
 }

}</lang>

If elements must be returned in some order, keys must be generated in that order; in the example above the array is filled through the split function, which uses indexes from 1, so to iterate over the array's elements in the right order, a normal loop can be done:

<lang awk>for(i=1; i <= length(strs); i++) {

 print strs[i]

}</lang>

C

C does not really have a native 'container' type, nor does it have a 'for each' type statement. The following shows how to loop through an array and print each element. <lang c>#include <stdio.h> ...

const char *list[] = {"Red","Green","Blue","Black","White"};

  1. define LIST_SIZE (sizeof(list)/sizeof(list[0]))

int ix; for(ix=0; ix<LIST_SIZE; ix++) {

  printf("%s\n", list[ix]);

}</lang>

C++

C++03 did not have a "for each" loop. The following is a generic loop which works with any standard container except for built-in arrays. The code snippet below assumes that the container type in question is typedef'd to container_type and the actual container object is named container. <lang cpp>for (container_type::iterator i = container.begin(); i != container.end(); ++i) {

 std::cout << *i << "\n";

}</lang> However the idiomatic way to output a container would be <lang cpp>std::copy(container.begin(), container.end(),

         std::output_iterator<container_type::value_type>(std::cout, "\n"));</lang>

There's also an algorithm named for_each. However, you need a function or function object to use it, e.g. <lang cpp>void print_element(container_type::value_type const& v) {

 std::cout << v << "\n";

}

...

 std::for_each(container.begin(), container.end(), print_element);</lang>
Works with: C++11

<lang cpp>#include <iterator_concepts>

for (auto element: container) {

 std::cout << element << "\n";

}</lang> Here container is the container variable, element is the loop variable (initialized with each container element in turn), and auto means that the compiler should determine the correct type of that variable automatically. If the type is expensive to copy, a const reference can be used instead: <lang cpp>#include <iterator_concepts>

for (auto const& element: container) {

 std::cout << element << "\n";

}</lang> Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant).

C#

<lang csharp>string[] things = {"Apple", "Banana", "Coconut"};

foreach (string thing in things) {

   Console.WriteLine(thing);

}</lang>

Clojure

<lang lisp>(doseq [item collection] (println item))</lang>

CMake

<lang cmake>set(list one.c two.c three.c)

foreach(file ${list})

 message(${file})

endforeach(file)</lang>

Common Lisp

<lang lisp>(loop for i in list do (print i))</lang> or <lang lisp>(map nil #'print list)</lang>

D

This works if collection is an array/associative array type or any type that implements an appropriate opApply function. <lang d>foreach(element ; collection)

 writefln(element);</lang>

Dao

<lang dao>items = { 1, 2, 3 } for( item in items ) io.writeln( item )</lang>

Delphi

Supports arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator().

<lang Delphi>program LoopForEach;

{$APPTYPE CONSOLE}

var

 s: string;

begin

 for s in 'Hello' do
   Writeln(s);

end.</lang>

Output:

H
e
l
l
o

E

<lang e>for e in theCollection {

   println(e)

}</lang>

In E, the for ... in ... loop is also used for iterating over numeric ranges; see Loop/For#E.

Efene

Any data structure can be printed as a whole, preformated: <lang efene>io.format("~p~n", [Collection])</lang>

However, to iterate over each element of a list, Efene uses lists.map/2, except in the case of IO where lists.foreach/2 has to be used as the evaluation order is defined to be the same as the order of the elements in the list. <lang efene>lists.foreach(fn (X) { io.format("~p~n", [X]) }, Collection)</lang>

Eiffel

Works with: EiffelStudio version 6.6 beta (with provisional loop syntax)

The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword across.

<lang eiffel > across my_list as ic loop print (ic.item) end</lang>

The local entity ic is an instance of the library class ITERATION_CURSOR. The cursor's feature item provides access to each structure element. Descendants of class ITERATION_CURSOR can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (my_list in the example) are based on classes that inherit from the library class ITERABLE

Boolean expression variant

The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword loop is replaced by either all (effecting universal quantification) or some (effecting existential quantification).

This iteration is a boolean expression which is true if all items in my_list have counts greater than three:

<lang eiffel> across my_list as ic all ic.item.count > 3 end</lang>

Whereas, the following is true if at least one item has a count greater than three:

<lang eiffel> across my_list as ic some ic.item.count > 3 end</lang>

Ela

Standard Approach

<lang ela>open Con open Core

each writen [1..10]</lang>

Function 'each' is defined in standard Core module as:

<lang ela>let each f (x::xs) = f x $ each f xs

   each _ []      = ()</lang>

This also can be accomplished using 'map':

<lang ela>open Con open Core

let _ = map writen [1..10]</lang>

Alternate Approach

<lang ela>let each (x::xs) = writen x $ each xs

   each []      = ()

each [1..10] </lang>

Erlang

Any data structure can be printed as a whole, preformated: <lang erlang>io:format("~p~n",[Collection]).</lang>

However, to iterate over each element of a list, Erlang uses lists:map/2, except in the case of IO where lists:foreach/2 has to be used as the evaluation order is defined to be the same as the order of the elements in the list. <lang erlang>lists:foreach(fun(X) -> io:format("~p~n",[X]) end, Collection).</lang>

Factor

<lang factor>{ 1 2 4 } [ . ] each</lang>

Fantom

Use each method to iterate over a collection of items in a List.

<lang fantom> class Main {

 public static Void main ()
 {
   Int[] collection := [1, 2, 3, 4, 5]
   collection.each |Int item|
   {
     echo (item)
   }
 }

} </lang>

Fortran

<lang fortran>program main

implicit none
integer :: i
character(len=5),dimension(5),parameter :: colors = ['Red  ','Green','Blue ','Black','White']
!using a do loop:
do i=1,size(colors)
  write(*,'(A)') colors(i) 
end do
!this will also print each element:
write(*,'(A)') colors

end program main</lang>

Forth

<lang forth>create a 3 , 2 , 1 ,

.array ( a len -- )
 cells bounds do  i @ .  cell +loop ;     \ 3 2 1</lang>

F#

We can use for directly or list iteration. <lang fsharp>for i in [1 .. 10] do printfn "%d" i

List.iter (fun i -> printfn "%d" i) [1 .. 10]</lang>

Go

range works with all of the built-in container-types. With one variable (i), it gives you the key/index of every item. With two variables (i, x), it gives you both the key/index and value/item. For channels, only the single-variable variant is allowed.

<lang go>func printAll(values []int) {

  for i, x := range values {
     fmt.Printf("Item %d = %d\n", i, x)
  }

}</lang>

Groovy

"for" loop: <lang groovy>def beatles = ["John", "Paul", "George", "Ringo"]

for(name in beatles) {

   println name

}</lang>

"each()" method: Though technically not a loop, most Groovy programmers would use the somewhat more terse "each()" method on the list itself in preference to the "for" loop construct. <lang groovy>beatles.each {

   println it

}</lang>

Output (same for either):

John
Paul
George
Ringo

Haskell

<lang haskell>import Control.Monad (forM_) forM_ collect print</lang> which is the same as <lang haskell>mapM_ print collect</lang>

HaXe

<lang HaXe>for(i in 1...10) Lib.println(i);</lang>

HicEst

<lang hicest>CHARACTER days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday "

items = INDEX(days, ' ', 256)  ! 256 = count option DO j = 1, items

 EDIT(Text=days, ITeM=j, Parse=today)
 WRITE() today

ENDDO</lang>

Io

<lang io>collection foreach(println)</lang>

Icon and Unicon

The example below X can be a list, string, table or other data type. <lang Icon>procedure main() X := [1,2,3,-5,6,9] every x := !L do

  write(x)

end</lang>

This loop can be written somewhat more concisely as: <lang Icon>every write(!L)</lang>

J

<lang J>smoutput each i.10</lang>

Java

Works with: Java version 1.5+

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

  System.out.println(i);

}</lang> This works for any array type as well as any type that implements the Iterable interface (including all Collections).

JavaScript

This works for any object, as well as arrays. It iterates over the keys of an object. <lang JavaScript>for (var a in o) {

   print(o[a]);

}</lang> However, it has the often unwanted feature that it lists inherited properties and methods of objects as well as the ones directly set on the object -- consider whether to filter out such properties inside the loop, for example:

<lang JavaScript>for (var a in o) {

   if (o.hasOwnProperty(a)) {
       print(o[a]);
   }

}</lang>

Works with: JavaScript version 1.6

There is also a for each in construct that iterates over the values of an object: <lang JavaScript>h = {"one":1, "two":2, "three":3} for (x in h) print(x); /* two one three

  • /

for each (y in h) print(y); /* 2 1 3

  • /</lang>

Liberty BASIC

The most natural way is to use a csv list with a sentinel value. <lang lb> in$ ="Not,Hardly,Just,Adequately,Quite,Really,Very,Fantastically,xyzzy" element$ ="" i =1 ' used to point to successive elements

do

   element$ =word$( in$, i, ",")
   if element$ ="xyzzy" then exit do
   print element$; " good!"
   i =i +1

loop until 1 =2

end </lang>

Not good!
Hardly good!
Just good!
Adequately good!
Quite good!
Really good!
Very good!
Fantastically good!

Lisaac

<lang Lisaac>"Lisaac loop foreach".split.foreach { word : STRING;

 word.print;
 '\n'.print;

};</lang>

<lang logo>foreach [red green blue] [print ?]</lang>

Lua

Lua has 2 built-in iterators over tables.

pairs() iterates over all entries in a table, but in no particular order: <lang lua> t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"} for key, value in pairs(t) do

 print(value, key)

end </lang>

Output:

0	sunday
fooday	7
2	tuesday
3	wednesday
5	friday
4	thursday
6	saturday
1	monday

ipairs() iterates over table entries with positive integer keys, and is used to iterate over lists in order. <lang lua> l={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' } for key, value in ipairs(l) do

 print(key, value)

end </lang>

Output:

1	monday
2	tuesday
3	wednesday
4	thursday
5	friday
6	saturday
7	sunday

Note that ipairs() ignores non-numeric and non-positive integer keys.

Mathematica

Foreach over list of strings <lang mathematica>s = (StringSplit@Import["ExampleData/USConstitution.txt"])1;;7; Do[

Print@i,
{i, s}

]</lang>

Output:

We
the
People
of
the
United
States,

MAXScript

<lang maxscript>for i in collect do (

   print i

)</lang>

Metafont

If we have a list of arbitrary items, we can simply use for:

<lang metafont>for x = "mary", "had", "a", "little", "lamb": message x; endfor end</lang>

The list can be generated in place by any suitable macro or another loop... e.g. let us suppose we have things like a[n] defined (with maximum n being 10). Then

<lang metafont>for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor end</lang>

works more like a foreach; we could make a macro to hide the strangeness of such a code.

MOO

<lang moo>things = {"Apple", "Banana", "Coconut"};

for thing in (things)

   player:tell(thing);

endfor</lang>

Nemerle

This works on anything which implements the IEnumerable interface. <lang Nemerle>def things = ["Apple", "Banana", "Coconut"];

foreach (thing in things) WriteLine(thing.ToLower()); foreach (i in [5, 10 .. 100]) Write($"$i\t");</lang>

NetRexx

<lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols nobinary

 say
 say 'Loops/Foreach'
 days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
 daysl = Arrays.asList(days)
 daysi = daysl.iterator
 loop while daysi.hasNext
   say daysi.next
   end

</lang>

Nimrod

<lang Python>var list: seq[string] = @[] list.add("lorem") list.add("ipsum") list.add("dolor") for i in items(list):

 echo(i)</lang>

Output: <lang>lorem ipsum dolor</lang>

Objective-C

Works with: Objective-C version 2.0+
Works with: GNUstep
Works with: Cocoa

<lang objc>NSArray *collect; //... for(Type i in collect){

  NSLog(@"%@", i);

}</lang> collect can be any object that adopts the NSFastEnumeration protocol.

Or (always using OpenStep compatible frameworks):

Works with: Objective-C version <2.0

<lang objc>NSArray *collect; //... NSEnumerator *enm = [collect objectEnumerator]; id i; while( (i = [enm nextObject]) ) {

 // do something with object i

}</lang>


Objeck

<lang objeck> fruits := ["Apple", "Banana", "Coconut"]; each(i : fruits) {

 fruits[i]->PrintLine();

}; </lang>

OCaml

List of integers: <lang ocaml>List.iter

 (fun i -> Printf.printf "%d\n" i)
 collect_list</lang>

Array of integers: <lang ocaml>Array.iter

 (fun i -> Printf.printf "%d\n" i)
 collect_array</lang>

Octave

<lang octave>a = [ 1,4,3,2 ]; b = [ 1,2,3,4; 5,6,7,8 ]; for v = a

 disp(v); % output single values: 1,4,3,2

endfor for v = b

 disp(v); % v is the column vector [1;5], then [2;6] ...

endfor</lang>

We can also iterate over structures: <lang octave>x.a = [ 10, 11, 12 ]; x.b = { "Cell", "ul", "ar" }; for [ val, key ] = x

 disp(key);
 disp(val);

endfor</lang>

Oz

<lang oz>declare

 MyList = [1 2 3 4]

in

 {ForAll MyList Show}
 %% or:
 for E in MyList do {Show E} end</lang>

PARI/GP

<lang parigp>for(i=1,#v,print(v[i]))</lang>

Pascal

See Delphi

Perl

<lang perl>foreach my $i (@collection) {

  print "$i\n";

}</lang>

The keyword for can be used instead of foreach. If a loop variable (here $i) is not given, then $_ is used.

A more compact notation using perl statement modifier: <lang perl>print "$_\n" foreach @collection</lang>

Perl 6

Works with: Rakudo version #21 "Seattle"

<lang perl6>say $_ for @collection;</lang>

Perl 6 leaves off the each from foreach, leaving us with for instead. The variable $_ refers to the current element, unless you assign a name to it using ->.

<lang perl6>for @collection -> $currentElement { say $currentElement; }</lang>

PHP

<lang php>foreach ($collect as $i) {

  echo "$i\n";

}

foreach ($collect as $key => $i) {

  echo "\$collect[$key] = $i\n";

}</lang> foreach can also iterate over objects. By default it iterates over all visible fields of an object.

PicoLisp

<lang PicoLisp>(mapc println '(Apple Banana Coconut))</lang>

Pike

<lang pike>int main(){

  array(int|string) collect = ({109, "Hi", "asdf", "qwerty"});
  foreach(collect, int|string elem){
     write(elem + "\n");
  }

}</lang>

Iterating over the keys and values of a mapping (dictionary): <lang pike>int main(){

   mapping(string:string) coll = (["foo":"asdf", "bar":"qwer", "quux":"zxcv"]);
   foreach (coll;string key;string val)
       write(key+" --> "+val+"\n");
   }

}</lang>

PL/I

<lang PL/I> declare A(10) fixed binary; do i = lbound(A,1) to hbound(A,1);

  put skip list (A(i));

end; </lang>

Pop11

Iteration over list: <lang pop11>lvars el, lst = [1 2 3 4 foo bar]; for el in lst do

  printf(el,'%p\n');

endfor;</lang>

PostScript

The forall operator performs a loop over a collection (array, string or dictionary). Strings and arrays can be treated very much the same: <lang postscript>[1 5 3 2] { = } forall (abc) { = } forall</lang> but dictionaries take a little more work since a key/value pair is pushed on the stack in each iteration: <lang postscript><</a 25 /b 42>> {

 exch (Key: ) print
 =
 (Value: ) print
 =

} forall</lang>

PowerShell

<lang powershell>foreach ($x in $collection) {

   Write-Host $x

}</lang>

PureBasic

Works for LinkedLists and Maps <lang PureBasic>ForEach element()

 PrintN(element())

Next</lang>

Python

<lang python>for i in collection:

  print i</lang>

Note: The Python for statement is always a "foreach" ... and the range() and xrange() built-in functions are used to generate lists of indexes over which it will iterate as necessary. The majority of Python objects support iteration. Lists and tuples iterate over each item, strings iterate over each character, dictionaries iterate over keys, files iterate over lines, and so on.

For example:

<lang python>lines = words = characters = 0 f = open('somefile','r') for eachline in f:

   lines += 1
   for eachword in eachline.split():
       words += 1
       for eachchar in eachword:
           chracters += 1

print lines, words, characters</lang>

R

<lang R>a <- list("First", "Second", "Third", 5, 6) for(i in a) print(i)</lang>

REBOL

<lang REBOL>REBOL [ Title: "Loop/Foreach" Author: oofoe Date: 2009-12-19 URL: http://rosettacode.org/wiki/Loop/Foreach ]

x: [Sork Gun Blues Neds Thirst Fright Catur]

foreach i x [prin rejoin [i "day "]] print ""

REBOL also has the 'forall' construct, which provides the rest of
the list from the current position.

forall x [prin rejoin [x/1 "day "]] print ""</lang>

Output:

Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday
Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday

REXX

Standard REXX: <lang rexx>days = "sunday monday tuesday wednesday thursday friday saturday"

do d = 1 to words(days)

 say word(days,d)

end</lang> or: <lang rexx>days = "sunday monday tuesday wednesday thursday friday saturday"

hlp = days do while hlp <> ""

 parse var hlp item hlp
 say item

end</lang>

Works with: oorexx

:

<lang rexx>colors = .bag~of("red","green","blue","pink")

do c over colors

 say c

end</lang>


Ruby

<lang ruby>for i in collection do

 puts i

end</lang>

This is syntactic sugar for:

<lang ruby>collection.each do |i|

 puts i

end</lang>

There are various flavours of each that may be class-dependent: String#each_char, Array#each_index, Hash#each_key, etc

Sather

<lang sather>class MAIN is

 main is
    num:ARRAY{INT} := |1, 5, 4, 3, 10|;
    loop
      -- the iterator elt! behaves like a "foreach",
      -- yielding the next element of the array at each iteration
      #OUT + num.elt! + "\n";
    end;
 end;

end;</lang>

Scala

<lang scala>val collection = Array(1, 2, 3, 4) for (element <- collection)

 println(element)</lang>

Alternatively:

<lang scala>for (element <- 1 to 4)

 println(element)</lang>

Scheme

List: <lang scheme>(for-each

 (lambda (i) (display i) (newline))
 the_list)</lang>

Seed7

The for loop of Seed7 can be used to loop over the elements of a container. <lang seed7>$ include "seed7_05.s7i";

var array string: things is [] ("Apple", "Banana", "Coconut");

const proc: main is func

 local
   var string: thing is "";
 begin
   for thing range things do
     writeln(thing);
   end for;
 end func;</lang>

Slate

<lang slate>c do: [| :obj | print: obj].</lang>

Smalltalk

<lang smalltalk>aCollection do: [ :element | element displayNl ].</lang>

(Provided that the objects in the collection understand the displayNl method).

Standard ML

List of integers: <lang sml>app

 (fn i => print (Int.toString i ^ "\n"))
 collect_list</lang>

Array of integers: <lang sml>Array.app

 (fn i => print (Int.toString i ^ "\n"))
 collect_array</lang>

Suneido

<lang Suneido>for i in #(1, 2, 3)

   Print(i)</lang>    

SystemVerilog

<lang SystemVerilog>program main;

 int values[$];
 initial begin
   values = '{ 1, 3, 7, 11 };
   foreach (values[i]) begin
      $display( "%0d --> %0d", i, values[i] );
   end
 end

endprogram</lang>

Tcl

<lang tcl>foreach i {foo bar baz} {

   puts "$i"

}</lang> Note that foreach also accepts multiple variables: <lang tcl>foreach {x y} {1 2 3 4} {

   puts "$x,$y"

}</lang> And also multiple lists: <lang tcl>foreach i {1 2 3} j {a b c} {

   puts "$i,$j"

}</lang> Or any combination of variables/list: <lang tcl>foreach i {1 2 3} {x y} {a b c d e f} {

   puts "$i,$x,$y"

}</lang>

TI-89 BASIC

<lang ti89b>Local i,strs Define strs = {"Lorem","ipsum","dolor"} For i, 1, dim(strs)

 Disp strs[i]

EndFor</lang>

Trith

<lang trith>[1 2 3 4 5] [print] each</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT LOOP/CLEAR i=2,9,2 PRINT i ENDLOOP </lang> Output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saterday
Sunday 

UNIX Shell

To iterate any single list, you use a for loop.

Works with: Bourne Shell

<lang bash>for file in *.sh; do

 echo "filename is $file"

done</lang>

If the list is in a shell parameter (like PATH), you adjust IFS.

Works with: Bourne Shell

<lang bash>PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin

oldifs=$IFS IFS=: for dir in $PATH; do

 echo search $dir

done IFS=$oldifs</lang>


Some shells have real arrays. The for loop can also iterate these.

Works with: Bash

<lang bash>collection=("first" "second" "third" "fourth" "something else") for x in "${collection[@]}"; do

 echo "$x"

done</lang>

Works with: pdksh version 5.2.14

<lang bash>set -A collection "first" "second" "third" "fourth" "something else" for x in "${collection[@]}"; do

 echo "$x"

done</lang>

C Shell

<lang csh>set collection=(first second third fourth "something else") foreach x ($collection:q) echo $x:q end</lang>

V

<lang v>[1 2 3] [puts] step</lang>

VBScript

<lang vbscript>dim items(2) items(0)="Apple" items(1)="Orange" items(2)="Banana"

For Each x in items

 WScript.Echo x

Next</lang>

Visual Basic .NET

<lang vbnet>Dim list As New List(Of String) list.Add("Car") list.Add("Boat") list.Add("Train")

For Each item In list

   Console.WriteLine(item)

Next</lang>

XSLT

For-each is the only iteration construct that is built into XSLT. All other iteration is either implied by applying a template to all members matching an XPath expression, or built from recursive application of a template. You have access to something like a loop counter with the one-based "position()" function. <lang xml><fo:block font-weight="bold">Adults:</fo:block> <xsl:for-each select="person[@age >= 21]">

 <fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>

</xsl:for-each></lang>