In computer science a for loop is a programming language statement which allows code to be
repeatedly executed.
A for loop is classified as an iteration statement.
The keyword used to declare a for loop is based on the heritage of the language and
the prior programming languages it borrowed from, so programming languages that are descendants
of or offshoots of a language that originally developed an iterator will often use the same
keyword to name an iterator, e.g. descendants of ALGOL will use "for", while descendants
of Fortran will use "do."
Some languages started from scratch, and didn't have a predefined term for an iterator to
choose from, which is why COBOL uses "PERFORM VARYING".
Unlike many other kinds of loops, such as the while loop, the for loop is often distinguished
by an explicit loop counter or loop variable.
This allows the body of the for loop to know about the sequencing of each iteration.
For loops are also typically used when the amount of iterations is known before entering
the loop.
For loops are the shorthand way to make loops when the number of iterations is known, as
a for loop can be written as a while loop.
The name for loop comes from the English word for, which is used as the keyword in most
programming languages to introduce a for loop.
The term in English dates to ALGOL 58 and was popularized in the influential later ALGOL
60; it is the direct translation of the earlier German für, used in Superplan by Heinz Rutishauser,
who also was involved in defining ALGOL 58 and ALGOL 60.
The loop body is executed "for" the given values of the loop variable, though this is
more explicit in the ALGOL version of the statement, in which a list of possible values
and/or increments can be specified.
In FORTRAN and PL/I though, the keyword DO is used and it is called a do loop, but it
is otherwise identical to the for loop described here and is not to be confused with the do
while loop.
Kinds of for loops A for loop statement is available in most
imperative programming languages.
Even ignoring minor differences in syntax there are many differences in how these statements
work and the level of expressiveness they support.
Generally, for loops fall into one of the following categories:
Traditional for loops The traditional for loop found in C/C++ requires
3 parts: the initialization, the condition, and the afterthought.
The initialization declares any variables required.
The condition checks a condition, and quits the loop if false.
The afterthought is performed exactly once every time the loop ends and then repeats.
Here is an example of the traditional for loop in Java 7.
Iterator-based for loops
This type of for loop is a falsification of the numeric range type of for loop; as it
allows for the enumeration of sets of items other than number sequences.
It is usually characterized by the use of an implicit or explicit iterator, in which
the loop variable takes on each of the values in a sequence or other order able data collection.
A representative example in Python is:
Where some_iterable_object is either a data collection that supports implicit iteration,
or may in fact be an iterator itself.
Some languages have this in addition to another for-loop syntax; notably, PHP has this type
of loop under the name for each, as well as a three-expression for loop under the name
for.
Vectorised for loops Some languages offer a for loop that acts
as if processing all iterations in parallel, such as the for all keyword in FORTRAN 95
which has the interpretation that all right-hand-side expressions are evaluated before any assignments
are made, as distinct from the explicit iteration form.
For example, in the for loop in the following pseudocode fragment, when calculating the
new value for A(i), except for the first the reference to A(i - 1) will obtain the new
value that had been placed there in the previous step.
In the for all version, however, each calculation refers only to the original, unaltered A.
for i:=2:N - 1 do A(i):=[A(i - 1) + A(i) + A(i + 1)]/3; next i;
for all i:=2:N - 1 do A(i):=[A(i - 1) + A(i) + A(i + 1)]/3;
The difference may be significant.
Some languages also offer array assignment statements, that enable many for-loops to
be omitted.
Thus pseudocode such as A:=0; would set all elements of array A to zero, no matter its
size or dimensionality.
The example loop could be rendered as
But whether that would be rendered in the style of the for-loop or the for all-loop
or something else may not be clearly described in the compiler manual.
Compound for loops Introduced with ALGOL 68 and followed by PL/I,
this allows the iteration of a loop to be compounded with a test, as in
for i:=1:N while A(i) > 0 do etc.
That is, a value is assigned to the loop variable i and only if the while expression is true
will the loop body be executed.
If the result were false the for-loop's execution stops short.
Granted that the loop variable's value is defined after the termination of the loop,
then the above statement will find the first non-positive element in array A, or, with
suitable variations, the first non-blank character in a string, and so on.
Additional semantics and constructs Use as infinite loops
This C-style for loop is commonly the source of an infinite loop since the fundamental
steps of iteration are completely in the control of the programmer.
In fact, when infinite loops are intended, this type of for loop can be used, such as:
This style is used instead of infinite while(1) loops to avoid a warning in Visual C++.
Early exit and continuation Some languages may also provide other supporting
statements, which when present can alter how the for loop iteration proceeds.
Common among these are the break and continue statements found in C and its derivatives.
The break statement causes the inner-most loop to be terminated immediately when executed.
The continue statement will move at once to the next iteration without further progress
through the loop body for the current iteration.
Other languages may have similar statements or otherwise provide means to alter the for
loop progress; for example in FORTRAN 95:
Loop variable scope and semantics Different languages specify different rules
for what value the loop variable will hold on termination of its loop, and indeed some
hold that it "becomes undefined".
This permits a compiler to generate code that leaves any value in the loop variable, or
perhaps even leaves it unchanged because the loop value was held in a register and never
stored to memory.
Actual behaviour may even vary according to the compiler's optimisation settings, as with
the Honywell Fortran66 compiler.
In some languages the loop variable is immutable within the scope of the loop body, with any
attempt to modify its value being regarded as a semantic error.
Such modifications are sometimes a consequence of a programmer error, which can be very difficult
to identify once made.
However only overt changes are likely to be detected by the compiler.
Situations where the address of the loop variable is passed as an argument to a subroutine make
it very difficult to check, because the routine's behavior is in general unknowable to the compiler.
Some examples in the style of Fortran:
A common approach is to calculate the iteration count at the start of a loop and with each
iteration decrement this count while also adjusting the value of I: double counting
results.
However, adjustments to the value of I within the loop will not change the number of iterations
executed.
Still another possibility is that the code generated may employ an auxiliary variable
as the loop variable, possibly held in a machine register, whose value may or may not be copied
to I on each iteration.
Again, modifications of I would not affect the control of the loop, but now a disjunction
is possible: within the loop, references to the value of I might be to the current value
of I or to the auxiliary variable and confusing results are guaranteed.
For instance, within the loop a reference to element I of an array would likely employ
the auxiliary variable, but if I is a parameter to some routine, it would likely be a reference
to the proper variable I instead.
It is best to avoid such possibilities.
List of value ranges PL/I and Algol 68, allows loops in which the
loop variable is iterated over a list of ranges of values instead of a single range.
The following PL/I example will execute the loop with six values of i: 1, 7, 12, 13, 14,
15:
Equivalence with while loops A for loop can be converted into an equivalent
while loop by incrementing a counter variable directly.
The following pseudocode illustrates this technique:
factorial = 1 for counter from 1 to 5
factorial = factorial * counter
is easily translated into the following while loop:
factorial = 1 counter = 1
while counter <= 5 factorial = factorial * counter
counter = counter + 1
This translation is slightly complicated by languages which allow a statement to jump
to the next iteration of the loop.
These statements will typically implicitly increment the counter of a for loop, but not
the equivalent while loop.
Any translation will have to place all such statements within a block that increments
the explicit counter before running the statement.
Syntax Given an action that must be repeated, for
instance, five times, different languages' for loops will be written differently.
The syntax for a three-expression for loop is nearly identical in all languages that
have it, after accounting for different styles of block termination and so on.
ActionScript 3
Ada
The exit statement may be used to exit the loop.
Loops can be labeled, and exit may leave a specific labeled loop in a group of nested
loops:
AppleScript
You can also iterate through a list of items, similar to what you can do with arrays in
other languages:
You may also use "exit repeat" to exit a loop at any time.
Unlike other languages, AppleScript does not currently have any command to continue to
the next iteration of the loop.
Bash
Note that an empty loop is a syntax error.
If the above loops contained only comments, execution would result in the message "syntax
error near unexpected token 'done'".
BASIC
Notice that the end-loop marker specifies the name of the index variable, which must
correspond to the name of the index variable in the start of the for loop.
Some languages allow a statement label on the start of a for loop that can be matched
by the compiler against the same text on the corresponding end loop statement.
Fortran also allows the EXIT and CYCLE statements to name this text; in a nest of loops this
makes clear which loop is intended.
However, in these languages the labels must be unique, so successive loops involving the
same index variable cannot use the same text nor can a label be the same as the name of
a variable, such as the index variable for the loop.
C/C++
The statement is often a block statement; an example of this would be:
The ISO/IEC 9899:1999 publication also allows initial declarations in for loops.
CFML Script syntax
Simple index loop:
Using an array:
Using a "list" of string values:
The above "list" example is only available in Railo's dialect of CFML.
Tag syntax Simple index loop:
Using an array:
Using a "list" of string values:
FORTRAN While using the keyword do instead of for,
this type of FORTRAN do loop behaves similarly to the three argument for loop in other languages.
This example behaves the same as the others, initializing the counter variable to 1, incrementing
by 1 each iteration of the loop and stopping at five.
Haskell The built-in imperative forM_ maps a monadic
expression into a list, as
or get each iteration result as a list in
But, if you want to save the space of the [1..5] list, a more authentic monadic forLoop_
construction can be defined as
and used as:
Java
For the extended for loop, see Foreach loop JavaScript
JavaScript supports C-style "three-expression" loops.
The break and continue statements are supported inside loops.
Alternatively, it is possible to iterate over all keys of an array.
Lua
So, this code
will print:
For loops can also loop through a table using
to iterate numerically through arrays and
to iterate randomly through dictionaries.
Generic for-loop making use of closures:
Mathematica The construct corresponding to most other
languages' for loop is called Do in Mathematica
Mathematica also has a For construct that mimics the for loop of C-like languages
MATLAB
Maxima CAS In Maxima CAS one can use also non integer
values :
Oberon-2, Oberon-07, or Component Pascal
Note that in the original Oberon language the for loop was omitted in favor of the more
general Oberon loop construct.
The for loop was reintroduced in Oberon-2.
OCaml See expression syntax.
Pascal
Decrementing is using 'downto' keyword instead of 'to', as in:
The numeric-range for loop varies somewhat more.
Perl
(Note that "there's more than one way to do it" is a Perl programming motto.)
PHP
PL/I
The LEAVE statement may be used to exit the loop.
Loops can be labeled, and leave may leave a specific labeled loop in a group of nested
loops.
Some PL/I dialects include the ITERATE statement to terminate the current loop iteration and
begin the next.
PostScript PostScript supports a very simple kind of
for loop.
The repeat loop, written as X { ... } repeat, repeats the body exactly X times.
Python
Ruby
Ruby has several possible syntaxes, including the above samples.
Smalltalk
Contrary to other languages, in Smalltalk a for loop is not a language construct but
defined in the class Number as a method with two parameters, the end value and a closure,
using self as start value.
Timeline of the for loop in various programming languages
1957: FORTRAN Fortran's equivalent of the for loop is the
DO loop.
The syntax of Fortran's DO loop is:
Where the step part may be omitted if the step is one.
Example:
1958: Algol Algol was first formalised in the Algol58
report.
1960: COBOL COBOL was formalised in late 1959 and has
had many elaborations.
It uses the PERFORM verb which has many options, with the later addition of "structured" statements
such as END-PERFORM.
Ignoring the need for declaring and initialising variables, the equivalent of a for-loop would
be
If the PERFORM verb has the optional clause TEST AFTER, the resulting loop is slightly
different: the loop body is executed at least once, before any test.
1968: Algol 68 Algol68 has what was considered the universal
loop, the full syntax is:
Further, the single iteration range could be replaced by a list of such ranges.
There are several unusual aspects of the construct only the "do ~ od" portion was compulsory,
in which case the loop will iterate indefinitely.
thus the clause "to 100 do ~ od", will iterate exactly 100 times.
the "while" syntactic element allowed a programmer to break from a "for" loop early, as in:
Subsequent extensions to the standard Algol68 allowed the "to" syntactic element to be replaced
with "upto" and "downto" to achieve a small optimization.
The same compilers also incorporated: until - for late loop termination.
foreach - for working on arrays in parallel.
1983: Ada 83 and above
Implementation in Interpreted Programming Languages
In interpreted programming languages, for loops can be implemented in many ways.
Oftentimes, the for loops are directly translated to assembly-like compare instructions and
conditional jump instructions.
However, this is not always so.
In some interpreted programming languages, for loops are simply translated to while loops.
For instance, take the following Mint/Horchata code:
See also Do while loop
Foreach Loop counter
While loop References
External links For loop implementation in different languages
at Wikia:Code