Loops/Foreach: Difference between revisions

→‎{{header|Objective-C}}: conventional syntax
(added ReScript)
(→‎{{header|Objective-C}}: conventional syntax)
 
(43 intermediate revisions by 28 users not shown)
Line 26:
{{trans|C#}}
 
<langsyntaxhighlight lang="11l">V things = [‘Apple’, ‘Banana’, ‘Coconut’]
 
L(thing) things
print(thing)</langsyntaxhighlight>
 
=={{header|ACL2}}==
 
<langsyntaxhighlight Lisplang="lisp">(defun print-list (xs)
(if (endp xs)
nil
(prog2$ (cw "~x0~%" (first xs))
(print-list (rest xs)))))</langsyntaxhighlight>
 
<pre>
Line 47:
SYM
NIL
</pre>
 
=={{header|Action!}}==
In Action! there is no for-each loop.
<syntaxhighlight lang="action!">PROC Main()
DEFINE PTR="CARD"
BYTE i
PTR ARRAY items(10)
items(0)="First" items(1)="Second"
items(2)="Third" items(3)="Fourth"
items(4)="Fifth" items(5)="Sixth"
items(6)="Seventh" items(7)="Eighth"
items(8)="Ninth" items(9)="Tenth"
 
PrintE("In Action! there is no for-each loop")
PutE()
FOR i=0 TO 9
DO
PrintE(items(i))
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Foreach.png Screenshot from Atari 8-bit computer]
<pre>
In Action! there is no for-each loop
 
First
Second
Third
Fourth
Fifth
Sixth
Seventh
Eighth
Ninth
Tenth
</pre>
 
=={{header|Ada}}==
===arrays===
<langsyntaxhighlight Adalang="ada">with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
 
Line 64 ⟶ 100:
end loop;
 
end For_Each;</langsyntaxhighlight>
 
Alternative solution (Ada 2012):
 
<langsyntaxhighlight Adalang="ada"> for Item of A loop
Put( Item );
end loop;</langsyntaxhighlight>
 
===doubly linked lists===
{{works with|Ada 2005}}
<langsyntaxhighlight Adalang="ada">with Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists;
use Ada.Integer_Text_IO, Ada.Containers;
 
Line 98 ⟶ 134:
DL_List.Iterate (Print_Node'Access);
end Doubly_Linked_List;</langsyntaxhighlight>
===vectors===
{{works with|Ada 2005}}
<langsyntaxhighlight Adalang="ada">with Ada.Integer_Text_IO, Ada.Containers.Vectors;
use Ada.Integer_Text_IO, Ada.Containers;
 
Line 125 ⟶ 161:
V.Iterate (Print_Element'Access);
end Vector_Example;</langsyntaxhighlight>
 
=={{header|Aikido}}==
Aikido's <code>foreach</code> loop allows iteration through multiple value types.
===strings===
<langsyntaxhighlight lang="aikido">var str = "hello world"
foreach ch str { // you can also use an optional 'in'
println (ch) // one character at a time
}</langsyntaxhighlight>
===vectors===
<langsyntaxhighlight lang="aikido">var vec = [1,2,3,4]
foreach v vec { // you can also use an optional 'in'
println (v)
}</langsyntaxhighlight>
===maps===
<langsyntaxhighlight 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)
}</langsyntaxhighlight>
===integers===
<langsyntaxhighlight lang="aikido">foreach i 100 {
println (i) // prints values 0..99
}
Line 157 ⟶ 193:
foreach i a..b {
println (i) // prints values from a to b (20..10)
}</langsyntaxhighlight>
===Objects===
Aikido allows definition of a <code>foreach</code> operator for an object. In this example we define a single linked list and a foreach operator to iterate through it
<langsyntaxhighlight lang="aikido">class List {
class Element (public data) {
public var next = null
Line 193 ⟶ 229:
foreach n list {
println (n)
}</langsyntaxhighlight>
===Coroutines===
Aikido supports coroutines. The foreach operator may be used to iterate thorough the generated values.
<langsyntaxhighlight lang="aikido">// coroutine to generate the squares of a sequence of numbers
function squares (start, end) {
for (var i = start ; i < end ; i++) {
Line 208 ⟶ 244:
foreach s squares (start, end) {
println (s)
}</langsyntaxhighlight>
===Files===
If you open a file you can iterate through all the lines
<langsyntaxhighlight lang="aikido">var s = openin ("input.txt")
foreach line s {
print (line)
}</langsyntaxhighlight>
===Enumerations===
<langsyntaxhighlight lang="aikido">enum Color {
RED, GREEN, BLUE
}
Line 222 ⟶ 258:
foreach color Color {
println (color)
}</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime"># iterate over a list of integers
integer i, v;
 
for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) {
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 235 ⟶ 271:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight 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</langsyntaxhighlight>
Output:
<pre>
Mary Had +1 little lamb.
</pre>
<br>
Note: [[ALGOL 68S]] actually has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel.
[[ALGOL 68S]] has a reserved word FOREACH that is used to break arrays in to portions, and process in parallel.
<br>
<br>[[ALGOL 68RS]] and [[Algol68toc]] have a FORALL loop, the following is equivalent to the example above:
<syntaxhighlight lang="algol68">FORALL c IN collection DO
print((c," "))
OD</syntaxhighlight>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <jambo.h>
 
Main
things = {}, len list=0
Set ' 100,200,300,"Hello world!", -3,-2,-1 ' Apndlist 'things'
Let ' len list := Length(things) '
Printnl ' "\nNormal count:\n" '
For each( n, things, len list )
Printnl ' "Thing : ", n '
Next
 
Printnl ' "\n\nReverse count:\n" '
For each reverse ( n, things, len list )
Printnl ' "Thing : ", n '
Next
End
</syntaxhighlight>
{{out}}
<pre>
Normal count:
 
Thing : 100
Thing : 200
Thing : 300
Thing : Hello world!
Thing : -3
Thing : -2
Thing : -1
 
 
Reverse count:
 
Thing : -1
Thing : -2
Thing : -3
Thing : Hello world!
Thing : 300
Thing : 200
Thing : 100
 
</pre>
 
=={{header|AmigaE}}==
<langsyntaxhighlight lang="amigae">PROC main()
DEF a_list : PTR TO LONG, a
a_list := [10, 12, 14]
Line 255 ⟶ 342:
-> if the "action" fits a single statement, we can do instead
ForAll({a}, a_list, `WriteF('\d\n', a))
ENDPROC</langsyntaxhighlight>
 
=={{header|Apex}}==
<syntaxhighlight lang="apex">
<lang Apex>
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
Line 264 ⟶ 351:
System.debug(i);
}
</syntaxhighlight>
</lang>
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript">repeat with fruit in {"Apple", "Orange", "Banana"}
log contents of fruit
end repeat</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">arr: ["one" "two" "three"]
 
dict: #[
Line 284 ⟶ 371:
 
loop dict [key val]->
print [key "=>" val]</langsyntaxhighlight>
{{out}}
<pre>one
Line 294 ⟶ 381:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">string = mary,had,a,little,lamb
Loop, Parse, string, `,
MsgBox %A_LoopField%</langsyntaxhighlight>
 
=={{header|AWK}}==
The <code>for (element_index in array)</code> 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).
<langsyntaxhighlight lang="awk">
BEGIN {
split("Mary had a little lamb", strs, " ")
Line 306 ⟶ 393:
print strs[el]
}
}</langsyntaxhighlight>
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,
Line 312 ⟶ 399:
So to iterate over the array's elements in the ''right'' order,
a normal loop can be used:
<langsyntaxhighlight lang="awk">BEGIN {
n = split("Mary had a little lamb", strs, " ")
for(i=1; i <= n; i++) {
print strs[i]
}
}</langsyntaxhighlight>
 
Note that in awk, foreach loops can only be performed against an associative container.
It is not possible to loop against an explicit list, so the following will not work:
 
<langsyntaxhighlight lang="awk"># This will not work
BEGIN {
for (el in "apples","bananas","cherries") {
print "I like " el
}
}</langsyntaxhighlight>
 
=={{header|Bait}}==
`for-in` loops work with both builtin container types (arrays and maps).
They allow to iterate the indices/keys and values.
 
<syntaxhighlight lang="bait">
fun for_in_array() {
arr := ['1st', '2nd', '3rd']
 
// Iterate over array indices and elements
for i, val in arr {
println('${i}: ${val}')
}
 
// Using only one variable will iterate over the elements
for val in arr {
println(val)
}
 
// To only iterate over the indices, use `_` as the second variable name.
// `_` is a special variable that will ignore any assigned value
for i, _ in arr {
println(i)
}
}
 
fun for_in_map() {
nato_abc := map{
'a': 'Alpha'
'b': 'Bravo'
'c': 'Charlie'
'd': 'Delta'
}
 
// Iterate over map keys and values.
// Note that, unlike arrays, only the two-variable variant is allowed
for key, val in nato_abc {
println('${key}: ${val}')
}
}
 
fun main() {
for_in_array()
println('')
for_in_map()
}
</syntaxhighlight>
 
=={{header|BASIC}}==
Line 334 ⟶ 468:
BaCon includes support for ''delimited strings''. Delimited strings form a type of collection. Along with this support is a <code>for in</code> loop. Not quite a <code>for each</code> but pretty close.
 
<langsyntaxhighlight lang="freebasic">OPTION COLLAPSE TRUE
FOR x$ IN "Hello cruel world"
PRINT x$
Line 341 ⟶ 475:
FOR y$ IN "1,2,\"3,4\",5" STEP ","
PRINT y$
NEXT</langsyntaxhighlight>
 
{{out}}
Line 358 ⟶ 492:
==={{header|BASIC256}}===
BASIC-256 does not have a FOR EACH type statement. Use a FOR loop to iterate through an array by index.
<langsyntaxhighlight BASIC256lang="basic256">DIM collection$(1)
collection$ = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }
 
Line 364 ⟶ 498:
PRINT collection$[i]+ " ";
NEXT i
PRINT</langsyntaxhighlight>
Output:
<pre>The quick brown fox jumps over the lazy dog.</pre>
Line 370 ⟶ 504:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM collection$(8)
collection$() = "The", "quick", "brown", "fox", "jumps", \
\ "over", "the", "lazy", "dog."
Line 377 ⟶ 511:
PRINT collection$(index%) " ";
NEXT
PRINT</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
Commodore BASIC too does not have a FOR-EACH construct. FOR loop is used to iterate through a string array by index. READ-DATA is used to fill up the string array
<langsyntaxhighlight lang="qbasic">10 DIM A$(9) :REM DECLARE STRING ARRAY
20 REM *** FILL ARRAY WITH WORDS ***
30 FOR I = 0 TO 8
Line 391 ⟶ 525:
90 NEXT
100 END
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</langsyntaxhighlight>
 
==={{header|Creative Basic}}===
<langsyntaxhighlight Creativelang="creative Basicbasic">DEF AnArray[11]:INT
 
AnArray=0,1,2,3,4,5,6,7,8,9,10
Line 413 ⟶ 547:
'because this is a console only program.
END
</syntaxhighlight>
</lang>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">' FB 1.05.0
 
' FreeBASIC doesn't have a foreach loop but it's easy to manufacture one using macros
Line 433 ⟶ 567:
 
Print
Sleep</langsyntaxhighlight>
 
{{out}}
Line 442 ⟶ 576:
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=cb94500c68749f6f93915f3f10de5a03 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9]
Dim siTemp As Short
Line 450 ⟶ 584:
Next
 
End</langsyntaxhighlight>
{{out}}
<pre>
Line 457 ⟶ 591:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 STRING COLLECTION$(1 TO 9)*8
110 LET I=1
120 DO
Line 466 ⟶ 600:
170 PRINT COLLECTION$(J);" ";
180 NEXT
190 DATA The,quick,brown,fox,jumps,over,the,lazy,dog.</langsyntaxhighlight>
 
==={{header|IWBASIC}}===
'''Linked List'''
<langsyntaxhighlight IWBASIClang="iwbasic">DEF AList:POINTER
 
AList=ListCreate()
Line 501 ⟶ 635:
 
'Because this is a console only program.
END</langsyntaxhighlight>
 
'''An Array'''
<langsyntaxhighlight IWBASIClang="iwbasic">DEF AnArray[11]:INT
 
AnArray=0,1,2,3,4,5,6,7,8,9,10
Line 521 ⟶ 655:
'Because this is a console only program.
END
</syntaxhighlight>
</lang>
 
==={{header|Lambdatalk}}===
<langsyntaxhighlight lang="scheme">
{def collection alpha beta gamma delta}
-> collection
Line 550 ⟶ 684:
delta
 
</syntaxhighlight>
</lang>
 
==={{header|Liberty BASIC}}===
The most natural way is to use a csv list with a sentinel value.
<langsyntaxhighlight lang="lb">in$ ="Not,Hardly,Just,Adequately,Quite,Really,Very,Fantastically,xyzzy"
element$ =""
i =1 ' used to point to successive elements
Line 565 ⟶ 699:
loop until 1 =2
 
end</langsyntaxhighlight>
Not good!
Hardly good!
Line 576 ⟶ 710:
 
==={{header|NS-HUBASIC}}===
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">10 DIM A$(9) : REM DECLARE STRING ARRAY
20 REM ADD DATA TO ARRAY AND PRINT ARRAY CONTENTS
30 FOR I=0 TO 8
Line 582 ⟶ 716:
50 PRINT A$(I)" ";
60 NEXT
70 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</langsyntaxhighlight>
 
==={{header|PureBasic}}===
Works for LinkedLists and Maps
<langsyntaxhighlight PureBasiclang="purebasic">ForEach element()
PrintN(element())
Next</langsyntaxhighlight>
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="runbasic">t$={Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"
 
while word$(t$,i+1,",") <> ""
i = i + 1
print word$(t$,i,",")
wend</langsyntaxhighlight>
 
==={{header|TI-89 BASIC}}===
<langsyntaxhighlight lang="ti89b">Local i,strs
Define strs = {"Lorem","ipsum","dolor"}
For i, 1, dim(strs)
Disp strs[i]
EndFor</langsyntaxhighlight>
 
==={{header|VBA}}===
<langsyntaxhighlight VBlang="vb">Public Sub LoopsForeach()
Dim FruitArray() As Variant
Dim Fruit As Variant
Line 618 ⟶ 752:
Debug.Print Fruit
Next Fruit
End Sub</langsyntaxhighlight>
 
==={{header|VBScript}}===
<langsyntaxhighlight lang="vbscript">items = Array("Apple", "Orange", "Banana")
 
For Each x In items
WScript.Echo x
Next</langsyntaxhighlight>
 
==={{header|Visual Basic .NET}}===
<langsyntaxhighlight lang="vbnet">Dim list As New List(Of String)
list.Add("Car")
list.Add("Boat")
Line 635 ⟶ 769:
For Each item In list
Console.WriteLine(item)
Next</langsyntaxhighlight>
 
 
==={{header|Yabasic}}===
<langsyntaxhighlight Yabasiclang="yabasic">//Yabasic tampoco tiene una construcción ForEach.
//Mediante un bucle FOR iteramos a través de una matriz por índice.
//READ-DATA se usa para rellenar la matriz
Line 653 ⟶ 787:
next each
print
end</langsyntaxhighlight>
 
 
Line 660 ⟶ 794:
 
'''Direct usage:'''
<langsyntaxhighlight lang="dos">@echo off
for %%A in (This is a sample collection) do (
echo %%A
)</langsyntaxhighlight>
'''Using a Collection Variable:'''
<langsyntaxhighlight lang="dos">@echo off
set "collection=This is a sample collection"
for %%A in (%collection%) do (
echo %%A
)</langsyntaxhighlight>
{{Out|They have the Same Output}}
<pre>This
Line 679 ⟶ 813:
=={{header|bc}}==
There is no "for each"-loop in bc. For accessing each element of an array (the only collection-like type) one uses a straightforward for-loop.
<langsyntaxhighlight lang="bc">a[0] = .123
a[1] = 234
a[3] = 95.6
for (i = 0; i < 4; i++) {
a[i]
}</langsyntaxhighlight>
 
=={{header|Bracmat}}==
Bracmat has a more or less traditional 'while' loop (<code>whl'<i>expression</i></code>) which was introduced rather late in the history of Bracmat. Before that, tail recursion was a way to repeat something.
But let us make a list first:
<langsyntaxhighlight lang="bracmat"> ( list
= Afrikaans
Ελληνικά
Line 695 ⟶ 829:
മലയാളം
ئۇيغۇرچە
)</langsyntaxhighlight>
The 'while' solution. Use an auxiliary variable <code>L</code> that gets its head chopped off until nothing is left:
<langsyntaxhighlight lang="bracmat"> !list:?L
& whl'(!L:%?language ?L&out$!language)</langsyntaxhighlight>
The tail-recursive solution. When the auxiliary variable is reduced to nothing, the loop fails. By adding the <code>~</code> flag to the initial invocation, failure is turned into success. This solution benefits from tail recursion optimization.
<langsyntaxhighlight lang="bracmat"> !list:?L
& ( loop
= !L:%?language ?L
Line 706 ⟶ 840:
& !loop
)
& ~!loop</langsyntaxhighlight>
A completely different way of iteration is by using a pattern that matches an element in the list, does something useful as a side effect and then fails, forcing bracmat to backtrack and try the next element in the list. The <code>@</code> flag matches at most one element. The <code>%</code> flag matches at least one element. Together they ensure that exactly one language name is assigned to the variable <code>language</code>. After all elements have been done, control is passed to the rhs of the <code>|</code> operator.
<langsyntaxhighlight lang="bracmat"> ( !list
: ? (%@?language&out$!language&~) ?
|
)</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="c">#include <stdio.h>
...
 
Line 724 ⟶ 858:
for(ix=0; ix<LIST_SIZE; ix++) {
printf("%s\n", list[ix]);
}</langsyntaxhighlight>
 
The C language does, however, have a number of standard data structures that can be thought of as collections, and foreach can easily be made with a macro.<BR><BR>
 
C string as a collection of char
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 747 ⟶ 881:
return(0);
}
</syntaxhighlight>
</lang>
 
C int array as a collection of int (array size known at compile-time)
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 767 ⟶ 901:
return(0);
}
</syntaxhighlight>
</lang>
 
Most general: string or array as collection (collection size known at run-time)
: ''Note: idxtype can be removed and [http://gcc.gnu.org/onlinedocs/gcc/Typeof.html typeof(col&#91;0&#93;)] can be used in it's place with [[GCC]]''
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 796 ⟶ 930:
return(0);
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">string[] things = {"Apple", "Banana", "Coconut"};
 
foreach (string thing in things)
{
Console.WriteLine(thing);
}</langsyntaxhighlight>
 
=={{header|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 <tt>container_type</tt> and the actual container object is named container.
<langsyntaxhighlight lang="cpp">for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
std::cout << *i << "\n";
}</langsyntaxhighlight>
However the idiomatic way to output a container would be
<langsyntaxhighlight lang="cpp">std::copy(container.begin(), container.end(),
std::ostream_iterator<container_type::value_type>(std::cout, "\n"));</langsyntaxhighlight>
There's also an algorithm named <tt>for_each</tt>. However, you need a function or function object to use it, e.g.
<langsyntaxhighlight lang="cpp">void print_element(container_type::value_type const& v)
{
std::cout << v << "\n";
Line 822 ⟶ 956:
 
...
std::for_each(container.begin(), container.end(), print_element);</langsyntaxhighlight>
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">for (auto element: container)
{
std::cout << element << "\n";
}</langsyntaxhighlight>
Here <tt>container</tt> is the container variable, <tt>element</tt> 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:
<langsyntaxhighlight lang="cpp">for (auto const& element: container)
{
std::cout << element << "\n";
}</langsyntaxhighlight>
Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant):
<langsyntaxhighlight lang="cpp">for (auto&& element: container) //use a 'universal reference'
{
element += 42;
}</langsyntaxhighlight>
 
=={{header|C3}}==
C3 has a standard built-in foreach for iterating through lists.
 
<syntaxhighlight lang="c3">String[] fruits = { "Apple", "Banana", "Strawberry" };
foreach (fruit : fruits) io::printn(fruit);</syntaxhighlight>
 
=={{header|Chapel}}==
<langsyntaxhighlight lang="chapel">var food = ["Milk", "Bread", "Butter"];
for f in food do writeln(f);</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(doseq [item collection] (println item))</langsyntaxhighlight>
 
=={{header|CLU}}==
 
As in Python (which no doubt got the idea from CLU), every <em>for</em> loop in
CLU is really a <em>foreach</em>, and iterating over a range of numbers is done
by using an iterator (e.g. <code>int$from_to</code>).
 
Unlike Python, the <em>for</em> loop '''only''' accepts iterators, and collections
are not automatically cast into iterators. To loop over the elements of an array,
one needs to explicitly use the <code>elements</code> iterator.
 
<syntaxhighlight lang="clu">start_up = proc ()
po: stream := stream$primary_output()
words: array[string] := array[string]$
["enemy", "lasagna", "robust", "below", "wax"]
for word: string in array[string]$elements(words) do
stream$putl(po, word)
end
end start_up</syntaxhighlight>
 
=={{header|CMake}}==
<langsyntaxhighlight lang="cmake">set(list one.c two.c three.c)
 
foreach(file ${list})
message(${file})
endforeach(file)</langsyntaxhighlight>
 
=={{header|COBOL}}==
Line 857 ⟶ 1,018:
{{trans|C#}}
{{works with|Visual COBOL}}
<langsyntaxhighlight lang="cobol">01 things occurs 3.
...
set content of things to ("Apple", "Banana", "Coconut")
perform varying thing as string through things
display thing
end-perform</langsyntaxhighlight>
 
=={{header|ColdFusion}}==
<langsyntaxhighlight lang="cfm">
<Cfloop list="Fee, Fi, Foe, Fum" index="i">
<Cfoutput>#i#!</Cfoutput>
</Cfloop>
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(loop for i in list do (print i))</langsyntaxhighlight>
or
<langsyntaxhighlight lang="lisp">(map nil #'print list)</langsyntaxhighlight>
or
<langsyntaxhighlight lang="lisp">(dolist (x the-list) (print x))</langsyntaxhighlight>
or
<langsyntaxhighlight lang="lisp">(use-package :iterate)
(iter
(for x in the-list)
(print x))</langsyntaxhighlight>
 
=== Using DO ===
<langsyntaxhighlight lang="lisp">
(let ((the-list '(1 7 "foo" 1 4))) ; Set the-list as the list
(do ((i the-list (rest i))) ; Initialize to the-list and set to rest on every loop
((null i)) ; Break condition
(print (first i)))) ; On every loop print list's first element
</syntaxhighlight>
</lang>
 
{{out}}
Line 902 ⟶ 1,063:
=={{header|D}}==
This works if ''collection'' is a string/array/associative array, or if implements an appropriate ''opApply'' function, or if it has the basic Range methods.
<langsyntaxhighlight lang="d">import std.stdio: writeln;
 
void main() {
Line 919 ⟶ 1,080:
foreach (key, value; collection3)
writeln(key, " ", value);
}</langsyntaxhighlight>
{{out}}
<pre>A
Line 935 ⟶ 1,096:
 
=={{header|Dao}}==
<langsyntaxhighlight lang="dao">items = { 1, 2, 3 }
for( item in items ) io.writeln( item )</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 942 ⟶ 1,103:
 
Supports arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator().
<langsyntaxhighlight Delphilang="delphi">program LoopForEach;
 
{$APPTYPE CONSOLE}
Line 951 ⟶ 1,112:
for s in 'Hello' do
Writeln(s);
end.</langsyntaxhighlight>
Output:
<pre>H
Line 960 ⟶ 1,121:
 
=={{header|Dragon}}==
<langsyntaxhighlight lang="dragon">
for value : array {
showln value
}
</syntaxhighlight>
</lang>
 
=={{header|Dyalect}}==
<langsyntaxhighlight Dyalectlang="dyalect">for i in [1,2,3] {
print(i)
}</langsyntaxhighlight>
 
This code would work for any type that has a method "iter" (returning an iterator). In fact a runtime environment silently calls this method for you here and creates an iterator out of an array. The code above is absolutely identical to:
 
<langsyntaxhighlight Dyalectlang="dyalect">for i in [1,2,3].iterIterate() {
print(i)
}</langsyntaxhighlight>
 
This would perfectly work with any custom iterator as well:
 
<langsyntaxhighlight Dyalectlang="dyalect">func myCollection() {
yield 1
yield 2
Line 987 ⟶ 1,148:
for i in myCollection() {
print(i)
}</langsyntaxhighlight>
 
All three code samples would output:
Line 996 ⟶ 1,157:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">for e in theCollection {
println(e)
}</langsyntaxhighlight>
In E, the for ... in ... loop is also used for iterating over numeric ranges; see [[Loop/For#E]].
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
for i in [ 5 1 19 25 12 1 14 7 ]
print i
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(define my-list '( albert simon antoinette))
(for ((h my-list)) (write h))
Line 1,016 ⟶ 1,184:
 
;; etc ... for other collections like Streams, Hashes, Graphs, ...
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module LoopForEach {
@Inject Console console;
void run() {
val vals = [10, 20, 30, 40];
console.print("Array of values:");
Loop: for (val val : vals) {
console.print($" value #{Loop.count + 1}: {val}");
}
 
Map<String, Int> pairs = ["x"=42, "y"=69];
console.print("\nKeys and values:");
for ((String key, Int val) : pairs) {
console.print($" {key}={val}");
}
console.print("\nJust the keys:");
Loop: for (String key : pairs) {
console.print($" key #{Loop.count + 1}: {key}");
}
 
console.print("\nValues from a range:");
for (Int n : 1..5) {
console.print($" {n}");
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Array of values:
value #1: 10
value #2: 20
value #3: 30
value #4: 40
 
Keys and values:
x=42
y=69
 
Just the keys:
key #1: x
key #2: y
 
Values from a range:
1
2
3
4
5
</pre>
 
=={{header|Efene}}==
Any data structure can be printed as a whole, preformated:
<langsyntaxhighlight lang="efene">io.format("~p~n", [Collection])</langsyntaxhighlight>
However, to iterate over each element of a list, Efene uses <tt>lists.map/2</tt>, except in the case of IO where <tt>lists.foreach/2</tt> has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
<langsyntaxhighlight lang="efene">lists.foreach(fn (X) { io.format("~p~n", [X]) }, Collection)</langsyntaxhighlight>
 
=={{header|Eiffel}}==
{{works with|EiffelStudio|6.6 beta (with provisional loop syntax)}}
The iteration (foreach) form of the Eiffel loop construct is introduced by the keyword <code lang="eiffel">across</code>.
<langsyntaxhighlight lang="eiffel "> across my_list as ic loop print (ic.item) end</langsyntaxhighlight>
The local entity <code lang="eiffel">ic</code> is an instance of the library class <code lang="eiffel">ITERATION_CURSOR</code>. The cursor's feature <code lang="eiffel">item</code> provides access to each structure element. Descendants of class <code lang="eiffel">ITERATION_CURSOR</code> can be created to handle specialized iteration algorithms. The types of objects that can be iterated across (<code lang="eiffel">my_list</code> in the example) are based on classes that inherit from the library class <code lang="eiffel">ITERABLE</code>
===Boolean expression variant===
Line 1,033 ⟶ 1,254:
 
This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three:
<langsyntaxhighlight lang="eiffel"> across my_list as ic all ic.item.count > 3 end</langsyntaxhighlight>
Whereas, the following is true if at least one item has a count greater than three:
<langsyntaxhighlight lang="eiffel"> across my_list as ic some ic.item.count > 3 end</langsyntaxhighlight>
 
=={{header|Ela}}==
<langsyntaxhighlight lang="ela">open monad io
each [] = do return ()
each (x::xs) = do
putStrLn $ show x
each xs</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,054 ⟶ 1,275:
var things := new string[]{"Apple", "Banana", "Coconut"};
things.forEach::(thing)
{
console.printLine(thing)
}
}</syntaxhighlight>
 
=== Using foreach statement template ===
<syntaxhighlight lang="elena">import extensions;
public program()
{
var things := new string[]{"Apple", "Banana", "Coconut"};
foreach(var thing; in things)
{
console.printLine:(thing)
}
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> list = [1,3.14,"abc",[3],{0,5}]
[1, 3.14, "abc", [3], {0, 5}]
iex(2)> Enum.each(list, fn x -> IO.inspect x end)
Line 1,069 ⟶ 1,303:
[3]
{0, 5}
:ok</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
For a list either <code>dolist</code> macro
 
<langsyntaxhighlight Lisplang="lisp">(dolist (x '(1 2 3 4))
(message "x=%d" x))</langsyntaxhighlight>
 
or <code>mapc</code> function
 
<langsyntaxhighlight Lisplang="lisp">(mapc (lambda (x)
(message "x=%d" x))
'(1 2 3 4))</langsyntaxhighlight>
 
{{libheader|cl-lib}}
<code>dolist</code> and <code>mapc</code> are both builtin in current Emacs. For past Emacs both can be had from <code>cl.el</code> with for instance <code>(eval-when-compile (require 'cl))</code>.
 
<syntaxhighlight lang="lisp">(cl-loop for x in '(1 2 3 4) do (message "x=%d" x))</syntaxhighlight>
<code>cl.el</code> also offers a <code>loop</code> macro similar in style to [[#Common Lisp|Common Lisp]].
 
=={{header|Erlang}}==
Any data structure can be printed as a whole, preformated:
<langsyntaxhighlight lang="erlang">io:format("~p~n",[Collection]).</langsyntaxhighlight>
However, to iterate over each element of a list, Erlang uses <tt>lists:map/2</tt>, except in the case of IO where <tt>lists:foreach/2</tt> has to be used as the evaluation order is defined to be the same as the order of the elements in the list.
<langsyntaxhighlight lang="erlang">lists:foreach(fun(X) -> io:format("~p~n",[X]) end, Collection).</langsyntaxhighlight>
 
=={{header|ERRE}}==
It's an extension of 'standard' FOR loop: constant list must be explicit.
<langsyntaxhighlight ERRElang="erre">
FOR INDEX$=("The","quick","brown","fox","jumps","over","the","lazy","dog.") DO
PRINT(INDEX$;" ";)
END FOR
PRINT
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
<syntaxhighlight lang="euphoria">
<lang>
include std/console.e
 
Line 1,129 ⟶ 1,363:
 
if getc(0) then end if
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,170 ⟶ 1,404:
=={{header|F_Sharp|F#}}==
We can use ''for'' directly or list iteration.
<langsyntaxhighlight lang="fsharp">for i in [1 .. 10] do printfn "%d" i
 
List.iter (fun i -> printfn "%d" i) [1 .. 10]</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">{ 1 2 4 } [ . ] each</langsyntaxhighlight>
 
=={{header|Fantom}}==
Use <code>each</code> method to iterate over a collection of items in a <code>List</code>.
<langsyntaxhighlight lang="fantom">class Main
{
public static Void main ()
Line 1,189 ⟶ 1,423:
}
}
}</langsyntaxhighlight>
 
=={{header|Fennel}}==
====sequential table====
<langsyntaxhighlight lang="fennel">(each [k v (ipairs [:apple :banana :orange])]
(print k v))</langsyntaxhighlight>
{{out}}
<pre>1 apple
Line 1,200 ⟶ 1,434:
3 orange</pre>
====key-value table====
<langsyntaxhighlight lang="fennel">(each [k v (pairs {:apple :x :banana 4 :orange 3})]
(print k v))</langsyntaxhighlight>
{{out}}
<pre>apple x
Line 1,207 ⟶ 1,441:
orange 3</pre>
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">create a 3 , 2 , 1 ,
: .array ( a len -- )
cells bounds do i @ . cell +loop ; \ 3 2 1</langsyntaxhighlight>
===FOREACH===
The thing about extensible languages is if you need FOREACH, you can have FOREACH.
The Forth ' operator returns the "execution token" (XT) of a Forth word. An XT can be run with EXECUTE.
If we apply an appropriate XT to all the elements of an array we have it.
 
<syntaxhighlight lang="forth">: FOREACH ( array size XT --)
>R \ save execution token on return stack
CELLS BOUNDS \ convert addr,len -> last,first addresses
BEGIN
2DUP > \ test addresses
WHILE ( last>first )
DUP R@ EXECUTE \ apply the execution token to the address
CELL+ \ move first to the next memory cell
REPEAT
R> DROP \ clean return stack
2DROP \ and data stack
;
 
\ Make an operator to fetch contents of an address and print
: ? ( addr --) @ . ;
 
CREATE A[] 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ,
 
\ Usage example:
A[] 10 ' ? FOREACH </syntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program main
 
implicit none
Line 1,227 ⟶ 1,486:
write(*,'(A)') colors
 
end program main</langsyntaxhighlight>
 
=={{header|friendly interactive shell}}==
Unlike, bash or csh, the PATH variable is automatically converted to real array.
<langsyntaxhighlight lang="fishshell">for path in $PATH
echo You have $path in PATH.
end</langsyntaxhighlight>
 
Sample output:
Line 1,243 ⟶ 1,502:
=={{header|Frink}}==
Frink's <CODE>for</CODE> loop is actually a "for each" loop which can iterate over built-in collection types including arrays, sets, dictionaries, enumerating expressions, and Java types such as Map, Iterator, Enumeration, etc.
<langsyntaxhighlight lang="frink">
array = [1, 2, 3, 5, 7]
for n = array
println[n]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
window 1
 
void local fn DoIt
CFArrayRef array = @[@"Alpha",@"Bravo",@"Charlie",@"Delta",@"Echo",@"FutureBasic"]
CFStringRef string
for string in array
print string
next
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
Alpha
Bravo
Charlie
Delta
Echo
FutureBasic
</pre>
 
=={{header|GAP}}==
 
<langsyntaxhighlight lang="gap">for p in AlternatingGroup(4) do
Print(p, "\n");
od;
Line 1,266 ⟶ 1,553:
(1,3,4)
(1,2)(3,4)
(1,4,2)</langsyntaxhighlight>
 
=={{header|Go}}==
<code>range</code> 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.
<langsyntaxhighlight lang="go">func printAll(values []int) {
for i, x := range values {
fmt.Printf("Item %d = %d\n", i, x)
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
"for" loop:
<langsyntaxhighlight lang="groovy">def beatles = ["John", "Paul", "George", "Ringo"]
 
for(name in beatles) {
println name
}</langsyntaxhighlight>
"each()" method:<br>
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.
<langsyntaxhighlight lang="groovy">beatles.each {
println it
}</langsyntaxhighlight>
Output (same for either):
<pre>John
Line 1,295 ⟶ 1,582:
 
=={{header|Halon}}==
<langsyntaxhighlight lang="halon">$things = ["Apple", "Banana", "Coconut"];
 
foreach ($things as $thing) {
echo $thing;
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad (forM_)
forM_ collect print</langsyntaxhighlight>
which is the same as
<syntaxhighlight lang ="haskell">mapM_ print collect</langsyntaxhighlight>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">var a = [1, 2, 3, 4];
 
for (i in a)
Sys.println(i);</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER days="Monday Tuesday Wednesday Thursday Friday Saturday Sunday "
 
items = INDEX(days, ' ', 256) ! 256 = count option
Line 1,320 ⟶ 1,607:
EDIT(Text=days, ITeM=j, Parse=today)
WRITE() today
ENDDO</langsyntaxhighlight>
 
=={{header|Hy}}==
<langsyntaxhighlight lang="clojure">(for [x collection] (print x))</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The example below X can be a list, string, table or other data type.
<langsyntaxhighlight Iconlang="icon">procedure main()
X := [1,2,3,-5,6,9]
every x := !L do
write(x)
end</langsyntaxhighlight>
This loop can be written somewhat more concisely as:
<syntaxhighlight lang Icon="icon">every write(!L)</langsyntaxhighlight>
 
=={{header|Io}}==
<syntaxhighlight lang ="io">collection foreach(println)</langsyntaxhighlight>
 
=={{header|J}}==
<syntaxhighlight lang="j"> echo every i.10
<lang J>smoutput each i.10</lang>
0
1
2
3
4
5
6
7
8
9</syntaxhighlight>
 
That said, J's <code>for.</code> provides a "foreach" mechanism.
 
<syntaxhighlight lang="J"> {{for_i. i. y do. echo i end.}}10
0
1
2
3
4
5
6
7
8
9
</syntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">Iterable<Type> collect;
...
for(Type i:collect){
System.out.println(i);
}</langsyntaxhighlight>
This works for any array type as well as any type that implements the Iterable interface (including all Collections).
 
{{works with|Java|1.8+}}
<langsyntaxhighlight lang="java">
Iterable collect;
...
collect.forEach(o -> System.out.println(o));
</syntaxhighlight>
</lang>
This works with any Iterable, but not with arrays.
 
=={{header|JavaScript}}==
For arrays in ES5, we can use '''Array.forEach()''':
<langsyntaxhighlight JavaScriptlang="javascript">"alpha beta gamma delta".split(" ").forEach(function (x) {
console.log(x);
});</langsyntaxhighlight>
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use '''Array.map()''',
<langsyntaxhighlight JavaScriptlang="javascript">console.log("alpha beta gamma delta".split(" ").map(function (x) {
return x.toUpperCase(x);
}).join("\n"));</langsyntaxhighlight>
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
<langsyntaxhighlight JavaScriptlang="javascript">console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) {
return lst.length - i + ". " + x + "\n" + a;
}, ""));</langsyntaxhighlight>
More generally, the following works for any object, including an array. It iterates over the keys of an object.
<langsyntaxhighlight JavaScriptlang="javascript">for (var a in o) {
print(o[a]);
}</langsyntaxhighlight>
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:
<langsyntaxhighlight JavaScriptlang="javascript">for (var a in o) {
if (o.hasOwnProperty(a)) {
print(o[a]);
}
}</langsyntaxhighlight>
{{works with|JavaScript|1.6}}
;Deprecated
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for_each...in for each in]</tt> construct that iterates over the values of an object:
<langsyntaxhighlight JavaScriptlang="javascript">h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for each (y in h) print(y);</langsyntaxhighlight>
{{works with|ECMAScript|6th edition}}
There is also a <tt>[https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...of for of]</tt> construct that iterates over the values of an object:
<langsyntaxhighlight JavaScriptlang="javascript">h = {"one":1, "two":2, "three":3}
for (x in h) print(x);
for (y of h) print(y);</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,397 ⟶ 1,709:
 
In this section, the array defined by "example" is used as an example:
<langsyntaxhighlight lang="jq">def example: [1,2];</langsyntaxhighlight>
jq has two types of iterables -- JSON arrays and JSON objects. In both cases, the ".[]" filter may be used to iterate through the values, it being understand that for objects, the "values" are the values associated with the keys:
<langsyntaxhighlight lang="jq">example | .[]
# or equivalently: example[]</langsyntaxhighlight>
<langsyntaxhighlight lang="jq">{"a":1, "b":2} | .[]
# or equivalently: {"a":1, "b":2}[]</langsyntaxhighlight>
 
In both cases, the output is the stream consisting of the values 1 followed by 2.
 
Sometimes it is necessary to use an alternative to ".[]". For example, one might want to generate an index along with the array elements. In such cases, the "range(m;n)" generator, which performs a similar role to C's "for(i=m; i<n; i++)", can be used for array. Here is how range/2 would be used to perform the task for an array:
<langsyntaxhighlight lang="jq">example | . as $a | range(0; length) | $a[.]</langsyntaxhighlight>
For JSON objects, the corresponding technique involves using <tt>keys</tt>, e.g.
<syntaxhighlight lang="jq">
<lang jq>
{"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )
</syntaxhighlight>
</lang>
produces:
[["a",1],["b",2]]
Line 1,419 ⟶ 1,731:
 
To convert the constituent characters (or technically, codepoints) of a string into a stream of values, there are two techniques illustrated by these examples:
<langsyntaxhighlight lang="jq">"abc" | . as $s | range(0;length) | $s[.:.+1]
 
"abc" | explode | map( [.]|implode) | .[]</langsyntaxhighlight>
 
In both cases, the result is the stream of values: "a", "b", "c".
Line 1,427 ⟶ 1,739:
=={{header|Jsish}}==
Jsi supports ''for of'' for looping over element of an array.
<langsyntaxhighlight lang="javascript">for (str of "alpha beta gamma delta".split(' ')) { puts(str); }</langsyntaxhighlight>
 
{{out}}
Line 1,437 ⟶ 1,749:
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">for i in collection
println(i)
end</langsyntaxhighlight>
The Julia <code>for</code> statement is always a "foreach", and the built-in <code>start:end</code> or <code>start:step:end</code> "range" syntax can be used for iteration over arithmetic sequences. Many Julia objects support iteration: arrays and tuples iterate over each item, strings iterate over each character, dictionaries iterate over (key,value) pairs, numeric scalars provide a length-1 iteration over their value, and so on.
 
=={{header|K}}==
<langsyntaxhighlight Klang="k"> {`0:$x} ' !10</langsyntaxhighlight>
<langsyntaxhighlight Klang="k"> _sin ' (1; 2; 3;)</langsyntaxhighlight>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
( -2 "field" 3.14159 ( "this" "that" ) ) len [get ?] for
 
" " input</langsyntaxhighlight>
{{out}}
<pre>-2
Line 1,459 ⟶ 1,771:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 1,468 ⟶ 1,780:
greek.forEach { print("$it ") }
println()
}</langsyntaxhighlight>
 
{{out}}
Line 1,480 ⟶ 1,792:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def collection alpha beta gamma delta}
-> collection
Line 1,506 ⟶ 1,818:
delta
 
</syntaxhighlight>
</lang>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
$collection = fn.arrayOf(1, 2, 3)
 
# Foreach loop [Works with iterable types (text, collections [array, list])]
$ele
foreach($[ele], $collection) {
fn.println($ele)
}
 
# Foreach function
# Array: fn.arrayForEach(&arr, func)
# List: fn.listForEach(&list, func)
 
fn.arrayForEach($collection, fn.println)
</syntaxhighlight>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: >>say.(*) . ;
5 iota >>say.</langsyntaxhighlight>
 
=={{header|langur}}==
A for in loop iterates over values and a for of loop iterates over indiceskeys.
<langsyntaxhighlight lang="langur">for .i in [1, 2, 3] {
writeln .i
}
Line 1,530 ⟶ 1,859:
for .i in .abc {
writeln cp2s .i
}</langsyntaxhighlight>
 
{{out}}
Line 1,547 ⟶ 1,876:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">array(1,2,3) => foreach { stdoutnl(#1) }</langsyntaxhighlight>
<langsyntaxhighlight Lassolang="lasso">with i in array(1,2,3) do { stdoutnl(#i) }</langsyntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
fruits is text list
fruit is text
 
procedure:
split "apple banana orange" by " " in fruits
for each fruit in fruits do
display fruit lf
repeat
</syntaxhighlight>
{{out}}
<pre>
apple
banana
orange
</pre>
 
=={{header|LFE}}==
 
<langsyntaxhighlight lang="lisp">(lists:foreach
(lambda (x)
(io:format "item: ~p~n" (list x)))
(lists:seq 1 10))
</syntaxhighlight>
</lang>
 
=={{header|LIL}}==
<langsyntaxhighlight lang="tcl"># Loops/Foreach, in LIL
set collection [list 1 2 "three"]
append collection [list 4 5 six] # appended as a single item in collection
Line 1,570 ⟶ 1,917:
# each loop step quotes two copies of the item
set newlist [foreach j $collection {quote $j $j}]
print "Result of second foreach: $newlist"</langsyntaxhighlight>
 
{{out}}
Line 1,583 ⟶ 1,930:
=={{header|Lingo}}==
 
<langsyntaxhighlight lang="lingo">days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
repeat with day in days
put day
end repeat</langsyntaxhighlight>
A callback-based forEach() can be implemented like this:
<langsyntaxhighlight lang="lingo">----------------------------------------
-- One of the five native iterative methods defined in ECMAScript 5
-- @param {list} tList
Line 1,600 ⟶ 1,947:
call(cbFunc, cbObj, tList[i], i, tList)
end repeat
end</langsyntaxhighlight>
<langsyntaxhighlight lang="lingo">days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
forEach(days, #alert, _player)</langsyntaxhighlight>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">"Lisaac loop foreach".split.foreach { word : STRING;
word.print;
'\n'.print;
};</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Livecode's ''for each'' operates on chunks which may be words, items, lines, tokens. Example is for items.<langsyntaxhighlight LiveCodelang="livecode">repeat for each item x in "red, green, blue"
put x & cr
--wait 100 millisec -- req'd if you want to see in the LC Message Box (akin to repl)
end repeat</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">foreach [red green blue] [print ?]</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 1,623 ⟶ 1,970:
 
<code>pairs()</code> iterates over all entries in a table, but in no particular order:
<langsyntaxhighlight 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</langsyntaxhighlight>
Output:
<pre>
Line 1,640 ⟶ 1,987:
<code>ipairs()</code> iterates over table entries with positive integer keys,
and is used to iterate over lists in order.
<langsyntaxhighlight 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</langsyntaxhighlight>
Output:
<pre>
Line 1,659 ⟶ 2,006:
Iterators we have for Arrays, Inventories and Stacks (containers). Each(object Start to End), or Each(object 1 to -1) or Each(Object, 1,-1). We can use -2 for second from end item. We can use step inside while iterator {} using Iterator=Each(object, new_start, end_item). We can read cursor using ^. So Print k^, k2^, k1^ return positions (from 0 for inventories). We can use more than one iterators for an object.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
\\ Inventories may have keys or keys/values
Line 1,687 ⟶ 2,034:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
for p in [2, 3, 5, 7] do
print(p);
end do;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Foreach over list of strings
<langsyntaxhighlight lang="mathematica">s = (StringSplit@Import["ExampleData/USConstitution.txt"])[[1;;7]];
Do[
Print@i,
{i, s}
]</langsyntaxhighlight>
Output:
<pre>We
Line 1,713 ⟶ 2,060:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> list1 = [1,5,6,7,-7,-9];
for k = list1, % list1 must be a row vector (i.e. array of size 1xn)
printf('%i\n',k)
end; </langsyntaxhighlight>
<langsyntaxhighlight Matlablang="matlab"> list2 = {'AA','BB','CC'};
for k = list2, % list2 must be a row vector (i.e. array of size 1xn)
printf('%s\n',k{1})
end; </langsyntaxhighlight>
A vectorized version of the code is
<langsyntaxhighlight Matlablang="matlab"> printf('%d\n',list1);
printf('%s\n',list2{:}); </langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">for n in [2, 3, 5, 7] do print(n);</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">
arr = for i in 1 to 50 collect ("Number: " + (random 10 99) as string)
makeuniquearray arr
Line 1,735 ⟶ 2,082:
 
for i in arr do print i as string
</syntaxhighlight>
</lang>
 
=={{header|Metafont}}==
If we have a list of arbitrary items, we can simply use for:
<langsyntaxhighlight lang="metafont">for x = "mary", "had", "a", "little", "lamb": message x; endfor
end</langsyntaxhighlight>
The list can be generated in place by any suitable macro or another loop... e.g. let us suppose we have things like <tt>a[n]</tt> defined (with maximum n being 10). Then
<langsyntaxhighlight lang="metafont">for x = for i = 1 upto 9: a[i], endfor, a[10]: show x; endfor
end</langsyntaxhighlight>
works more like a <tt>foreach</tt>; we could make a macro to hide the strangeness of such a code.
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">(1 2 3) 'puts foreach</langsyntaxhighlight>
 
=={{header|MiniScript}}==
 
<langsyntaxhighlight MiniScriptlang="miniscript">for i in collection
print i
end</langsyntaxhighlight>
The MiniScript <code>for</code> statement is always a "foreach", and the standard <code>range</code> intrinsic can be used for iteration over arithmetic sequences. All MiniScript collection types support iteration: lists iterate over each item, strings iterate over each character, and maps/objects iterate over (key,value) pairs.
 
=={{header|MOO}}==
<langsyntaxhighlight lang="moo">things = {"Apple", "Banana", "Coconut"};
for thing in (things)
player:tell(thing);
endfor</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
Like Python, Nanoquery supports for...in syntax for list types and strings.
<langsyntaxhighlight Nanoquerylang="nanoquery">for item in collection
println item
end</langsyntaxhighlight>
<strong>Some examples:</strong>
<langsyntaxhighlight Nanoquerylang="nanoquery">for n in {1,3,5,7,9}
print n + " "
end
Line 1,778 ⟶ 2,125:
print char
end
println</langsyntaxhighlight>
{{out}}
<pre>1 3 5 7 9
Line 1,785 ⟶ 2,132:
=={{header|Nemerle}}==
This works on anything which implements the IEnumerable interface.
<langsyntaxhighlight Nemerlelang="nemerle">def things = ["Apple", "Banana", "Coconut"];
 
foreach (thing in things) WriteLine(thing.ToLower());
foreach (i in [5, 10 .. 100]) Write($"$i\t");</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 1,803 ⟶ 2,150:
loop while daysi.hasNext
say daysi.next
end</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(map println '(Apple Banana Coconut))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">let list = ["lorem", "ipsum", "dolor"}]
for item in list:
echo item</langsyntaxhighlight>
{{out}}
<pre>lorem
ipsum
dolor</pre>
=={{header|Nu}}==
<syntaxhighlight lang="nu">
let l = [a b c d]
for x in $l {print $x}
</syntaxhighlight>
{{out}}
<pre>
a
b
c
d
</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">fruits := ["Apple", "Banana", "Coconut"];
each(i : fruits) {
fruits[i]->PrintLine();
};</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Line 1,827 ⟶ 2,186:
{{works with|GNUstep}}
{{works with|Cocoa}}
<langsyntaxhighlight lang="objc">NSArray *collect;
// ...
for (Type i in collect) {
NSLog(@"%@", i);
}</langsyntaxhighlight>
''collect'' can be any object that adopts the NSFastEnumeration protocol.
 
Or (always using OpenStep compatible frameworks):
{{works with|Objective-C|<2.0}}
<langsyntaxhighlight lang="objc">NSArray *collect;
// ...
NSEnumerator *enm = [collect objectEnumerator];
id i;
while( ((i = [enm nextObject]) ) {
// do something with object i
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
List of integers:
<langsyntaxhighlight lang="ocaml">List.iter
(fun i -> Printf.printf "%d\n" i)
collect_list</langsyntaxhighlight>
Array of integers:
<langsyntaxhighlight lang="ocaml">Array.iter
(fun i -> Printf.printf "%d\n" i)
collect_array</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">a = [ 1,4,3,2 ];
b = [ 1,2,3,4; 5,6,7,8 ];
for v = a
Line 1,862 ⟶ 2,221:
for v = b
disp(v); % v is the column vector [1;5], then [2;6] ...
endfor</langsyntaxhighlight>
We can also iterate over structures:
<langsyntaxhighlight lang="octave">x.a = [ 10, 11, 12 ];
x.b = { "Cell", "ul", "ar" };
for [ val, key ] = x
disp(key);
disp(val);
endfor</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: printMonths | m | Date.Months forEach: m [ m . ] ;</langsyntaxhighlight>
 
But, apply can be used instead of a loop :
<syntaxhighlight lang Oforth="oforth">#. Date.Months apply</langsyntaxhighlight>
 
=={{header|Ol}}==
<langsyntaxhighlight lang="scheme">
(for-each print '(1 3 4 2))
(print)
Line 1,886 ⟶ 2,245:
'(5 6 7 8)
'(a b x z))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,903 ⟶ 2,262:
The <tt>OVER</tt> loop control keyword is used to select each item in a collection in turn.
Open Object Rexx allows the <tt>DO</tt> block structure keyword to be used to start a loop for backward compatibility with classic Rexx; the <tt>LOOP</tt> keyword is preferred here as it is self-documenting.
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
say
say 'Loops/Foreach'
Line 1,915 ⟶ 2,274:
say out~strip()
 
exit</langsyntaxhighlight>
'''Output:'''
<pre>
Line 1,923 ⟶ 2,282:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
MyList = [1 2 3 4]
in
Line 1,929 ⟶ 2,288:
 
%% or:
for E in MyList do {Show E} end</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">for(i=1,#v,print(v[i]))</langsyntaxhighlight>
 
or (PARI/GP >= 2.4)
 
<langsyntaxhighlight lang="parigp">apply(x->print(x),v)</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,942 ⟶ 2,301:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">foreach my $i (@collection) {
print "$i\n";
}</langsyntaxhighlight>
The keyword <code>for</code> can be used instead of <code>foreach</code>. If a loop variable (here <code>$i</code>) is not given, then <code>$_</code> is used.
 
A more compact notation using perl statement modifier:
<langsyntaxhighlight lang="perl">print "$_\n" foreach @collection</langsyntaxhighlight>
 
In perl, it is possible to loop against an explicit list, so there is no need to define a container:
 
<langsyntaxhighlight lang="perl">foreach $l ( "apples", "bananas", "cherries" ) {
print "I like $l\n";
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"field"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3.14159268979</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"this"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"that"</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHL}}==
<langsyntaxhighlight lang="phl">var numbers = 1..10;
 
numbers each # (number) [
printf("%i\n", number);
];</langsyntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">foreach ($collect as $i) {
echo "$i\n";
}
Line 1,978 ⟶ 2,337:
foreach ($collect as $key => $i) {
echo "\$collect[$key] = $i\n";
}</langsyntaxhighlight>
<code>foreach</code> can also iterate over objects. By default it iterates over all visible fields of an object.
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(mapc println '(Apple Banana Coconut))</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">int main(){
array(int|string) collect = ({109, "Hi", "asdf", "qwerty"});
foreach(collect, int|string elem){
write(elem + "\n");
}
}</langsyntaxhighlight>
Iterating over the keys and values of a mapping (dictionary):
<langsyntaxhighlight lang="pike">int main(){
mapping(string:string) coll = (["foo":"asdf", "bar":"qwer", "quux":"zxcv"]);
foreach (coll;string key;string val)
write(key+" --> "+val+"\n");
}
}</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">declare A(10) fixed binary;
do i = lbound(A,1) to hbound(A,1);
put skip list (A(i));
end;</langsyntaxhighlight>
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Create a list.
Line 2,041 ⟶ 2,400:
Write the entry to the console.
Put the entry's next into the entry.
Repeat.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,054 ⟶ 2,413:
=={{header|Pop11}}==
Iteration over list:
<langsyntaxhighlight lang="pop11">lvars el, lst = [1 2 3 4 foo bar];
for el in lst do
printf(el,'%p\n');
endfor;</langsyntaxhighlight>
 
=={{header|PostScript}}==
The <code>forall</code> operator performs a loop over a collection (array, string or dictionary). Strings and arrays can be treated very much the same:
<langsyntaxhighlight lang="postscript">[1 5 3 2] { = } forall
(abc) { = } forall</langsyntaxhighlight>
but dictionaries take a little more work since a key/value pair is pushed on the stack in each iteration:
<langsyntaxhighlight lang="postscript"><</a 25 /b 42>> {
exch (Key: ) print
=
(Value: ) print
=
} forall</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$colors = "Black","Blue","Cyan","Gray","Green","Magenta","Red","White","Yellow",
"DarkBlue","DarkCyan","DarkGray","DarkGreen","DarkMagenta","DarkRed","DarkYellow"
Line 2,080 ⟶ 2,439:
Write-Host "$color" -ForegroundColor $color
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,103 ⟶ 2,462:
=={{header|Prolog}}==
For example :
<langsyntaxhighlight Prologlang="prolog">?- foreach(member(X, [red,green,blue,black,white]), writeln(X)).
red
green
Line 2,110 ⟶ 2,469:
white
true.
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">for i in collection:
print i</langsyntaxhighlight>
 
Note: The Python <code>for</code> statement is always a ''"foreach" ...'' and the <code>range()</code> and <code>xrange()</code> 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:
<langsyntaxhighlight lang="python">lines = words = characters = 0
f = open('somefile','r')
for eachline in f:
Line 2,128 ⟶ 2,487:
characters += 1
 
print lines, words, characters</langsyntaxhighlight>
 
Whether <code>for</code> loops over the elements of the collection in order depends on the collection having an inherent order or not. Elements of strings (i.e. characters), tuples and lists, for example, are ordered but the order of elements in dictionaries and sets is not defined.
Line 2,134 ⟶ 2,493:
One can loop over the key/value pairs of a dictionary in ''alphabetic'' or ''numeric'' key order by sorting the sequence of keys, provided that the keys are all of ''comparable'' types. In Python 3.x a sequence of mixed numeric and string elements is not sortable (at least not with the default invocation of <code>sorted()</code>), whereas in Python 2.x numeric types are sorted according to their string representation by default:
 
<langsyntaxhighlight lang="python">d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"}
for k in sorted(d):
print("%i: %s" % (k, d[k]))
Line 2,140 ⟶ 2,499:
d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))</langsyntaxhighlight>
 
{{works with|Python|2.x}}
 
<langsyntaxhighlight lang="python">d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery">$ "Sweet Boom Pungent Prickle Orange" nest$
witheach [ i times sp echo$ cr ]</langsyntaxhighlight>
{{Out}}
<pre> Sweet
Line 2,161 ⟶ 2,520:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">a <- list("First", "Second", "Third", 5, 6)
for(i in a) print(i)</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,175 ⟶ 2,534:
(for ([i sequence])
(displayln i))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.10-40}}
<syntaxhighlight lang="raku" perl6line>say $_ for @collection;</langsyntaxhighlight>
Raku leaves off the <tt>each</tt> from <tt>foreach</tt>, leaving us with <tt>for</tt> instead. The variable <tt>$_</tt> refers to the current element, unless you assign a name to it using <tt>-></tt>.
<syntaxhighlight lang="raku" perl6line>for @collection -> $currentElement { say $currentElement; }</langsyntaxhighlight>
Raku will do it's best to put the topic at the right spot.
<syntaxhighlight lang="raku" perl6line>.say for @collection;
for @collection { .say };</langsyntaxhighlight>
Iteration can also be done with hyperoperators. In this case it's a candidate for autothreading and as such, execution order may vary. The resulting list will be in order.
<syntaxhighlight lang="raku" per6line>@collection>>.say;
@collection>>.=&infix:<+>(2); # increment each element by 2</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Loop/Foreach"
URL: http://rosettacode.org/wiki/Loop/Foreach
Line 2,203 ⟶ 2,562:
; the list from the current position.
 
forall x [prin rejoin [x/1 "day "]] print ""</langsyntaxhighlight>
Output:
<pre>Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday
Line 2,209 ⟶ 2,568:
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">>> blk: ["John" 23 "dave" 30 "bob" 20 "Jeff" 40]
>> foreach item blk [print item]
John
Line 2,233 ⟶ 2,592:
20 Jeff 40
Jeff 40
40</langsyntaxhighlight>
 
=={{header|ReScript}}==
<langsyntaxhighlight ReScriptlang="rescript">let fruits = ["apple", "banana", "coconut"]
 
Js.Array2.forEach(fruits, f => Js.log(f))</langsyntaxhighlight>
 
=={{header|Retro}}==
Retro has '''for-each''' combinators for operating on elements of various data structures.
 
<langsyntaxhighlight Retrolang="retro"># Strings
 
This will display the ASCII code for each character in a string
Line 2,266 ⟶ 2,625:
&Dictionary [ d:name s:put sp ] d:for-each
~~~
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes'
 
do j=1 for words(days) /*loop through days of the week. */
say word(days,j) /*display the weekday to screen. */
end /*j*/
/*stick a fork in it, we're done.*/</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = "Welcome to the Ring Programming Language"
for n in aList
see n + nl
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
In RPL, « printing » a collection means sending it to the printer, if you have one. To just output the items of a list, you put them into the stack, like this:
≪ { "one" "two" "three" "four" "five" } LIST→ DROP ≫
If the idea is to do more than displaying the items, the usual way is a <code>FOR..NEXT</code> loop
≪ { "one" "two" "three" "four" "five" } → collection
≪ 1 collection SIZE '''FOR''' j
collection j GET
''(do something with the item here)''
'''NEXT'''
≫ ≫
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">for i in collection do
puts i
end</langsyntaxhighlight>
This is syntactic sugar for:
<langsyntaxhighlight lang="ruby">collection.each do |i|
puts i
end</langsyntaxhighlight>
There are various flavours of <code>each</code> that may be class-dependent: [http://www.ruby-doc.org/core/classes/String.html#M000862 String#each_char], [http://www.ruby-doc.org/core/classes/Array.html#M002174 Array#each_index], [http://www.ruby-doc.org/core/classes/Hash.html#M002863 Hash#each_key], etc
 
=={{header|Rust}}==
Rust's for-loop already is a foreach-loop.
<langsyntaxhighlight lang="rust">let collection = vec![1,2,3,4,5];
for elem in collection {
println!("{}", elem);
}</langsyntaxhighlight>
 
Do note that Rust moves values by default and doesn't copy them. A vector would be unusable after looping over it like above. To preserve it, borrow it or use an Iter, to mutate values do a mutable borrow or create an IterMut. To get an immutable reference omit the mut-part.
<langsyntaxhighlight lang="rust">let mut collection = vec![1,2,3,4,5];
for mut_ref in &mut collection {
// alternatively:
Line 2,315 ⟶ 2,685:
// for immut_ref in collection.iter() {
println!("{}", *immut_ref);
}</langsyntaxhighlight>
 
Since Rust 1.21 foreach can be used explicitly executing a closure on each element.
<langsyntaxhighlight lang="rust">let collection = vec![1, 2, 3, 4, 5];
collection.iter().for_each(|elem| println!("{}", elem));</langsyntaxhighlight>
 
=={{header|Salmon}}==
<langsyntaxhighlight Salmonlang="salmon">iterate (x; ["Red", "Green", "Blue"])
x!;</langsyntaxhighlight>
output:
<pre>
Line 2,332 ⟶ 2,702:
 
=={{header|SAS}}==
<langsyntaxhighlight lang="sas">/* Initialize an array with integers 1 to 10, and print their sum */
data _null_;
array a a1-a10;
Line 2,342 ⟶ 2,712:
s=sum(of a{*});
put s;
run;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
num:ARRAY{INT} := |1, 5, 4, 3, 10|;
Line 2,354 ⟶ 2,724:
end;
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val collection = Array(1, 2, 3, 4)
collection.foreach(println)</langsyntaxhighlight>
Alternatively:
<langsyntaxhighlight lang="scala">(element <- 1 to 4).foreach(println)</langsyntaxhighlight>
 
=={{header|Scheme}}==
List:
<langsyntaxhighlight lang="scheme">(for-each
(lambda (i) (display i) (newline))
the_list)</langsyntaxhighlight>
 
=={{header|Scilab}}==
{{works with|Scilab|5.5.1}}
<syntaxhighlight lang="text">for e=["a","b","c"]
printf("%s\n",e)
end</langsyntaxhighlight>
{{out}}
<pre>a
Line 2,380 ⟶ 2,750:
=={{header|Seed7}}==
The for loop of Seed7 can be used to loop over the elements of a container.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
var array string: things is [] ("Apple", "Banana", "Coconut");
Line 2,391 ⟶ 2,761:
writeln(thing);
end for;
end func;</langsyntaxhighlight>
 
=={{header|Self}}==
<langsyntaxhighlight lang="self">aCollection do: [| :element | element printLine ].</langsyntaxhighlight>
(Provided that the objects in the collection understand the <code>printLine</code> method).
 
=={{header|SETL}}==
<langsyntaxhighlight lang="setl">S := {1,2,3,5,8,13,21,34,55,89};
for e in S loop
print(e);
end loop;</langsyntaxhighlight>
 
=={{header|Sidef}}==
'''foreach''' loop:
<langsyntaxhighlight lang="ruby">foreach [1,2,3] { |i|
say i
}</langsyntaxhighlight>
 
'''for-in''' loop:
<langsyntaxhighlight lang="ruby">for i in [1,2,3] {
say i
}</langsyntaxhighlight>
 
'''.each''' method:
<langsyntaxhighlight lang="ruby">[1,2,3].each { |i|
say i
}</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">c do: [| :obj | print: obj].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">aCollection do: [ :element | element displayNl ].</langsyntaxhighlight>
Provided that the objects in the collection understand the <code>displayNl</code> method (which can be added, if missing).
 
Most modern Smalltalks allow for a selector symbol to be sent a <tt>value:</tt> message; which allows for the very compact:
<syntaxhighlight lang ="smalltalk">aCollection do:#displayNl.</langsyntaxhighlight>
 
(and because Aikido mentions it: of course this works for any kind of collection (and even things which simply implement a <tt>do:</tt> method to iterate on something)
<langsyntaxhighlight lang="smalltalk">(1 to:6 by:2) do:#displayNl.
'hello' do:#displayNl.
(Integer primesUpTo:100) do:#displayNl.
Line 2,442 ⟶ 2,812:
arg value:'no classes needed'].
funnyClassLessObject do:#displayNl.
etc.</langsyntaxhighlight>
{{out}}
1
Line 2,469 ⟶ 2,839:
=={{header|Snabel}}==
Prints foo, bar & baz followed by newlines.
<langsyntaxhighlight lang="snabel">['foo' 'bar' 'baz'] &say for</langsyntaxhighlight>
 
=={{header|Sparkling}}==
Line 2,475 ⟶ 2,845:
Sparkling currently has no "foreach" construct, but there's a "foreach" function in the standard library:
 
<langsyntaxhighlight lang="sparkling">let hash = { "foo": 42, "bar": 1337, "baz": "qux" };
foreach(hash, function(key, val) {
print(key, " -> ", val);
});</langsyntaxhighlight>
 
=={{header|Standard ML}}==
List of integers:
<langsyntaxhighlight lang="sml">app
(fn i => print (Int.toString i ^ "\n"))
collect_list</langsyntaxhighlight>
Array of integers:
<langsyntaxhighlight lang="sml">Array.app
(fn i => print (Int.toString i ^ "\n"))
collect_array</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">local a 2 9 4 7 5 3 6 1 8
foreach i in `a' {
display "`i'"
}</langsyntaxhighlight>
 
=={{header|Suneido}}==
<langsyntaxhighlight Suneidolang="suneido">for i in #(1, 2, 3)
Print(i)</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">for i in [1,2,3] {
print(i)
}</langsyntaxhighlight>
This works for any type that conforms to the <code>SequenceType</code> protocol (including arrays, collections, generators, ranges).
 
Alternately:
{{works with|Swift|2.x+}}
<langsyntaxhighlight lang="swift">[1,2,3].forEach {
print($0)
}</langsyntaxhighlight>
 
=={{header|SystemVerilog}}==
<langsyntaxhighlight SystemVeriloglang="systemverilog">program main;
int values[$];
 
Line 2,522 ⟶ 2,892:
end
end
endprogram</langsyntaxhighlight>
 
=={{header|Tailspin}}==
Stream them
<langsyntaxhighlight lang="tailspin">
['a', 'b', 'c'] ... -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>abc</pre>
 
Lists/arrays can be put through an array transform to get the index as well
<langsyntaxhighlight lang="tailspin">
['a', 'b', 'c'] -> \[i]('$i;:$;
' -> !OUT::write \) -> !VOID
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,545 ⟶ 2,915:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">foreach i {foo bar baz} {
puts "$i"
}</langsyntaxhighlight>
Note that <tt>foreach</tt> also accepts multiple variables:
<langsyntaxhighlight lang="tcl">foreach {x y} {1 2 3 4} {
puts "$x,$y"
}</langsyntaxhighlight>
And also multiple lists:
<langsyntaxhighlight lang="tcl">foreach i {1 2 3} j {a b c} {
puts "$i,$j"
}</langsyntaxhighlight>
Or any combination of variables/list:
<langsyntaxhighlight lang="tcl">foreach i {1 2 3} {x y} {a b c d e f} {
puts "$i,$x,$y"
}</langsyntaxhighlight>
 
=={{header|Trith}}==
<langsyntaxhighlight lang="trith">[1 2 3 4 5] [print] each</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
week="Monday'Tuesday'Wednesday'Thursday'Friday'Saterday'Sunday"
LOOP day=week
PRINT day
ENDLOOP</langsyntaxhighlight>
Output:
<pre>
Line 2,584 ⟶ 2,954:
To iterate any single list, you use a <code>for</code> loop.
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">for file in *.sh; do
echo "filename is $file"
done</langsyntaxhighlight>
If the list is in a shell parameter (like <code>PATH</code>), you adjust <code>IFS</code>.
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash">PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11R6/bin:/usr/local/bin
 
oldifs=$IFS
Line 2,596 ⟶ 2,966:
echo search $dir
done
IFS=$oldifs</langsyntaxhighlight>
Some shells have real arrays. The <code>for</code> loop can also iterate these.
{{works with|Bash}}
<langsyntaxhighlight lang="bash">collection=("first" "second" "third" "fourth" "something else")
for x in "${collection[@]}"; do
echo "$x"
done</langsyntaxhighlight>
{{works with|pdksh|5.2.14}}
<langsyntaxhighlight lang="bash">set -A collection "first" "second" "third" "fourth" "something else"
for x in "${collection[@]}"; do
echo "$x"
done</langsyntaxhighlight>
 
==={{header|C Shell}}===
<langsyntaxhighlight lang="csh">set collection=(first second third fourth "something else")
foreach x ($collection:q)
echo $x:q
end</langsyntaxhighlight>
 
=={{header|V}}==
<langsyntaxhighlight lang="v">[1 2 3] [puts] step</langsyntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">List<string> things = new List<string> ();
things.append("Apple");
things.append("Banana");
Line 2,627 ⟶ 2,997:
{
stdout.printf("%s\n", thing);
}</langsyntaxhighlight>
 
=={{header|Vim Script}}==
Vim Script's for-loop is actually a foreach-loop and iterates through a list.
<langsyntaxhighlight lang="vim">for i in ["alpha", "beta", 42, 5.54]
echo i
endfor</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
 
<syntaxhighlight lang="v (vlang)">fn print_all(values []int) {
for i, x in values {
println("Item $i = $x")
}
}</syntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">each x '(1 2 3)
prn x</langsyntaxhighlight>
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let a => import 'arrays';
let s => import 'stream';
 
Line 2,646 ⟶ 3,025:
-> s.map (io.writeln io.stdout)
-> s.drain
;</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">for (f in ["apples", "oranges", "pears"]) System.print(f)</langsyntaxhighlight>
 
{{out}}
Line 2,660 ⟶ 3,039:
=={{header|XLISP}}==
XLISP's <tt>FOR-EACH</tt> applies a procedure to each member of a list in turn.
<langsyntaxhighlight lang="lisp">(FOR-EACH PRINT '(CYRUS CAMBYSES DARIUS XERXES ARTAXERXES))</langsyntaxhighlight>
{{out}}
<pre>CYRUS
Line 2,670 ⟶ 3,049:
=={{header|XPL0}}==
Translation of C example:
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
int List, I;
[List:= ["Red", "Green", "Blue", "Black", "White"];
for I:= 0, 5-1 do
[Text(0, List(I)); CrLf(0)];
]</langsyntaxhighlight>
 
=={{header|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.
<langsyntaxhighlight lang="xml"><fo:block font-weight="bold">Adults:</fo:block>
<xsl:for-each select="person[@age &gt;= 21]">
<fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
</xsl:for-each></langsyntaxhighlight>
 
=={{header|zig}}==
<langsyntaxhighlight lang="zig">const warn = @import("std").debug.warn;
pub fn main() void {
Line 2,694 ⟶ 3,073:
}
}
</syntaxhighlight>
</lang>
 
=={{header|zkl}}==
{{trans|XPL0}}
<langsyntaxhighlight lang="zkl">foreach c in (T("Red","Green","Blue","Black","White"))
{ print(c," "); }</langsyntaxhighlight>
{{out}}
<pre>Red Green Blue Black White</pre>
Other forms of foreach, one that breaks apart a container into elements and one line nested loops.
<langsyntaxhighlight lang="zkl">foreach x,y,z in (T(T(1,2,3), T(4,5,6))) { println(x,y,z) }
foreach x,y,z in (T(1,2,3), T(4,5), T(6)){ println(x,y,z) }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,718 ⟶ 3,097:
356
</pre>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() !void {
const stdout_wr = std.io.getStdOut().writer();
 
// 1. Index element index sizes are comptime-known
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' };
// also works with slices
//const a2: [] u8 = &a1;
for (a1) |el_a|
try stdout_wr.print("{c}\n", .{el_a});
// 2. Index element index sizes are not comptime-known
// Convention is to provide a `next()` method.
// TODO
}</syntaxhighlight>
 
{{omit from|GUISS}}
{{omit from|PL/0}}
{{omit from|Tiny BASIC}}
3

edits