Loops/Foreach: Difference between revisions
Content deleted Content added
Add ed example |
|||
(113 intermediate revisions by 62 users not shown) | |||
Line 22:
* [[Loops/Wrong ranges]]
<br><br>
=={{header|11l}}==
{{trans|C#}}
<syntaxhighlight lang="11l">V things = [‘Apple’, ‘Banana’, ‘Coconut’]
L(thing) things
print(thing)</syntaxhighlight>
=={{header|ACL2}}==
<
(if (endp xs)
nil
(prog2$ (cw "~x0~%" (first xs))
(print-list (rest xs)))))</
<pre>
Line 39 ⟶ 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===
<
use Ada.Integer_Text_IO;
Line 56 ⟶ 100:
end loop;
end For_Each;</
Alternative solution (Ada 2012):
<
Put( Item );
end loop;</
===doubly linked lists===
{{works with|Ada 2005}}
<
use Ada.Integer_Text_IO, Ada.Containers;
Line 90 ⟶ 134:
DL_List.Iterate (Print_Node'Access);
end Doubly_Linked_List;</
===vectors===
{{works with|Ada 2005}}
<
use Ada.Integer_Text_IO, Ada.Containers;
Line 117 ⟶ 161:
V.Iterate (Print_Element'Access);
end Vector_Example;</
=={{header|Aikido}}==
Aikido's <code>foreach</code> loop allows iteration through multiple value types.
===strings===
<
foreach ch str { // you can also use an optional 'in'
println (ch) // one character at a time
}</
===vectors===
<
foreach v vec { // you can also use an optional 'in'
println (v)
}</
===maps===
<
foreach city cities {
println (city.first + " has population " + city.second)
}</
===integers===
<
println (i) // prints values 0..99
}
Line 149 ⟶ 193:
foreach i a..b {
println (i) // prints values from a to b (20..10)
}</
===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
<
class Element (public data) {
public var next = null
Line 185 ⟶ 229:
foreach n list {
println (n)
}</
===Coroutines===
Aikido supports coroutines. The foreach operator may be used to iterate thorough the generated values.
<
function squares (start, end) {
for (var i = start ; i < end ; i++) {
Line 200 ⟶ 244:
foreach s squares (start, end) {
println (s)
}</
===Files===
If you open a file you can iterate through all the lines
<
foreach line s {
print (line)
}</
===Enumerations===
<
RED, GREEN, BLUE
}
Line 214 ⟶ 258:
foreach color Color {
println (color)
}</
=={{header|Aime}}==
<
integer i, v;
for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) {
}</
=={{header|ALGOL 68}}==
Line 228 ⟶ 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}}
<
FOR index FROM LWB collection TO UPB collection DO
print((collection[index]," "))
OD</
Output:
<pre>
Mary Had +1 little lamb.
</pre>
<br>
[[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}}==
<
DEF a_list : PTR TO LONG, a
a_list := [10, 12, 14]
Line 248 ⟶ 342:
-> if the "action" fits a single statement, we can do instead
ForAll({a}, a_list, `WriteF('\d\n', a))
ENDPROC</
=={{header|Apex}}==
<syntaxhighlight lang="apex">
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Line 257 ⟶ 351:
System.debug(i);
}
</syntaxhighlight>
=={{header|AppleScript}}==
<
log contents of fruit
end repeat</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">arr: ["one" "two" "three"]
dict: #[
name: "John"
surname: "Doe"
age: 34
]
loop arr 'item ->
print item
loop dict [key val]->
print [key "=>" val]</syntaxhighlight>
{{out}}
<pre>one
two
three
name => John
surname => Doe
age => 34</pre>
=={{header|AutoHotkey}}==
<
Loop, Parse, string, `,
MsgBox %A_LoopField%</
=={{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).
<
BEGIN {
split("Mary had a little lamb", strs, " ")
Line 277 ⟶ 393:
print strs[el]
}
}</
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 283 ⟶ 399:
So to iterate over the array's elements in the ''right'' order,
a normal loop can be used:
<
n = split("Mary had a little lamb", strs, " ")
for(i=1; i <= n; i++) {
print strs[i]
}
}</
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:
<
BEGIN {
for (
print "I like "
}
}</syntaxhighlight>
=={{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}}==
==={{header|BaCon}}===
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.
<syntaxhighlight lang="freebasic">OPTION COLLAPSE TRUE
FOR x$ IN "Hello cruel world"
PRINT x$
NEXT
FOR y$ IN "1,2,\"3,4\",5" STEP ","
PRINT y$
NEXT</syntaxhighlight>
{{out}}
<pre>prompt$ bacon -q forin.bac >/dev/null
prompt$ ./forin
Hello
cruel
world
1
2
"3,4"
5</pre>
The <code>OPTION COLLAPSE TRUE</code> statements prevents empty results when multiple delimiters appear together. The default delimiter is space, and can be changed with <code>OPTION DELIM x</code> where x is a static string literal.
==={{header|BASIC256}}===
BASIC-256 does not have a FOR EACH type statement. Use a FOR loop to iterate through an array by index.
<
collection$ = { "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog." }
Line 309 ⟶ 498:
PRINT collection$[i]+ " ";
NEXT i
PRINT</
Output:
<pre>The quick brown fox jumps over the lazy dog.</pre>
Line 315 ⟶ 504:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
collection$() = "The", "quick", "brown", "fox", "jumps", \
\ "over", "the", "lazy", "dog."
Line 322 ⟶ 511:
PRINT collection$(index%) " ";
NEXT
PRINT</
==={{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
<
20 REM *** FILL ARRAY WITH WORDS ***
30 FOR I = 0 TO 8
Line 336 ⟶ 525:
90 NEXT
100 END
1000 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</
==={{header|Creative Basic}}===
<
AnArray=0,1,2,3,4,5,6,7,8,9,10
Line 358 ⟶ 547:
'because this is a console only program.
END
</syntaxhighlight>
==={{header|FreeBASIC}}===
<
' FreeBASIC doesn't have a foreach loop but it's easy to manufacture one using macros
Line 378 ⟶ 567:
Print
Sleep</
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10 11
</pre>
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=cb94500c68749f6f93915f3f10de5a03 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siInput As Short[] = [1, 8, 0, 6, 4, 7, 3, 2, 5, 9]
Dim siTemp As Short
For Each siTemp In siInput.Sort()
Print siTemp;;
Next
End</syntaxhighlight>
{{out}}
<pre>
0 1 2 3 4 5 6 7 8 9
</pre>
==={{header|IS-BASIC}}===
<
110 LET I=1
120 DO
Line 395 ⟶ 600:
170 PRINT COLLECTION$(J);" ";
180 NEXT
190 DATA The,quick,brown,fox,jumps,over,the,lazy,dog.</
==={{header|IWBASIC}}===
'''Linked List'''
<
AList=ListCreate()
Line 430 ⟶ 635:
'Because this is a console only program.
END</
'''An Array'''
<
AnArray=0,1,2,3,4,5,6,7,8,9,10
Line 450 ⟶ 655:
'Because this is a console only program.
END
</syntaxhighlight>
==={{header|Lambdatalk}}===
<syntaxhighlight lang="scheme">
{def collection alpha beta gamma delta}
-> collection
{S.map {lambda {:i} {br}:i} {collection}}
->
alpha
beta
gamma
delta
or
{def S.foreach
{lambda {:s}
{if {S.empty? {S.rest :s}}
then {S.first :s}
else {S.first :s} {br}{S.foreach {S.rest :s}}}}}
{S.foreach {collection}}
->
alpha
beta
gamma
delta
</syntaxhighlight>
==={{header|Liberty BASIC}}===
The most natural way is to use a csv list with a sentinel value.
<
element$ =""
i =1 ' used to point to successive elements
Line 465 ⟶ 699:
loop until 1 =2
end</
Not good!
Hardly good!
Line 474 ⟶ 708:
Very good!
Fantastically good!
==={{header|NS-HUBASIC}}===
<syntaxhighlight lang="ns-hubasic">10 DIM A$(9) : REM DECLARE STRING ARRAY
20 REM ADD DATA TO ARRAY AND PRINT ARRAY CONTENTS
30 FOR I=0 TO 8
40 READ A$(I)
50 PRINT A$(I)" ";
60 NEXT
70 DATA THE, QUICK, BROWN, FOX, JUMPS, OVER, THE, LAZY, DOG.</syntaxhighlight>
==={{header|PureBasic}}===
Works for LinkedLists and Maps
<
PrintN(element())
Next</
==={{header|Run BASIC}}===
<
while word$(t$,i+1,",") <> ""
i = i + 1
print word$(t$,i,",")
wend</
==={{header|TI-89 BASIC}}===
<
Define strs = {"Lorem","ipsum","dolor"}
For i, 1, dim(strs)
Disp strs[i]
EndFor</
==={{header|VBA}}===
<syntaxhighlight lang="vb">Public Sub LoopsForeach()
Dim FruitArray() As Variant
Dim Fruit As Variant
FruitArray = [{"Apple","Banana","Strawberry"}]
Dim FruitBasket As Collection
Set FruitBasket = New Collection
For Each Fruit In FruitArray
FruitBasket.Add Fruit
Next Fruit
For Each Fruit In FruitBasket
Debug.Print Fruit
Next Fruit
End Sub</syntaxhighlight>
==={{header|VBScript}}===
<syntaxhighlight lang="vbscript">items = Array("Apple", "Orange", "Banana")
For Each x In items
WScript.Echo x
Next</syntaxhighlight>
==={{header|Visual Basic .NET}}===
<
list.Add("Car")
list.Add("Boat")
Line 504 ⟶ 769:
For Each item In list
Console.WriteLine(item)
Next</
==={{header|Yabasic}}===
<syntaxhighlight lang="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
dim arreglo(10)
data 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
for each = 0 to arraysize(a(),1)
read arreglo(each)
next each
for each = 0 to arraysize(a(),1)
print arreglo(each), " ";
next each
print
end</syntaxhighlight>
=={{header|Batch File}}==
Line 510 ⟶ 794:
'''Direct usage:'''
<
for %%A in (This is a sample collection) do (
echo %%A
)</
'''Using a Collection Variable:'''
<
set "collection=This is a sample collection"
for %%A in (%collection%) do (
echo %%A
)</
{{Out|They have the Same Output}}
<pre>This
Line 529 ⟶ 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.
<
a[1] = 234
a[3] = 95.6
for (i = 0; i < 4; i++) {
a[i]
}</
=={{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:
<
= Afrikaans
Ελληνικά
Line 545 ⟶ 829:
മലയാളം
ئۇيغۇرچە
)</
The 'while' solution. Use an auxiliary variable <code>L</code> that gets its head chopped off until nothing is left:
<
& whl'(!L:%?language ?L&out$!language)</
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.
<
& ( loop
= !L:%?language ?L
Line 556 ⟶ 840:
& !loop
)
& ~!loop</
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.
<
: ? (%@?language&out$!language&~) ?
|
)</
=={{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.
<
...
Line 574 ⟶ 858:
for(ix=0; ix<LIST_SIZE; ix++) {
printf("%s\n", list[ix]);
}</
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">
#include <stdio.h>
#include <stdlib.h>
Line 597 ⟶ 881:
return(0);
}
</syntaxhighlight>
C int array as a collection of int (array size known at compile-time)
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 617 ⟶ 901:
return(0);
}
</syntaxhighlight>
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[0])] can be used in it's place with [[GCC]]''
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 646 ⟶ 930:
return(0);
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">string[] things = {"Apple", "Banana", "Coconut"};
foreach (string thing in things)
{
Console.WriteLine(thing);
}</syntaxhighlight>
=={{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.
<
{
std::cout << *i << "\n";
}</
However the idiomatic way to output a container would be
<
std::ostream_iterator<container_type::value_type>(std::cout, "\n"));</
There's also an algorithm named <tt>for_each</tt>. However, you need a function or function object to use it, e.g.
<
{
std::cout << v << "\n";
Line 664 ⟶ 956:
...
std::for_each(container.begin(), container.end(), print_element);</
{{works with|C++11}}
<
{
std::cout << element << "\n";
}</
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:
<
{
std::cout << element << "\n";
}</
Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant):
<
{
element += 42;
}</
=={{header|
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}}==
<
for f in food do writeln(f);</
=={{header|Clojure}}==
<
=={{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}}==
<
foreach(file ${list})
message(${file})
endforeach(file)</
=={{header|COBOL}}==
Line 707 ⟶ 1,018:
{{trans|C#}}
{{works with|Visual COBOL}}
<
...
set content of things to ("Apple", "Banana", "Coconut")
perform varying thing as string through things
display thing
end-perform</
=={{header|ColdFusion}}==
<
<Cfloop list="Fee, Fi, Foe, Fum" index="i">
<Cfoutput>#i#!</Cfoutput>
</Cfloop>
</syntaxhighlight>
=={{header|Common Lisp}}==
<
or
<
or
<syntaxhighlight lang="lisp">(dolist (x the-list) (print x))</syntaxhighlight>
or
<syntaxhighlight lang="lisp">(use-package :iterate)
(iter
(for x in the-list)
(print x))</syntaxhighlight>
=== Using DO ===
<syntaxhighlight 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>
{{out}}
<pre>
1
7
"foo"
1
4
</pre>
=={{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.
<
void main() {
Line 746 ⟶ 1,080:
foreach (key, value; collection3)
writeln(key, " ", value);
}</
{{out}}
<pre>A
Line 762 ⟶ 1,096:
=={{header|Dao}}==
<
for( item in items ) io.writeln( item )</
=={{header|Delphi}}==
Line 769 ⟶ 1,103:
Supports arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator().
<
{$APPTYPE CONSOLE}
Line 778 ⟶ 1,112:
for s in 'Hello' do
Writeln(s);
end.</
Output:
<pre>H
Line 785 ⟶ 1,119:
l
o</pre>
=={{header|Dragon}}==
<syntaxhighlight lang="dragon">
for value : array {
showln value
}
</syntaxhighlight>
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">for i in [1,2,3] {
print(i)
}</syntaxhighlight>
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:
<syntaxhighlight lang="dyalect">for i in [1,2,3].Iterate() {
print(i)
}</syntaxhighlight>
This would perfectly work with any custom iterator as well:
<syntaxhighlight lang="dyalect">func myCollection() {
yield 1
yield 2
yield 3
}
for i in myCollection() {
print(i)
}</syntaxhighlight>
All three code samples would output:
<pre>1
2
3</pre>
=={{header|E}}==
<
println(e)
}</
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}}==
<
(define my-list '( albert simon antoinette))
(for ((h my-list)) (write h))
Line 807 ⟶ 1,184:
;; etc ... for other collections like Streams, Hashes, Graphs, ...
</syntaxhighlight>
=={{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|Ed}}==
Print all (newline-separated) lines in the file.
<syntaxhighlight lang="sed">
,p
</syntaxhighlight>
=={{header|Efene}}==
Any data structure can be printed as a whole, preformated:
<
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.
<
=={{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>.
<
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 824 ⟶ 1,262:
This iteration is a boolean expression which is true if all items in <code>my_list</code> have counts greater than three:
<
Whereas, the following is true if at least one item has a count greater than three:
<
=={{header|Ela}}==
<
each [] = do return ()
each (x::xs) = do
putStrLn $ show x
each xs</
=={{header|Elena}}==
ELENA
<
import extensions
public program()
{
var things :=
things
console
}</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)
}
}</syntaxhighlight>
=={{header|Elixir}}==
<
[1, 3.14, "abc", [3], {0, 5}]
iex(2)> Enum.each(list, fn x -> IO.inspect x end)
Line 860 ⟶ 1,311:
[3]
{0, 5}
:ok</
=={{header|Emacs Lisp}}==
For a list either <code>dolist</code> macro
<
(message "x=%d" x))</
or <code>mapc</code> function
<
(message "x=%d" x))
'(1 2 3 4))</
{{libheader|cl-lib}}
<syntaxhighlight lang="lisp">(cl-loop for x in '(1 2 3 4) do (message "x=%d" x))</syntaxhighlight>
=={{header|Erlang}}==
Any data structure can be printed as a whole, preformated:
<
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.
<
=={{header|ERRE}}==
It's an extension of 'standard' FOR loop: constant list must be explicit.
<
FOR INDEX$=("The","quick","brown","fox","jumps","over","the","lazy","dog.") DO
PRINT(INDEX$;" ";)
END FOR
PRINT
</syntaxhighlight>
=={{header|Euphoria}}==
{{works with|OpenEuphoria}}
<syntaxhighlight lang="euphoria">
include std/console.e
Line 922 ⟶ 1,371:
if getc(0) then end if
</syntaxhighlight>
{{out}}
<pre>
Line 960 ⟶ 1,409:
2
</pre>
=={{header|F_Sharp|F#}}==
We can use ''for'' directly or list iteration.
<syntaxhighlight lang="fsharp">for i in [1 .. 10] do printfn "%d" i
List.iter (fun i -> printfn "%d" i) [1 .. 10]</syntaxhighlight>
=={{header|Factor}}==
<
=={{header|Fantom}}==
Use <code>each</code> method to iterate over a collection of items in a <code>List</code>.
<
{
public static Void main ()
Line 976 ⟶ 1,431:
}
}
}</
=={{header|
====sequential table====
<syntaxhighlight lang="fennel">(each [k v (ipairs [:apple :banana :orange])]
(print k v))</syntaxhighlight>
{{out}}
<pre>1 apple
2 banana
3 orange</pre>
====key-value table====
<syntaxhighlight lang="fennel">(each [k v (pairs {:apple :x :banana 4 :orange 3})]
(print k v))</syntaxhighlight>
{{out}}
<pre>apple x
banana 4
orange 3</pre>
=={{header|Forth}}==
<syntaxhighlight lang="forth">create a 3 , 2 , 1 ,
: .array ( a len -- )
cells bounds do i @ . cell +loop ; \ 3 2 1</syntaxhighlight>
===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}}==
<
implicit none
Line 1,006 ⟶ 1,494:
write(*,'(A)') colors
end program main</
=={{header|
Unlike, bash or csh, the PATH variable is automatically converted to real array.
<syntaxhighlight lang="fishshell">for path in $PATH
echo You have $path in PATH.
end</syntaxhighlight>
Sample output:
<pre>
You have /bin in PATH.
You have /usr/bin in PATH.
</pre>
=={{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.
<
array = [1, 2, 3, 5, 7]
for n = array
println[n]
</syntaxhighlight>
=={{header|
<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}}==
<
Print(p, "\n");
od;
Line 1,061 ⟶ 1,561:
(1,3,4)
(1,2)(3,4)
(1,4,2)</
=={{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.
<
for i, x := range values {
fmt.Printf("Item %d = %d\n", i, x)
}
}</
=={{header|Groovy}}==
"for" loop:
<
for(name in beatles) {
println name
}</
"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.
<
println it
}</
Output (same for either):
<pre>John
Line 1,090 ⟶ 1,590:
=={{header|Halon}}==
<
foreach ($things as $thing) {
echo $thing;
}</
=={{header|Haskell}}==
<
forM_ collect print</
which is the same as
<syntaxhighlight lang
=={{header|Haxe}}==
<
for (i in a)
=={{header|HicEst}}==
<
items = INDEX(days, ' ', 256) ! 256 = count option
Line 1,115 ⟶ 1,615:
EDIT(Text=days, ITeM=j, Parse=today)
WRITE() today
ENDDO</
=={{header|Hy}}==
<
=={{header|Icon}} and {{header|Unicon}}==
The example below X can be a list, string, table or other data type.
<
X := [1,2,3,-5,6,9]
every x := !L do
write(x)
end</
This loop can be written somewhat more concisely as:
<syntaxhighlight lang
=={{header|Io}}==
<syntaxhighlight lang="io">collection foreach(println)</syntaxhighlight>
=={{header|J}}==
<syntaxhighlight lang="j"> echo every i.10
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+}}
<
...
for(Type i:collect){
System.out.println(i);
}</
This works for any array type as well as any type that implements the Iterable interface (including all Collections).
{{works with|Java|1.8+}}
<syntaxhighlight lang="java">
Iterable collect;
...
collect.forEach(o -> System.out.println(o));
</syntaxhighlight>
This works with any Iterable, but not with arrays.
=={{header|JavaScript}}==
For arrays in ES5, we can use '''Array.forEach()''':
<syntaxhighlight lang="javascript">"alpha beta gamma delta".split(" ").forEach(function (x) {
console.log(x);
});</syntaxhighlight>
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use '''Array.map()''',
<syntaxhighlight lang="javascript">console.log("alpha beta gamma delta".split(" ").map(function (x) {
return x.toUpperCase(x);
}).join("\n"));</syntaxhighlight>
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
<syntaxhighlight lang="javascript">console.log("alpha beta gamma delta".split(" ").reduce(function (a, x, i, lst) {
return lst.length - i + ". " + x + "\n" + a;
}, ""));</syntaxhighlight>
More generally, the following works for any object, including an array. It iterates over the keys of an object.
<
print(o[a]);
}</
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:
<
if (o.hasOwnProperty(a)) {
print(o[a]);
}
}</
{{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:
<
for (x in h) print(x);
for each (y in h) print(y);</syntaxhighlight>
{{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:
<
for (x in h) print(x);
for (y of h) print(y);</syntaxhighlight>
=={{header|jq}}==
'''Iterables''':
In this section, the array defined by "example" is used as an example:
<
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:
<
# or equivalently: example[]</
<
# or equivalently: {"a":1, "b":2}[]</
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:
<
For JSON objects, the corresponding technique involves using <tt>keys</tt>, e.g.
<syntaxhighlight lang="jq">
{"a":1, "b":2} | . as $o | keys | map( [., $o[.]] )
</syntaxhighlight>
produces:
[["a",1],["b",2]]
Line 1,272 ⟶ 1,739:
To convert the constituent characters (or technically, codepoints) of a string into a stream of values, there are two techniques illustrated by these examples:
<
"abc" | explode | map( [.]|implode) | .[]</
In both cases, the result is the stream of values: "a", "b", "c".
=={{header|Jsish}}==
Jsi supports ''for of'' for looping over element of an array.
<syntaxhighlight lang="javascript">for (str of "alpha beta gamma delta".split(' ')) { puts(str); }</syntaxhighlight>
{{out}}
<pre>alpha
beta
gamma
delta</pre>
=={{header|Julia}}==
{{trans|Python}}
<syntaxhighlight lang="julia">for i in collection
println(i)
end</syntaxhighlight>
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}}==
<syntaxhighlight lang="k"> {`0:$x} ' !10</syntaxhighlight>
<syntaxhighlight lang="k"> _sin ' (1; 2; 3;)</syntaxhighlight>
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
( -2 "field" 3.14159 ( "this" "that" ) ) len [get ?] for
" " input</syntaxhighlight>
{{out}}
<pre>-2
field
3.14159
("this", "that")</pre>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,288 ⟶ 1,788:
greek.forEach { print("$it ") }
println()
}</
{{out}}
Line 1,295 ⟶ 1,795:
alpha beta gamma delta
</pre>
=={{header|LabVIEW}}==
[[LabVIEW]] has a feature known as an Auto-Indexed Tunnel. It is the very small orange box on the lower left of the for loop.<br/>{{VI solution|LabVIEW_Loops_Foreach.png}}
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def collection alpha beta gamma delta}
-> collection
{S.map {lambda {:i} {br}:i} {collection}}
->
alpha
beta
gamma
delta
or
{def S.foreach
{lambda {:s}
{if {S.empty? {S.rest :s}}
then {S.first :s}
else {S.first :s} {br}{S.foreach {S.rest :s}}}}}
{S.foreach {collection}}
->
alpha
beta
gamma
delta
</syntaxhighlight>
=={{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}}==
<syntaxhighlight lang="lang5">: >>say.(*) . ;
5 iota >>say.</syntaxhighlight>
=={{header|langur}}==
A for in loop iterates over values and a for of loop iterates over keys.
<syntaxhighlight lang="langur">
for i in [1, 2, 3] {
writeln i
}
val abc = "abc"
for i in abc {
writeln i
}
for i of abc {
writeln abc[i]
}
for i in abc {
writeln cp2s(i)
}
</syntaxhighlight>
{{out}}
<pre>1
2
3
97
98
99
97
98
99
a
b
c</pre>
=={{header|Lasso}}==
<
<
=={{header|
<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}}==
<
(lambda (x)
(io:format "item: ~p~n" (list x)))
(lists:seq 1 10))
</syntaxhighlight>
=={{header|
<syntaxhighlight 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
print "Collection is: $collection"
# using default "i" variable name set for each item
foreach $collection {print $i}
# user named variable in the steps, retrieving accumulated result of loop
# each loop step quotes two copies of the item
set newlist [foreach j $collection {quote $j $j}]
print "Result of second foreach: $newlist"</syntaxhighlight>
{{out}}
<pre>prompt$ lil loopsForeach.lil
Collection is: 1 2 three {4 5 six}
1
2
three
4 5 six
Result of second foreach: {1 1} {2 2} {three three} {4 5 six 4 5 six}</pre>
=={{header|Lingo}}==
<
repeat with day in days
put day
end repeat</
A callback-based forEach() can be implemented like this:
<
-- One of the five native iterative methods defined in ECMAScript 5
-- @param {list} tList
Line 1,339 ⟶ 1,957:
call(cbFunc, cbObj, tList[i], i, tList)
end repeat
end</
<
forEach(days, #alert, _player)</
=={{header|Lisaac}}==
<
word.print;
'\n'.print;
};</
=={{header|LiveCode}}==
Livecode's ''for each'' operates on chunks which may be words, items, lines, tokens. Example is for items.<
put x & cr
--wait 100 millisec -- req'd if you want to see in the LC Message Box (akin to repl)
end repeat</
=={{header|Logo}}==
<
=={{header|Lua}}==
Line 1,362 ⟶ 1,980:
<code>pairs()</code> iterates over all entries in a table, but in no particular order:
<
for key, value in pairs(t) do
print(value, key)
end</
Output:
<pre>
Line 1,379 ⟶ 1,997:
<code>ipairs()</code> iterates over table entries with positive integer keys,
and is used to iterate over lists in order.
<
for key, value in ipairs(l) do
print(key, value)
end</
Output:
<pre>
Line 1,398 ⟶ 2,016:
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">
Module Checkit {
\\ Inventories may have keys or keys/values
Line 1,426 ⟶ 2,044:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<syntaxhighlight lang="maple">
for p in [2, 3, 5, 7] do
print(p);
end do;
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Foreach over list of strings
<
Do[
Print@i,
{i, s}
]</
Output:
<pre>We
Line 1,452 ⟶ 2,070:
=={{header|MATLAB}} / {{header|Octave}}==
<
for k = list1, % list1 must be a row vector (i.e. array of size 1xn)
printf('%i\n',k)
end; </
<
for k = list2, % list2 must be a row vector (i.e. array of size 1xn)
printf('%s\n',k{1})
end; </
A vectorized version of the code is
<
printf('%s\n',list2{:}); </
=={{header|Maxima}}==
<
=={{header|MAXScript}}==
<
arr = for i in 1 to 50 collect ("Number: " + (random 10 99) as string)
makeuniquearray arr
Line 1,474 ⟶ 2,092:
for i in arr do print i as string
</syntaxhighlight>
=={{header|Metafont}}==
If we have a list of arbitrary items, we can simply use for:
<
end</
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
<
end</
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}}
<syntaxhighlight lang="min">(1 2 3) 'puts foreach</syntaxhighlight>
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">for i in collection
print i
end</syntaxhighlight>
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}}==
<
for thing in (things)
player:tell(thing);
endfor</
=={{header|Nanoquery}}==
Like Python, Nanoquery supports for...in syntax for list types and strings.
<syntaxhighlight lang="nanoquery">for item in collection
println item
end</syntaxhighlight>
<strong>Some examples:</strong>
<syntaxhighlight lang="nanoquery">for n in {1,3,5,7,9}
print n + " "
end
println
for char in "test string"
print char
end
println</syntaxhighlight>
{{out}}
<pre>1 3 5 7 9
test string</pre>
=={{header|Nemerle}}==
This works on anything which implements the IEnumerable interface.
<
foreach (thing in things) WriteLine(thing.ToLower());
foreach (i in [5, 10 .. 100]) Write($"$i\t");</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 1,512 ⟶ 2,160:
loop while daysi.hasNext
say daysi.next
end</
=={{header|NewLISP}}==
<
=={{header|Nim}}==
<syntaxhighlight lang="nim">let list = ["lorem", "ipsum", "dolor"]
for item in list:
echo item</syntaxhighlight>
{{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}}==
<syntaxhighlight lang="objeck">fruits := ["Apple", "Banana", "Coconut"];
each(i : fruits) {
fruits[i]->PrintLine();
};</syntaxhighlight>
=={{header|Objective-C}}==
Line 1,535 ⟶ 2,196:
{{works with|GNUstep}}
{{works with|Cocoa}}
<
// ...
for (Type i in collect) {
NSLog(@"%@", i);
}</
''collect'' can be any object that adopts the NSFastEnumeration protocol.
Or (always using OpenStep compatible frameworks):
{{works with|Objective-C|<2.0}}
<
// ...
NSEnumerator *enm = [collect objectEnumerator];
id i;
while
// do something with object i
}</
=={{header|OCaml}}==
List of integers:
<
(fun i -> Printf.printf "%d\n" i)
collect_list</
Array of integers:
<
(fun i -> Printf.printf "%d\n" i)
collect_array</
=={{header|Octave}}==
<
b = [ 1,2,3,4; 5,6,7,8 ];
for v = a
Line 1,583 ⟶ 2,231:
for v = b
disp(v); % v is the column vector [1;5], then [2;6] ...
endfor</
We can also iterate over structures:
<
x.b = { "Cell", "ul", "ar" };
for [ val, key ] = x
disp(key);
disp(val);
endfor</
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">: printMonths | m | Date.Months forEach: m [ m . ] ;</syntaxhighlight>
But, apply can be used instead of a loop :
<syntaxhighlight lang="oforth">#. Date.Months apply</syntaxhighlight>
=={{header|Ol}}==
<syntaxhighlight lang="scheme">
(for-each print '(1 3 4 2))
(print)
(for-each (lambda (a b c) (print a "-" b "/" c))
'(1 2 3 4)
'(5 6 7 8)
'(a b x z))
</syntaxhighlight>
{{out}}
<pre>
1
3
4
2
1-5/a
2-6/b
3-7/x
4-8/z
</pre>
=={{header|ooRexx}}==
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.
<
say
say 'Loops/Foreach'
Line 1,607 ⟶ 2,284:
say out~strip()
exit</
'''Output:'''
<pre>
Line 1,615 ⟶ 2,292:
=={{header|Oz}}==
<
MyList = [1 2 3 4]
in
Line 1,621 ⟶ 2,298:
%% or:
for E in MyList do {Show E} end</
=={{header|PARI/GP}}==
<
or (PARI/GP >= 2.4)
<
=={{header|Pascal}}==
See [[Loops/Foreach#Delphi | Delphi]]
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
##
foreach var s in |'Pascal','ABC','.NET'| do
Print(s);
</syntaxhighlight>
=={{header|Perl}}==
<
print "$i\n";
}</
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:
<
In perl, it is possible to loop against an explicit list, so there is no need to define a container:
<
print "I like $l\n";
}</
=={{header|Phix}}==
<!--<syntaxhighlight lang="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>
<!--</syntaxhighlight>-->
=={{header|PHL}}==
<
numbers each # (number) [
printf("%i\n", number);
];</
=={{header|PHP}}==
<
echo "$i\n";
}
Line 1,680 ⟶ 2,354:
foreach ($collect as $key => $i) {
echo "\$collect[$key] = $i\n";
}</
<code>foreach</code> can also iterate over objects. By default it iterates over all visible fields of an object.
=={{header|PicoLisp}}==
<
=={{header|Pike}}==
<
array(int|string) collect = ({109, "Hi", "asdf", "qwerty"});
foreach(collect, int|string elem){
write(elem + "\n");
}
}</
Iterating over the keys and values of a mapping (dictionary):
<
mapping(string:string) coll = (["foo":"asdf", "bar":"qwer", "quux":"zxcv"]);
foreach (coll;string key;string val)
write(key+" --> "+val+"\n");
}
}</
=={{header|PL/I}}==
<
do i = lbound(A,1) to hbound(A,1);
put skip list (A(i));
end;</
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Create a list.
Write each entry in the list to the console.
Destroy the list.
Wait for the escape key.
Shut down.
An entry is a thing with a number.
A list is some entries.
To add a number to a list:
Allocate memory for an entry.
Put the number into the entry's number.
Append the entry to the list.
To create a list:
Add 1 to the list.
Add 2 to the list.
Add 3 to the list.
Add 6 to the list.
Add 7 to the list.
Add 9 to the list.
To write an entry to the console:
Convert the entry's number to a string.
Write the string to the console.
To write each entry in a list to the console:
Get an entry from the list.
Loop.
If the entry is nil, exit.
Write the entry to the console.
Put the entry's next into the entry.
Repeat.</syntaxhighlight>
{{out}}
<pre>
1
2
3
6
7
9
</pre>
=={{header|Pop11}}==
Iteration over list:
<
for el in lst do
printf(el,'%p\n');
endfor;</
=={{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:
<
(abc) { = } forall</
but dictionaries take a little more work since a key/value pair is pushed on the stack in each iteration:
<
exch (Key: ) print
=
(Value: ) print
=
} forall</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
$colors = "Black","Blue","Cyan","Gray","Green","Magenta","Red","White","Yellow",
"DarkBlue","DarkCyan","DarkGray","DarkGreen","DarkMagenta","DarkRed","DarkYellow"
Line 1,735 ⟶ 2,456:
Write-Host "$color" -ForegroundColor $color
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,758 ⟶ 2,479:
=={{header|Prolog}}==
For example :
<
red
green
Line 1,765 ⟶ 2,486:
white
true.
</syntaxhighlight>
=={{header|Python}}==
<
print i</
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:
<
f = open('somefile','r')
for eachline in f:
Line 1,784 ⟶ 2,504:
characters += 1
print lines, words, characters</
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 1,790 ⟶ 2,510:
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:
<
for k in sorted(d):
print("%i: %s" % (k, d[k]))
Line 1,796 ⟶ 2,516:
d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"}
for k in sorted(d):
print("%s: %s" % (k, d[k]))</
{{works with|Python|2.x}}
<
for k in sorted(d):
print("%s: %s" % (k, d[k]))</
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">$ "Sweet Boom Pungent Prickle Orange" nest$
witheach [ i times sp echo$ cr ]</syntaxhighlight>
{{Out}}
<pre> Sweet
Boom
Pungent
Prickle
Orange
</pre>
=={{header|R}}==
<
for(i in a) print(i)</
=={{header|Racket}}==
<
#lang racket
Line 1,819 ⟶ 2,551:
(for ([i sequence])
(displayln i))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2015.10-40}}
<syntaxhighlight lang="raku" line>say $_ for @collection;</syntaxhighlight>
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" line>for @collection -> $currentElement { say $currentElement; }</syntaxhighlight>
Raku will do it's best to put the topic at the right spot.
<syntaxhighlight lang="raku" line>.say for @collection;
for @collection { .say };</syntaxhighlight>
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" line>@collection>>.say;
@collection>>.=&infix:<+>(2); # increment each element by 2</syntaxhighlight>
=={{header|REBOL}}==
<
Title: "Loop/Foreach"
URL: http://rosettacode.org/wiki/Loop/Foreach
Line 1,834 ⟶ 2,579:
; the list from the current position.
forall x [prin rejoin [x/1 "day "]] print ""</
Output:
<pre>Sorkday Gunday Bluesday Nedsday Thirstday Frightday Caturday
Line 1,840 ⟶ 2,585:
=={{header|Red}}==
<
>> foreach item blk [print item]
John
Line 1,864 ⟶ 2,609:
20 Jeff 40
Jeff 40
40</
=={{header|ReScript}}==
<syntaxhighlight lang="rescript">let fruits = ["apple", "banana", "coconut"]
Js.Array2.forEach(fruits, f => Js.log(f))</syntaxhighlight>
=={{header|Retro}}==
Retro has
<syntaxhighlight lang="retro"># Strings
This will display the ASCII code for each character in a string
~~~
'This_is_a_message [ n:put sp ] s:for-each
~~~
# Array
Display each element
~~~
{ #1 #2 #3 } [ n:put sp ] a:for-each
~~~
# Linked List
Using the dictionary as an example, display each name
~~~
&Dictionary [ d:name s:put sp ] d:for-each
~~~
</syntaxhighlight>
=={{header|REXX}}==
<
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.*/</
=={{header|Ring}}==
<
aList = "Welcome to the Ring Programming Language"
for n in aList
see n + nl
next
</syntaxhighlight>
=={{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}}==
<
puts i
end</
This is syntactic sugar for:
<
puts i
end</
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.
<
for elem in collection {
println!("{}", elem);
}</
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.
<
for mut_ref in &mut collection {
// alternatively:
Line 1,933 ⟶ 2,702:
// for immut_ref in collection.iter() {
println!("{}", *immut_ref);
}</
Since Rust 1.21 foreach can be used explicitly executing a closure on each element.
<syntaxhighlight lang="rust">let collection = vec![1, 2, 3, 4, 5];
collection.iter().for_each(|elem| println!("{}", elem));</syntaxhighlight>
=={{header|Salmon}}==
<
x!;</
output:
<pre>
Line 1,946 ⟶ 2,719:
=={{header|SAS}}==
<
data _null_;
array a a1-a10;
Line 1,956 ⟶ 2,729:
s=sum(of a{*});
put s;
run;</
=={{header|Sather}}==
<
main is
num:ARRAY{INT} := |1, 5, 4, 3, 10|;
Line 1,968 ⟶ 2,741:
end;
end;
end;</
=={{header|Scala}}==
<
collection.foreach(println)</syntaxhighlight>
Alternatively:
<
=={{header|Scheme}}==
List:
<
(lambda (i) (display i) (newline))
the_list)</
=={{header|Scilab}}==
{{works with|Scilab|5.5.1}}
<syntaxhighlight lang="text">for e=["a","b","c"]
printf("%s\n",e)
end</
{{out}}
<pre>a
Line 1,996 ⟶ 2,767:
=={{header|Seed7}}==
The for loop of Seed7 can be used to loop over the elements of a container.
<
var array string: things is [] ("Apple", "Banana", "Coconut");
Line 2,007 ⟶ 2,778:
writeln(thing);
end for;
end func;</
=={{header|Self}}==
<
(Provided that the objects in the collection understand the <code>printLine</code> method).
=={{header|SETL}}==
<
for e in S loop
print(e);
end loop;</
=={{header|Sidef}}==
'''foreach''' loop:
<
say i
}</
'''for-in''' loop:
<
say i
}</
'''.each''' method:
<
say i
}</
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
<
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.</syntaxhighlight>
(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)
<syntaxhighlight lang="smalltalk">(1 to:6 by:2) do:#displayNl.
'hello' do:#displayNl.
(Integer primesUpTo:100) do:#displayNl.
'/' asFilename directoryContents do:#displayNl.
((Smalltalk allClasses collect:#name) asSortedCollection to:2) do:#displayNl.
funnyClassLessObject := Plug new
respondTo:#do:
with:[:arg |
arg value:'look ma'.
arg value:'no classes needed'].
funnyClassLessObject do:#displayNl.
etc.</syntaxhighlight>
{{out}}
1
3
5
h
e
l
l
o
2
3
5
...
97
home
usr
...
tmp
cores
AAAARecord
AATree
look ma
no classes needed
=={{header|Snabel}}==
Prints foo, bar & baz followed by newlines.
<
=={{header|Sparkling}}==
Line 2,050 ⟶ 2,862:
Sparkling currently has no "foreach" construct, but there's a "foreach" function in the standard library:
<
foreach(hash, function(key, val) {
print(key, " -> ", val);
});</
=={{header|Standard ML}}==
List of integers:
<
(fn i => print (Int.toString i ^ "\n"))
collect_list</
Array of integers:
<
(fn i => print (Int.toString i ^ "\n"))
collect_array</
=={{header|Stata}}==
<
foreach i in `a' {
display "`i'"
}</
=={{header|Suneido}}==
<
Print(i)</
=={{header|Swift}}==
<
print(i)
}</
This works for any type that conforms to the <code>SequenceType</code> protocol (including arrays, collections, generators, ranges).
Alternately:
{{works with|Swift|2.x+}}
<
print($0)
}</
=={{header|SystemVerilog}}==
<
int values[$];
Line 2,096 ⟶ 2,909:
end
end
endprogram</
=={{header|Tailspin}}==
Stream them
<syntaxhighlight lang="tailspin">
['a', 'b', 'c'] ... -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>abc</pre>
Lists/arrays can be put through an array transform to get the index as well
<syntaxhighlight lang="tailspin">
['a', 'b', 'c'] -> \[i]('$i;:$;
' -> !OUT::write \) -> !VOID
</syntaxhighlight>
{{out}}
<pre>
1:a
2:b
3:c
</pre>
=={{header|Tcl}}==
<
puts "$i"
}</
Note that <tt>foreach</tt> also accepts multiple variables:
<
puts "$x,$y"
}</
And also multiple lists:
<
puts "$i,$j"
}</
Or any combination of variables/list:
<
puts "$i,$x,$y"
}</
=={{header|Trith}}==
<
=={{header|TUSCRIPT}}==
<
week="Monday'Tuesday'Wednesday'Thursday'Friday'Saterday'Sunday"
LOOP day=week
PRINT day
ENDLOOP</
Output:
<pre>
Line 2,139 ⟶ 2,971:
To iterate any single list, you use a <code>for</code> loop.
{{works with|Bourne Shell}}
<
echo "filename is $file"
done</
If the list is in a shell parameter (like <code>PATH</code>), you adjust <code>IFS</code>.
{{works with|Bourne Shell}}
<
oldifs=$IFS
Line 2,151 ⟶ 2,983:
echo search $dir
done
IFS=$oldifs</
Some shells have real arrays. The <code>for</code> loop can also iterate these.
{{works with|Bash}}
<
for x in "${collection[@]}"; do
echo "$x"
done</
{{works with|pdksh|5.2.14}}
<
for x in "${collection[@]}"; do
echo "$x"
done</
==={{header|C Shell}}===
<
foreach x ($collection:q)
echo $x:q
end</
=={{header|V}}==
<
=={{header|
<syntaxhighlight lang="vala">List<string> things = new List<string> ();
things.append("Apple");
things.append("Banana");
things.append("Coconut");
foreach (string thing in things)
{
stdout.printf("%s\n", thing);
}</syntaxhighlight>
=={{header|Vim Script}}==
Vim Script's for-loop is actually a foreach-loop and iterates through a list.
<
echo i
endfor</
=={{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}}==
<
prn x</
=={{header|WDTE}}==
<
let s => import 'stream';
Line 2,212 ⟶ 3,042:
-> s.map (io.writeln io.stdout)
-> s.drain
;</
=={{header|Wren}}==
<syntaxhighlight lang="wren">for (f in ["apples", "oranges", "pears"]) System.print(f)</syntaxhighlight>
{{out}}
<pre>
apples
oranges
pears
</pre>
=={{header|XLISP}}==
XLISP's <tt>FOR-EACH</tt> applies a procedure to each member of a list in turn.
<
{{out}}
<pre>CYRUS
Line 2,226 ⟶ 3,066:
=={{header|XPL0}}==
Translation of C example:
<
int List, I;
[List:= ["Red", "Green", "Blue", "Black", "White"];
for I:= 0, 5-1 do
[Text(0, List(I)); CrLf(0)];
]</
=={{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.
<
<xsl:for-each select="person[@age >= 21]">
<fo:block><xsl:value-of select="position()"/>. <xsl:value-of select="@name"/></fo:block>
</xsl:for-each></
=={{header|zig}}==
<
pub fn main() void {
const items = [_]i16{ 0, 1, 1, 2, 3, 5, 8 };
for (items) |i| {
warn("{}\n", .{i});
}
}
</syntaxhighlight>
=={{header|zkl}}==
{{trans|XPL0}}
<
{ print(c," "); }</
{{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.
<
foreach x,y,z in (T(1,2,3), T(4,5), T(6)){ println(x,y,z) }</
{{out}}
<pre>
Line 2,273 ⟶ 3,114:
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}}
|