Foreach loop

Last updated
.mw-parser-output .monospaced{font-family:monospace,monospace}
foreach loops are almost always used to iterate over items in a sequence of elements. For-Loop-Mint-Programming-Language-Type-2.gif
foreach loops are almost always used to iterate over items in a sequence of elements.

In computer programming, foreach loop (or for-each loop) is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops [1] usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

Contents

The foreach statement in some languages has some defined order, processing each item in the collection from the first to the last. The foreach statement in many other languages, especially array programming languages, does not have any particular order. This simplifies loop optimization in general and in particular allows vector processing of items in the collection concurrently.

Syntax

Syntax varies among languages. Most use the simple word for, roughly as follows:

for each item in collection:   do something to item

Language support

Programming languages which support foreach loops include ABC, ActionScript, Ada, C++11, C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), Delphi, ECMAScript, Erlang, Java (since 1.5), JavaScript, Lua, Objective-C (since 2.0), ParaSail, Perl, PHP, Prolog, [2] Python, R, REALbasic, Rebol, [3] Red, [4] Ruby, Scala, Smalltalk, Swift, Tcl, tcsh, Unix shells, Visual Basic .NET, and Windows PowerShell. Notable languages without foreach are C, and C++ pre-C++11.

ActionScript 3.0

ActionScript supports the ECMAScript 4.0 Standard [5] for for each .. in [6] which pulls the value at each index.

varfoo:Object={"apple":1,"orange":2};foreach(varvalue:intinfoo){trace(value);}// returns "1" then "2"

It also supports for .. in [7] which pulls the key at each index.

for(varkey:Stringinfoo){trace(key);}// returns "apple" then "orange"

Ada

Ada supports foreach loops as part of the normal for loop. Say X is an array:

forIinX'RangeloopX(I):=Get_Next_Element;endloop;

This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed.

Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...):

forObjofXloop-- Work on Objendloop;

C

The C language does not have collections or a foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a macro.

However, two obvious problems occur:

C string as a collection of char

#include<stdio.h>/* foreach macro viewing a string as a collection of char values */#define foreach(ptrvar, strvar) \char* ptrvar; \for (ptrvar = strvar; (*ptrvar) != '\0'; *ptrvar++)intmain(intargc,char**argv){char*s1="abcdefg";char*s2="123456789";foreach(p1,s1){printf("loop 1: %c\n",*p1);}foreach(p2,s2){printf("loop 2: %c\n",*p2);}return0;}

C int array as a collection of int (array size known at compile-time)

#include<stdio.h>/* foreach macro viewing an array of int values as a collection of int values */#define foreach(intpvar, intarr) \int* intpvar; \for (intpvar = intarr; intpvar < (intarr + (sizeof(intarr)/sizeof(intarr[0]))); ++intpvar)intmain(intargc,char**argv){inta1[]={1,1,2,3,5,8};inta2[]={3,1,4,1,5,9};foreach(p1,a1){printf("loop 1: %d\n",*p1);}foreach(p2,a2){printf("loop 2: %d\n",*p2);}return0;}

Most general: string or array as collection (collection size known at run-time)

Note: idxtype can be removed and typeof(col[0]) used in its place with GCC
#include<stdio.h>#include<string.h>/* foreach macro viewing an array of given type as a collection of values of given type */#define arraylen(arr) (sizeof(arr)/sizeof(arr[0]))#define foreach(idxtype, idxpvar, col, colsiz) \idxtype* idxpvar; \for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar)intmain(intargc,char**argv){char*c1="collection";intc2[]={3,1,4,1,5,9};double*c3;intc3len=4;c3=(double*)calloc(c3len,sizeof(double));c3[0]=1.2;c3[1]=3.4;c3[2]=5.6;c3[3]=7.8;foreach(char,p1,c1,strlen(c1)){printf("loop 1: %c\n",*p1);}foreach(int,p2,c2,arraylen(c2)){printf("loop 2: %d\n",*p2);}foreach(double,p3,c3,c3len){printf("loop 3: %.1lf\n",*p3);}return0;}

C#

In C#, assuming that myArray is an array of integers:

foreach(intxinmyArray){Console.WriteLine(x);}

Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression:

myArray.ToList().ForEach(x=>Console.WriteLine(x));

C++

C++11 provides a foreach loop. The syntax is similar to that of Java:

#include<iostream>intmain(){intmyint[]={1,2,3,4,5};for(inti:myint){std::cout<<i<<'\n';}}

C++11 range-based for statements have been implemented in GNU Compiler Collection (GCC) (since version 4.6), Clang (since version 3.0) and Visual C++ 2012 (version 11 [8] )

The range-based for is syntactic sugar equivalent to:

for(auto__anon=begin(myint);__anon!=end(myint);++__anon){autoi=*__anon;std::cout<<i<<'\n';}

The compiler uses argument-dependent lookup to resolve the begin and end functions. [9]

The C++ Standard Library also supports for_each, [10] that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the beginning to the end, the range and direction you can change the direction or range by altering the first two parameters.

#include<iostream>#include<algorithm> // contains std::for_each#include<vector>intmain(){std::vector<int>v{1,2,3,4,5};std::for_each(v.begin(),v.end(),[](inti){std::cout<<i<<'\n';});std::cout<<"reversed but skip 2 elements:\n";std::for_each(v.rbegin()+2,v.rend(),[](inti){std::cout<<i<<'\n';});}

Qt, a C++ framework, offers a macro providing foreach loops [11] using the STL iterator interface:

#include<QList>#include<QDebug>intmain(){QList<int>list;list<<1<<2<<3<<4<<5;foreach(inti,list){qDebug()<<i;}}

Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops: [12]

#include<boost/foreach.hpp>#include<iostream>intmain(){intmyint[]={1,2,3,4,5};BOOST_FOREACH(int&i,myint){std::cout<<i<<'\n';}}

C++/CLI

The C++/CLI language proposes a construct similar to C#.

Assuming that myArray is an array of integers:

foreach(intxinmyArray){Console::WriteLine(x);}

ColdFusion Markup Language (CFML)

Script syntax

// arraysarrayeach([1,2,3,4,5],function(v){writeOutput(v);});// orfor(vin[1,2,3,4,5]){writeOutput(v);}// or// (Railo only; not supported in ColdFusion)letters=["a","b","c","d","e"];letters.each(function(v){writeOutput(v);// abcde});// structsfor(kincollection){writeOutput(collection[k]);}// orstructEach(collection,function(k,v){writeOutput("key: #k#, value: #v#;");});// or// (Railo only; not supported in ColdFusion)collection.each(function(k,v){writeOutput("key: #k#, value: #v#;");});

Tag syntax

<!--- arrays ---><cfloopindex="v"array="#['a','b','c','d','e']#"><cfoutput>#v#</cfoutput><!--- a b c d e  ---></cfloop>

CFML incorrectly identifies the value as "index" in this construct; the index variable does receive the actual value of the array element, not its index.

<!--- structs ---><cfloopitem="k"collection="#collection#"><cfoutput>#collection[k]#</cfoutput></cfloop>

Common Lisp

Common Lisp provides foreach ability either with the dolist macro:

(dolist(i'(13568101417))(printi))

or the powerful loop macro to iterate on more data types

(loopforiin'(13568101417)do(printi))

and even with the mapcar function:

(mapcar#'print'(13568101417))

D

foreach(item;set){// do something to item}

or

foreach(argument){// pass value}

Dart

for(finalelementinsomeCollection){// do something with element}

Object Pascal, Delphi

Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section.

forenumeratorincollectiondobegin//do something hereend;

Eiffel

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

In this example, every element of the structure my_list is printed:

acrossmy_listasicloopprint(ic.item)end

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

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

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

acrossmy_listasicallic.item.count>3end

The following is true if at least one item has a count greater than three:

acrossmy_listasicsomeic.item.count>3end

Go

Go's foreach loop can be used to loop over an array, slice, string, map, or channel.

Using the two-value form, we get the index/key (first element) and the value (second element):

forindex,value:=rangesomeCollection{// Do something to index and value}

Using the one-value form, we get the index/key (first element):

forindex:=rangesomeCollection{// Do something to index}

[13]

Groovy

Groovy supports for loops over collections like arrays, lists and ranges:

defx=[1,2,3,4]for(vinx)// loop over the 4-element array x{printlnv}for(vin[1,2,3,4])// loop over 4-element literal list {printlnv}for(vin1..4)// loop over the range 1..4{printlnv}

Groovy also supports a C-style for loop with an array index:

for(i=0;i<x.size();i++){printlnx[i]}

Collections in Groovy can also be iterated over using the each keyword and a closure. By default, the loop dummy is named it

x.each{printlnit}// print every element of the x arrayx.each{i->printlni}// equivalent to line above, only loop dummy explicitly named "i"

Haskell

Haskell allows looping over lists with monadic actions using mapM_ and forM_ (mapM_ with its arguments flipped) from Control.Monad:

codeprints
mapM_print[1..4]
1 2 3 4
forM_"test"$\char->doputCharcharputCharchar
tteesstt

It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that is traversable using traverse (for with its arguments flipped) and mapM (forM with its arguments flipped) from Data.Traversable.

Haxe

for(valueiniterable){trace(value);}Lambda.iter(iterable,function(value)trace(value));

Java

In Java, a foreach-construct was introduced in Java Development Kit (JDK) 1.5.0. [14]

Official sources use several names for the construct. It is referred to as the "Enhanced for Loop", [14] the "For-Each Loop", [15] and the "foreach statement". [16] [17] :264

for(Typeitem:iterableCollection){// Do something to item}

Java also provides the stream api since java 8: [17] :294–203

List<Integer>intList=List.of(1,2,3,4);intList.stream().forEach(i->System.out.println(i));

JavaScript

The ECMAScript 6 standard has for..of for index-less iteration over generators, arrays and more:

for(varitemofarray){// Do stuff}

Alternatively, function-based style: [18]

array.forEach(item=>{// Do stuff})

For unordered iteration over the keys in an Object, JavaScript features the for...in loop:

for(varkeyinobject){// Do stuff with object[key]}

To limit the iteration to the object's own properties, excluding those inherited through the prototype chain, it is sometimes useful to add a hasOwnProperty() test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later").

for(varkeyinobject){if(object.hasOwnProperty(key)){// Do stuff with object[key]}}

ECMAScript 5 provided Object.keys method, to transfer the own keys of an object into array. [19]

varbook={name:"A Christmas Carol",author:"Charles Dickens"};for(varkeyofObject.keys(book)){alert("PropertyName = "key+" Property Value = "+book[key]);}

Lua

Source: [20]

Iterate only through numerical index values:

forindex,valueinipairs(array)do-- do somethingend

Iterate through all index values:

forindex,valueinpairs(array)do-- do somethingend

Mathematica

In Mathematica, Do will simply evaluate an expression for each element of a list, without returning any value.

In[]:=Do[doSomethingWithItem,{item,list}]

It is more common to use Table, which returns the result of each evaluation in a new list.

In[]:=list={3,4,5};In[]:=Table[item^2,{item,list}]Out[]={9,16,25}

MATLAB

foritem=array%do somethingend

Mint

For each loops are supported in Mint, possessing the following syntax:

foreachelementoflist/* 'Do something.' */end

The for (;;) or while (true) infinite loop in Mint can be written using a for each loop and an infinitely long list. [21]

importtype/* 'This function is mapped to' * 'each index number i of the' * 'infinitely long list.' */subidentity(x)returnxend/* 'The following creates the list' * '[0, 1, 2, 3, 4, 5, ..., infinity]' */infiniteList=list(identity)foreachelementofinfiniteList/* 'Do something forever.' */end

Objective-C

Foreach loops, called Fast enumeration, are supported starting in Objective-C 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc.

NSArray*a=[NSArraynew];// Any container class can be substitutedfor(idobjina){// Note the dynamic typing (we do not need to know the// Type of object stored in 'a'.  In fact, there can be// many different types of object in the array.printf("%s\n",[[objdescription]UTF8String]);// Must use UTF8String with %sNSLog(@"%@",obj);// Leave as an object}

NSArrays can also broadcast a message to their members:

NSArray*a=[NSArraynew];[amakeObjectsPerformSelector:@selector(printDescription)];

Where blocks are available, an NSArray can automatically perform a block on every contained item:

[myArrayenumerateObjectsUsingBlock:^(idobj,NSUIntegeridx,BOOL*stop){NSLog(@"obj %@",obj);if([objshouldStopIterationNow])*stop=YES;}];

The type of collection being iterated will dictate the item returned with each iteration. For example:

NSDictionary*d=[NSDictionarynew];for(idkeyind){NSObject*obj=[dobjectForKey:key];// We use the (unique) key to access the (possibly nonunique) object.NSLog(@"%@",obj);}

OCaml

OCaml is a functional programming language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays.

For lists:

List.iter(funx->print_intx)[1;2;3;4];;

or in short way:

List.iterprint_int[1;2;3;4];;

For arrays:

Array.iter(funx->print_intx)[|1;2;3;4|];;

or in short way:

Array.iterprint_int[|1;2;3;4|];;

ParaSail

The ParaSail parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container:

varCon:Container<Element_Type>:=...// ...foreachElemofConconcurrentloop// loop may also be "forward" or "reverse" or unordered (the default)// ... do something with Elemendloop

ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set":

varMy_Map:Map<Key_Type=>Univ_String,Value_Type=>Tree<Integer>>:=...constMy_Set:Set<Univ_String>:=["abc","def","ghi"];foreach[Str=>Tr]ofMy_Map{StrinMy_Set}forwardloop// ... do something with Str or Trendloop

Pascal

In Pascal, ISO standard 10206:1990 introduced iteration over set types, thus:

varelt:ElementType;eltset:setofElementType;{...}foreltineltsetdo{ ... do something with elt }

Perl

In Perl, foreach (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable.

List literal example:

foreach(1,2,3,4){print$_;}

Array examples:

foreach(@arr){print$_;}
foreach$x(@arr){#$x is the element in @arrprint$x;}

Hash example:

foreach$x(keys%hash){print$x." = ".$hash{$x};# $x is a key in %hash and $hash{$x} is its value}

Direct modification of collection members:

@arr=('remove-foo','remove-bar');foreach$x(@arr){$x=~s/remove-//;}# Now @arr = ('foo', 'bar');

PHP

foreach($setas$value){// Do something to $value;}

It is also possible to extract both keys and values using the alternate syntax:

foreach($setas$key=>$value){echo"{$key} has a value of {$value}";}

Direct modification of collection members:

$arr=array(1,2,3);foreach($arras&$value){// Note the &, $value is a reference to the original value inside $arr$value++;}// Now $arr = array(2, 3, 4);// also works with the full syntaxforeach($arras$key=>&$value){$value++;}

Python

foriteminiterable_collection:# Do something with item

Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in associative arrays:

forkey,valueinsome_dict.items():# Direct iteration on a dict iterates on its keys# Do stuff

As for ... in is the only kind of for loop in Python, the equivalent to the "counter" loop found in other languages is...

foriinrange(len(seq)):# Do something to seq[i]

... though using the enumerate function is considered more "Pythonic":

fori,iteminenumerate(seq):# Do stuff with item# Possibly assign it back to seq[i]

R

for (iteminobject){# Do something with item}

As for ... in is the only kind of for loop in R, the equivalent to the "counter" loop found in other languages is...

for (iinseq_along(object)){# Do something with object[[i]]}

Racket

(for([itemset])(do-something-withitem))

or using the conventional Scheme for-each function:

(for-eachdo-something-witha-list)

do-something-with is a one-argument function.

Raku

In Raku, a sister language to Perl, for must be used to traverse elements of a list (foreach is not allowed). The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s).

List literal example:

for1..4 {     .say; } 

Array examples:

for@arr {     .say; } 

The for loop in its statement modifier form:

.sayfor@arr; 
for@arr -> $x {     say$x; } 
for@arr -> $x, $y {    # more than one item at a timesay"$x, $y"; } 

Hash example:

forkeys%hash -> $key {     say"$key: $hash{$key}"; } 

or

for%hash.kv -> $key, $value {     say"$key: $value"; } 

or

for%hash -> $x {     say"$x.key(): $x.value()";    # Parentheses needed to inline in double quoted string } 


Direct modification of collection members with a doubly pointy block, <->:

my@arr = 1,2,3; for@arr <-> $x {     $x *= 2; } # Now @arr = 2,4,6;

Ruby

set.eachdo|item|# do something to itemend

or

foriteminset# do something to itemend

This can also be used with a hash.

set.eachdo|key,value|# do something to key# do something to valueend

Rust

The for loop has the structure for<pattern>in<expression>{/* optional statements */}. It implicitly calls the IntoIterator::into_iter method on the expression, and uses the resulting value, which must implement the Iterator trait. If the expression is itself an iterator, it is used directly by the for loop through an implementation of IntoIterator for all Iterators that returns the iterator unchanged. The loop calls the Iterator::next method on the iterator before executing the loop body. If Iterator::next returns Some(_) , the value inside is assigned to the pattern and the loop body is executed; if it returns None, the loop is terminated.

letmutnumbers=vec![1,2,3];// Immutable reference:fornumberin&numbers{// calls IntoIterator::into_iter(&numbers)println!("{}",number);}forsquareinnumbers.iter().map(|x|x*x){// numbers.iter().map(|x| x * x) implements Iteratorprintln!("{}",square);}// Mutable reference:fornumberin&mutnumbers{// calls IntoIterator::into_iter(&mut numbers)*number*=2;}// prints "[2, 4, 6]":println!("{:?}",numbers);// Consumes the Vec and creates an Iterator:fornumberinnumbers{// calls IntoIterator::into_iter(numbers)// ...}// Errors with "borrow of moved value":// println!("{:?}", numbers);

Scala

// return list of modified elementsitemsmap{x=>doSomething(x)}itemsmapmultiplyByTwofor{x<-items}yielddoSomething(x)for{x<-items}yieldmultiplyByTwo(x)// return nothing, just perform actionitemsforeach{x=>doSomething(x)}itemsforeachprintlnfor{x<-items}doSomething(x)for{x<-items}println(x)// pattern matching example in for-comprehensionfor((key,value)<-someMap)println(s"$key -> $value")

Scheme

(for-eachdo-something-witha-list)

do-something-with is a one-argument function.

Smalltalk

collectiondo: [:item|"do something to item" ] 

Swift

Swift uses the forin construct to iterate over members of a collection. [22]

forthinginsomeCollection{// do something with thing}

The forin loop is often used with the closed and half-open range constructs to iterate over the loop body a certain number of times.

foriin0..<10{// 0..<10 constructs a half-open range, so the loop body// is repeated for i = 0, i = 1, …, i = 9.}foriin0...10{// 0...10 constructs a closed range, so the loop body// is repeated for i = 0, i = 1, …, i = 9, i = 10.}

SystemVerilog

SystemVerilog supports iteration over any vector or array type of any dimensionality using the foreach keyword.

A trivial example iterates over an array of integers:

codeprints
intarray_1d[]='{3,2,1,0};foreacharray_1d[index]$display("array_1d[%0d]: %0d",index,array_1d[index]);
array_1d[0]: 3 array_1d[1]: 2 array_1d[2]: 1 array_1d[3]: 0

A more complex example iterates over an associative array of arrays of integers:

codeprints
intarray_2d[string][]='{"tens":'{10,11},"twenties":'{20,21}};foreacharray_2d[key,index]$display("array_2d[%s,%0d]: %0d",key,index,array_2d[key,index]);
array_2d[tens,0]: 10 array_2d[tens,1]: 11 array_2d[twenties,0]: 20 array_2d[twenties,1]: 21

Tcl

Tcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list.

codeprints
foreach{ij}{123456}{puts"$i $j"}
1 2 3 4 5 6

It is also possible to iterate over more than one list simultaneously. In the following i assumes sequential values of the first list, j sequential values of the second list:

codeprints
foreachi{123}j{abc}{puts"$i $j"}
1 a 2 b 3 c

Visual Basic .NET

ForEachitemInenumerable' Do something with item.Next

or without type inference

ForEachitemAstypeInenumerable' Do something with item.Next

Windows

Conventional command processor

Invoke a hypothetical frob command three times, giving it a color name each time.

C:\>FOR%%a IN( red green blue )DO frob %%a 

Windows PowerShell

foreach($itemin$set){# Do something to $item}

From a pipeline

$list|ForEach-Object{Write-Host$_}# or using the aliases$list|foreach{write $_}$list|%{write $_}

XSLT

<xsl:for-eachselect="set"><!-- do something for the elements in <set> --></xsl:for-each>

[23]

See also

Related Research Articles

In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an expression until its value is needed and which also avoids repeated evaluations.

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

Generic programming is a style of computer programming in which algorithms are written in terms of data types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. This approach, pioneered by the ML programming language in 1973, permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplicate code.

In computer programming, an iterator is an object that enables a programmer to traverse a container, particularly lists. Various types of iterators are often provided via a container's interface. Though the interface and semantics of a given iterator are fixed, iterators are often implemented in terms of the structures underlying a container implementation and are often tightly coupled to the container to enable the operational semantics of the iterator. An iterator performs traversal and also gives access to data elements in a container, but does not itself perform iteration.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

<span class="mw-page-title-main">D (programming language)</span> Multi-paradigm system programming language

D, also known as dlang, is a multi-paradigm system programming language created by Walter Bright at Digital Mars and released in 2001. Andrei Alexandrescu joined the design and development effort in 2007. Though it originated as a re-engineering of C++, D is now a very different language drawing inspiration from other high-level programming languages, notably Java, Python, Ruby, C#, and Eiffel.

<span class="mw-page-title-main">For loop</span> Control flow statement for repeated execution

In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.

In computing, aliasing describes a situation in which a data location in memory can be accessed through different symbolic names in the program. Thus, modifying the data through one name implicitly modifies the values associated with all aliased names, which may not be expected by the programmer. As a result, aliasing makes it particularly difficult to understand, analyze and optimize programs. Aliasing analysers intend to make and compute useful information for understanding aliasing in programs.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.

In computer programming, a sentinel value is a special value in the context of an algorithm which uses its presence as a condition of termination, typically in a loop or recursive algorithm.

C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases.

This article describes the syntax of the C# programming language. The features described are compatible with .NET Framework and Mono.

This Comparison of programming languages (associative arrays) compares the features of associative array data structures or array-lookup processing for over 40 computer programming languages.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

In C++, associative containers refer to a group of class templates in the standard library of the C++ programming language that implement ordered associative arrays. Being templates, they can be used to store arbitrary elements, such as integers or custom classes. The following containers are defined in the current revision of the C++ standard: set, map, multiset, multimap. Each of these containers differ only on constraints placed on their elements.

References

  1. "D Programming Language foreach Statement Documentation". Digital Mars. Retrieved 2008-08-04.
  2. "SWI-Prolog -- foreach/2". www.swi-prolog.org. Retrieved 2020-02-10.
  3. http://www.rebol.com.{{cite web}}: Missing or empty |title= (help)
  4. http://www.red-lang.org.{{cite web}}: Missing or empty |title= (help)
  5. "Proposed ECMAScript 4th Edition – Language Overview" (PDF). Retrieved 2020-02-21.
  6. "for each..in" . Retrieved 2020-02-21.
  7. "for..in" . Retrieved 2020-02-21.
  8. "C++11 Features in Visual C++ 11 - Visual C++ Team Blog - Site Home - MSDN Blogs". Blogs.msdn.com. 2011-09-12. Retrieved 2013-08-04.
  9. "Range-based for loop (since C++11)". en.cppreference.com. Retrieved 2018-12-03.
  10. "std::for_each - cppreference". en.cppreference.com. Retrieved 2017-09-30.
  11. "Qt 4.2: Generic Containers". Doc.qt.digia.com. Archived from the original on 2015-11-23. Retrieved 2013-08-04.
  12. Eric Niebler (2013-01-31). "Chapter 9. Boost.Foreach - 1.53.0". Boost.org. Retrieved 2013-08-04.
  13. "Range Clause". The Go Programming Language Specification. The Go Programming Language. Retrieved October 20, 2013.
  14. 1 2 "Enhanced for Loop - This new language construct[...]" "Java Programming Language, Section: Enhancements in JDK 5". Sun Microsystems, Inc. 2004. Retrieved 2009-05-26.
  15. "The For-Each Loop" "The For-Each Loop". Sun Microsystems, Inc. 2008. Retrieved 2009-05-10.
  16. "Implementing this interface allows an object to be the target of the "foreach" statement." "Iterable (Java Platform SE 6)". Sun Microsystems, Inc. 2004. Retrieved 2009-05-12.
  17. 1 2 Bloch, Joshua (2018). "Effective Java: Programming Language Guide" (third ed.). Addison-Wesley. ISBN   978-0134685991.
  18. "Array.prototype.forEach() - JavaScript | MDN". 16 December 2023.
  19. "Object.keys". Mozilla Developer Network. Retrieved May 7, 2014.
  20. "Lua Programming/Tables - Wikibooks, open books for an open world". en.wikibooks.org. Retrieved 2017-12-06.
  21. Chu, Oliver. "Mint Tutorial" . Retrieved 20 October 2013.
  22. "Control Flow — the Swift Programming Language (Swift 5.5)".
  23. "XSLT <xsl:for-each> Element". W3Schools.com.