Jump to content

For loop: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
No edit summary
 
(342 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
{{Short description|Control flow statement for repeated execution}}
[[File:For-loop-diagram.png|thumb|right|For loop flow diagram]]
[[File:For loop example.svg|thumb|right|Flow diagram of the following for loop code:
{{Helpbox <!-- NOTE: Please don't remove. Discuss naviagation concept at [[Talk:Do_while_loop#Helpbox_experiment] -->
<syntaxhighlight lang="c">
|name = Loop Constructs
for (i = 0; i < 5; i++)
|list1 = [[Do while loop|Do-While loop]]
printf("*");
|list2 = [[While loop]]
</syntaxhighlight>
|list3 = For loop
|list4 = [[Foreach loop|For-Each loop]]
|list5 = [[Infinite loop]]
|list6 = [[Control flow]]
}}


The loop will cause five asterisks to be printed.]]
In [[computer science]] a '''for-loop''' (or simply '''for loop''') is a [[programming language]] [[control statement|control]] [[statement (programming)|statement]] for specifying [[iteration]], which allows code to be [[execution (computers)|executed]] repeatedly. The syntax of 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 provided an iterator will often use the same keyword to name an iterator, e.g., descendants of [[ALGOL]] use "for", while descendants of [[Fortran]] use "do." There are other possibilities, for example [[COBOL]] which uses "PERFORM VARYING".
{{Loop constructs}}<!-- DO NOT remove. Discuss navigation concept at [[Talk:Do while loop#Helpbox experiment]] -->


In [[computer science]], a '''for-loop''' or '''for loop''' is a [[control flow]] [[Statement (computer science)|statement]] for specifying [[iteration]]. Specifically, a for-loop functions by running a section of code repeatedly until a certain condition has been satisfied.
Unlike many other kinds of [[Control flow#Loops|loops]], such as the [[while loop|while-loop]], the for-loop is often distinguished by an explicit [[loop counter]] or loop variable. This allows the body of the for-loop (the code that is being repeatedly executed) to know about the sequencing of each iteration. For-loops are also typically used when the number 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.


For-loops have two parts: a header and a body. The header defines the iteration and the body is the code executed once per iteration. The header often declares an explicit [[For loop#Loop counters|loop counter]] or loop [[Variable (computer science)|variable]]. This allows the body to know which iteration is being executed. For-loops are typically used when the number of iterations is known before entering the loop. For-loops can be thought of as shorthands for [[while-loop]]s which increment and test a loop variable.
The name ''for-loop'' comes from the English word [[Wiktionary:for|for]], which is used as the [[Keyword (computing)|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 '''[[wikt:für|für]]''', used in ''[[Superplan]]'' (1949–1951) 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.


Various keywords are used to indicate the usage of a for loop: descendants of [[ALGOL]] use "{{mono|for}}", while descendants of [[Fortran]] use "{{mono|do}}". There are other possibilities, for example [[COBOL]] which uses {{nowrap|{{code|PERFORM VARYING}}}}.
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|do-while loop]].


The name ''for-loop'' comes from the word [[Wiktionary: for|for]]. ''For'' is used as the [[reserved word]] (or keyword) in many programming languages to introduce a for-loop. The term in English dates to [[ALGOL 58]] and was popularized in [[ALGOL 60]]. It is the direct translation of the earlier German {{Wikt-lang|de|für}} and was used in [[Superplan]] (1949–1951) by [[Heinz Rutishauser]]. Rutishauser was involved in defining ALGOL 58 and ALGOL 60.<ref>{{Cite book |last=Wirth |first=Niklaus |author-link=Niklaus Wirth |year=1973 |chapter=Preface |title=Systematic Programming: An Introduction |pages=xiii |publisher=Prentice-Hall |isbn=0138803692}}</ref> The loop body is executed "for" the given values of the loop variable. This is more explicit in [[ALGOL]] versions of the for statement where a list of possible values and increments can be specified.
== 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:


In Fortran and [[PL/I]], the keyword {{mono|DO}} is used for the same thing and it is named a ''do-loop''; this is different from a ''[[do while loop]]''.
=== Traditional for-loops ===
The traditional for-loop found in [[C (programming language)|C]]/[[C++]] requires 3 parts: the [[Declaration (computer programming)|initialization]], the [[Boolean algebra|condition]], and the [[Code cleanup|afterthought]] and all these three parts are optional.<ref>{{cite web|url=https://www.tutorialcup.com/cplusplus/for-loop.htm|title=C++ For Loop}}</ref><ref>{{cite web|url=http://www.learncpp.com/cpp-tutorial/57-for-statements/|title=For loops in C++}}</ref>
<source Lang="java">
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Code for the for-loop's body goes here.
}
</source>


==FOR==
The initialization declares (and perhaps assigns to) any variables required. The type of a variable should be same if you are using multiple variables in initialization part. 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.
[[File:For loop.svg|thumb|350px|For loop illustration, from i=0 to i=2, resulting in data1=200]]
A for-loop statement is available in most [[imperative programming]] languages. Even ignoring minor differences in [[Syntax (programming languages)|syntax]], there are many differences in how these statements work and the level of expressiveness they support. Generally, for-loops fall into one of four categories:


===Traditional for-loops===
Here is an example of the traditional for-loop in [[Java (programming language)|Java]].
The for-loop of languages like [[ALGOL]], [[Simula]], [[BASIC]], [[Pascal (programming language)|Pascal]], [[Modula]], [[Oberon (programming language)|Oberon]], [[Ada (programming language)|Ada]], [[MATLAB]], [[OCaml]], [[F Sharp (programming language)|F#]], and so on, requires a [[Control flow|control variable]] with start- and end-values, which looks something like this:
<syntaxhighlight Lang="pascal">
for i = first to last do statement
(* or just *)
for i = first..last do statement
</syntaxhighlight>
Depending on the language, an explicit [[Assignment (computer science)|assignment]] sign may be used in place of the [[equal sign]] (and some languages require the word {{code|int}} even in the numerical case). An optional step-value (an increment or decrement ≠ 1) may also be included, although the exact syntaxes used for this differ a bit more between the languages. Some languages require a separate declaration of the control variable, some do not.


Another form was popularized by the [[C (programming language)|C language]]. It requires 3 parts: the [[Declaration (computer programming)|initialization]] ([[loop variant]]), the [[Boolean algebra|condition]], and the advancement to the next iteration. All these three parts are optional.<ref>{{cite web |url=http://www.learncpp.com/cpp-tutorial/57-for-statements/ |title=For loops in C++ |website=Learn C++}}</ref> This type of "semicolon loops" came from [[B (programming language)|B programming language]] and it was originally invented by [[Stephen C. Johnson|Stephen Johnson]].<ref name="ken">{{cite AV media |last=Thompson |first=Ken |author-link=Ken Thompson |website=[[YouTube]] |url=https://www.youtube.com/watch?v=EY6q5dv_B-o&t=2330 |title=VCF East 2019 – Brian Kernighan interviews Ken Thompson |archive-url=https://ghostarchive.org/varchive/youtube/20211212/EY6q5dv_B-o |archive-date=2021-12-12 |url-status=live |quote=I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it. |access-date=2020-11-16}}{{cbignore}}</ref>
<source Lang="java">

for (int i=0; i<100; i++) // Prints the numbers 0 to 99 (and not 100), each separated by a space.
In the initialization part, any variables needed are declared (and usually assigned values). If multiple variables are declared, they should all be the same type. The condition part checks a certain condition and exits the loop if false, even if the loop is never executed. If the condition is true, then the lines of code inside the loop are executed. The advancement to the next iteration part is performed exactly once every time the loop ends. The loop is then repeated if the condition evaluates to true.

Here is an example of the C-style traditional for-loop in [[Java (programming language)|Java]].

<syntaxhighlight Lang="java">
// Prints the numbers from 0 to 99 (and not 100), each followed by a space.

for (int i=0; i<100; i++)
{
{
System.out.print(i);
System.out.print(i);
Line 41: Line 47:
}
}
System.out.println();
System.out.println();
</syntaxhighlight>
</source>


These loops are also sometimes named ''numeric for-loops'' when contrasted with foreach loops (see below).
=== Iterator-based for-loops ===
{{Main|Foreach loop}}
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 (programming language)|Python]] is:


===Iterator-based for-loops===
<source Lang="python">
{{Further|Foreach loop}}
for item in some_iterable_object:
This type of for-loop is a generalization 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 data collection. A representative example in [[Python (programming language)|Python]] is:
do Something
do Something Else
</source>


<syntaxhighlight Lang="python">
Where <code>some_iterable_object</code> is either a data collection that supports implicit iteration (like a list of employee's names), 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 <code>for each</code>, as well as a three-expression for-loop (see below) under the name <code>for</code>.
for an item in some_iterable_object:
do_something()
do_something_else()
</syntaxhighlight>


Where {{code|some_iterable_object}} is either a data collection that supports implicit iteration (like a list of employee's names), or may 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 {{code|for each}}, as well as a three-expression for-loop (see below) under the name {{code|for}}.
=== Vectorised for-loops ===

Some languages offer a for-loop that acts as if processing all iterations [[Automatic vectorization|in parallel]], such as the <code>for all</code> keyword in [[FORTRAN 95]] which has the interpretation that ''all'' [[Sides of an equation|right-hand-side]] expressions are evaluated before ''any'' assignments are made, as distinct from the explicit iteration form. For example, in the <code>for</code> statement in the following pseudocode fragment, when calculating the new value for <code>A(i)</code>, except for the first (with <code>i = 2</code>) the reference to <code>A(i - 1)</code> will obtain the new value that had been placed there in the previous step. In the <code>for all</code> version, however, each calculation refers only to the original, unaltered <code>A</code>.
===Vectorised for-loops===
Some languages offer a for-loop that acts as if processing all iterations [[Automatic vectorization|in parallel]], such as the {{code|for all}} keyword in [[Fortran 95]] which has the interpretation that ''all'' [[Sides of an equation|right-hand-side]] expressions are evaluated before ''any'' assignments are made, as distinct from the explicit iteration form. For example, in the {{code|for}} statement in the following pseudocode fragment, when calculating the new value for {{code|A(i)}}, except for the first (with {{code|1=i = 2}}) the reference to {{code|A(i - 1)}} will obtain the new value that had been placed there in the previous step. In the {{code|for all}} version, however, each calculation refers only to the original, unaltered {{code|A}}.
'''for''' i := 2 : N - 1 '''do''' A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3; '''next''' i;
'''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;
'''for all''' i := 2 : N - 1 '''do''' A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3;
The difference may be significant.
The difference may be significant.


Some languages (such as FORTRAN 95, PL/I) also offer array assignment statements, that enable many for-loops to be omitted. Thus pseudocode such as <code>A := 0;</code> would set all elements of array A to zero, no matter its size or dimensionality. The example loop could be rendered as
Some languages (such as PL/I, Fortran 95) also offer array assignment statements, that enable many for-loops to be omitted. Thus pseudocode such as {{code|1=A:= 0;}} would set all elements of array A to zero, no matter its size or dimensionality. The example loop could be rendered as
<source lang="fortran">
<syntaxhighlight lang="Fortran">
A(2 : N - 1) := [A(1 : N - 2) + A(2 : N - 1) + A(3 : N)] / 3;
A(2 : N - 1) := [A(1 : N - 2) + A(2 : N - 1) + A(3 : N)] / 3;
</syntaxhighlight>
</source>
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.
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===
===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
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.''
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'' (and if no such, its value will be ''N + 1''), or, with suitable variations, the first non-blank character in a string, and so on.
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'' (and if no such, its value will be ''N + 1''), or, with suitable variations, the first non-blank character in a string, and so on.


==Loop counters==
==Additional semantics and constructs==
In [[computer programming]], a ''' loop counter''' is a control variable that controls the iterations of a loop (a computer [[programming language]] construct). It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequences (for example., starting at 0 and ending at 10 in increments of 1)


Loop counters change with each iteration of a loop, providing a unique value for each iteration. The loop counter is used to decide when the loop should terminate and for the program flow to continue to the next [[instruction (computer science)|instruction]] after the loop.

A common [[identifier naming convention]] is for the loop counter to use the variable names '''i''', '''j''', and '''k''' (and so on if needed), where '''i''' would be the most outer loop, '''j''' the next inner loop, etc. The reverse order is also used by some programmers. This style is generally agreed to have originated from the early programming of Fortran{{Citation needed|date=August 2009}}, where these variable names beginning with these letters were implicitly declared as having an integer type, and so were obvious choices for loop counters that were only temporarily required. The practice dates back further to [[mathematical notation]] where [[index notation|indices]] for [[summation|sums]] and [[multiplication]]s are often '''i''', '''j''', etc. A variant convention is the use of duplicated letters for the index, '''ii''', '''jj''', and ''' kk''', as this allows easier searching and search-replacing than using a single letter.<ref>http://www.knosof.co.uk/vulnerabilities/loopcntrl.pdf Analysis of loop control variables in C</ref>

===Example===
An example of C code involving nested for loops, where the loop counter variables are '''i''' and '''j''':

<syntaxhighlight lang="c">
for (i = 0; i < 100; i++) {
for (j = i; j < 10; j++) {
some_function(i, j);
}
}
</syntaxhighlight>

Loops in C can also be used to print the reverse of a word. As:
<syntaxhighlight lang="c">
for (i = 0; i < 6; i++) {
scanf("%c", &a[i]);
}
for (i = 4; i >= 0; i--) {
printf("%c", a[i]);
}
</syntaxhighlight>
Here, if the input is {{code|apple}}, the output will be {{code|elppa}}.

==Additional semantics and constructs==
===Use as infinite loops===
===Use as infinite loops===
{{Further|Infinite loop}}
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 (with empty expressions), such as:
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. When infinite loops are intended, this type of for-loop can be used (with empty expressions), such as:


<source lang=C>
<syntaxhighlight lang="c">
for (;;)
for (;;)
//loop body
//loop body
</syntaxhighlight>
</source>


This style is used instead of infinite {{code|while (1)}} loops to avoid a type conversion warning in some C/C++ compilers.<ref>{{cite web |title=Compiler Warning (level 4) C4127 |url=http://msdn.microsoft.com/en-us/library/6t66728h.aspx |publisher=Microsoft |accessdate=29 June 2011}}</ref> Some programmers prefer the more succinct {{code|for (;;)}} form over the semantically equivalent but more verbose {{code|while (true)}} form.
This style is used instead of infinite {{code|while (1)}} loops to avoid a type conversion warning in some C/C++ compilers.<ref>{{cite web |title=Compiler Warning (level 4) C4127 |url=http://msdn.microsoft.com/en-us/library/6t66728h.aspx |publisher=Microsoft |access-date=29 June 2011}}</ref> Some programmers prefer the more succinct {{code|for (;;)}} form over the semantically equivalent but more verbose {{code|while (true)}} form.


===Early exit and continuation===
===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 statement|break]] and [[Control flow#Continuation with next iteration|continue]] statements found in C and its derivatives. The break statement causes the innermost 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. A for statement also terminates when a break, goto, or return statement within the statement body is executed.[Wells] Other languages may have similar statements or otherwise provide means to alter the for-loop progress; for example in Fortran 95:
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 statement|break]] and [[Control flow#Continuation with next iteration|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:


<source lang=FORTRAN>
<syntaxhighlight lang="Fortran">
DO I = 1, N
DO I = 1, N
statements !Executed for all values of "I", up to a disaster if any.
statements!Executed for all values of "I", up to a disaster if any.
IF (no good) CYCLE !Skip this value of "I", continue with the next.
IF (no good) CYCLE! Skip this value of "I", and continue with the next.
statements !Executed only where goodness prevails.
Statements!Executed only where goodness prevails.
IF (disaster) EXIT !Abandon the loop.
IF (disaster) EXIT! Abandon the loop.
statements !While good and, no disaster.
Statements!While good and, no disaster.
END DO !Should align with the "DO".
END DO! Should align with the "DO".
</syntaxhighlight>
</source>

Some languages offer further facilities such as naming the various loop statements so that with multiple nested loops there is no doubt as to which loop is involved. Fortran 95, for example:
<syntaxhighlight lang="Fortran">
X1:DO I = 1, N
statements
X2:DO J = 1, M
statements
IF (trouble) CYCLE X1
statements
END DO X2
statements
END DO X1
</syntaxhighlight>
Thus, when "trouble" is detected in the inner loop, the CYCLE X1 (not X2) means that the skip will be to the next iteration for I, ''not'' J. The compiler will also be checking that each END DO has the appropriate label for its position: this is not just a documentation aid. The programmer must still code the problem correctly, but some possible blunders will be blocked.


===Loop variable scope and semantics===
===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.
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 in memory. Actual behavior may even vary according to the compiler's optimization settings, as with the Honeywell Fortran66 compiler.


In some languages (not [[C (language)|C]] or [[C++]]) the loop variable is [[Immutable object|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:
In some languages (not [[C (programming language)|C]] or [[C++]]) the loop variable is [[Immutable object|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:


<source lang=FORTRAN>
<syntaxhighlight lang="Fortran">
DO I = 1, N
DO I = 1, N
I = 7 !Overt adjustment of the loop variable. Compiler complaint likely.
I = 7!Overt adjustment of the loop variable. Compiler complaint likely.
Z = ADJUST(I) !Function "ADJUST" might alter "I", to uncertain effect.
Z = ADJUST(I)!Function "ADJUST" might alter "I", to uncertain effect.
normal statements !Memory might fade that "I" is the loop variable.
Normal statements! Memory might fade and "I" is the loop variable.
PRINT (A(I), B(I), I = 1, N, 2) !Implicit for-loop to print odd elements of arrays A and B, reusing "I"
PRINT (A(I), B(I), I = 1, N, 2)!Implicit for-loop to print odd elements of arrays A and B, reusing "I"...
PRINT I !What value will be presented?
PRINT I ! What value will be presented?
END DO !How many times will the loop be executed?
END DO! How many times will the loop be executed?
</syntaxhighlight>
</source>


A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in <code>for i := 0 : 65535 do ... ;</code> in sixteen-bit integer arithmetic) and with each iteration decrement this count while also adjusting the value of <code>I</code>: double counting results. However, adjustments to the value of <code>I</code> within the loop will not change the number of iterations executed.
A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in {{code|1=for i:= 0: 65535 do ... ;}} in sixteen-bit integer arithmetic) and with each iteration decrement this count while also adjusting the value of {{mono|I}}: double counting results. However, adjustments to the value of {{mono|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 <code>I</code> on each iteration. Again, modifications of <code>I</code> would not affect the control of the loop, but now a disjunction is possible: within the loop, references to the value of <code>I</code> might be to the (possibly altered) current value of <code>I</code> or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element <code>I</code> of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if <code>I</code> is a parameter to some routine (for instance, a ''print''-statement to reveal its value), it would likely be a reference to the proper variable <code>I</code> instead. It is best to avoid such possibilities.
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 {{mono|I}} on each iteration. Again, modifications of {{mono|I}} would not affect the control of the loop, but now a disjunction is possible: within the loop, references to the value of {{mono|I}} might be to the (possibly altered) current value of {{mono|I}} or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element {{mono|I}} of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if {{mono|I}} is a parameter to some routine (for instance, a ''print''-statement to reveal its value), it would likely be a reference to the proper variable {{mono|I}} instead. It is best to avoid such possibilities.


====Adjustment of bounds====
====Adjustment of bounds====
Just as the index variable might be modified within a for-loop, so also may its bounds and direction. But to uncertain effect. A compiler may prevent such attempts, they may have no effect, or they might even work properly - though many would declare that to do so would be wrong. Consider a statement such as
Just as the index variable might be modified within a for-loop, so also may its bounds and direction. But to uncertain effect. A compiler may prevent such attempts, they may have no effect, or they might even work properly - though many would declare that to do so would be wrong. Consider a statement such as
'''for''' i := first : last : step '''do'''
'''for''' i := first : last : step '''do'''
A(i) := A(i) / A(last);
A(i) := A(i) / A(last);
If the approach to compiling such a loop were to be the evaluation of ''first'', ''last'' and ''step'' and the calculation of an iteration count via something like ''(last - first)/step'' once only at the start, then if those items were simple variables and their values were somehow adjusted during the iterations, this would have no effect on the iteration count even if the element selected for division by ''A(last)'' changed.
If the approach to compiling such a loop was to be the evaluation of {{mono|first}}, {{mono|last}} and {{mono|step}} and the calculation of an iteration count via something like {{code|(last - first)/step}} once only at the start, then if those items were simple variables and their values were somehow adjusted during the iterations, this would have no effect on the iteration count even if the element selected for division by {{code|A(last)}} changed.


===List of value ranges===
===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:
PL/I and ALGOL 68, allow 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:
<source lang="pli">
<syntaxhighlight lang="rexx">
do i = 1, 7, 12 to 15;
do i = 1, 7, 12 to 15;
/*statements*/
/*statements*/
end;
end;
</syntaxhighlight>
</source>


== Equivalence with while-loops ==
==Equivalence with while-loops==
A for-loop is generally equivalent to a while-loop:
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
factorial := 1
for counter from 1 to 5
for counter from 2 to 5
factorial = factorial * counter
factorial := factorial * counter
counter:= counter - 1
print counter + "! equals " + factorial


Is equivalent to:
is easily translated into the following while-loop:


factorial = 1
factorial := 1
counter = 1
counter := 1
while counter <= 5
while counter < 5
factorial = factorial * counter
counter := counter + 1
counter = counter + 1
factorial := factorial * counter
print counter + "! equals " + factorial


As demonstrated by the output of the variables.
This translation is slightly complicated by languages which allow a statement to jump to the next iteration of the loop (such as the "continue" statement in C). These statements will typically implicitly increment the counter of a for-loop, but not the equivalent while-loop (since in the latter case the counter is not an integral part of the loop construct). Any translation will have to place all such statements within a block that increments the explicit counter before running the statement.


==Timeline of the ''for-loop'' syntax in various programming languages==
=== In practice ===
The formal equivalence applies only in so far as computer arithmetic also follows the axia of mathematics, in particular that x + 1 > x. Actual computer arithmetic suffers from the overflow of limited representations so that for example in sixteen-bit unsigned arithmetic, 65535 + 1 comes out as zero, because 65536 cannot be represented in unsigned sixteen-bit. Similar problems arise for other sizes, signed or unsigned. Compiler writers will handle the likes of <code>for counter := 0 to 65535 do ... next counter</code>, possibly by producing code that inspects the state of an "overflow" indicator, but unless there is some provision for the equivalent checking when calculating <code>counter := counter + 1;</code> the while-loop equivalence will fail because the counter will never exceed 65535 and so the loop will never end - unless some other mishap occurs.

== Timeline of the ''for-loop'' syntax in various programming languages ==
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.
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.


===1957: FORTRAN===
===1957: FORTRAN===
{{Further|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 (inclusive).
Fortran's equivalent of the {{mono|for}} loop is the {{mono|DO}} loop,
<source lang=FORTRAN>
using the keyword do instead of for,
do counter = 1, 5, 1
The syntax of Fortran's {{mono|DO}} loop is:
<syntaxhighlight lang="fortranfixed">
DO label counter = first, last, step
statements
label statement
</syntaxhighlight>
The following two examples behave equivalently to the three argument for-loop in other languages,
initializing the counter variable to 1, incrementing by 1 each iteration of the loop, and stopping at five (inclusive).
<syntaxhighlight lang="fortranfixed">
DO 9, COUNTER = 1, 5, 1
WRITE (6,8) COUNTER
8 FORMAT( I2 )
9 CONTINUE
</syntaxhighlight>
In Fortran 77 (or later), this may also be written as:
<syntaxhighlight lang="Fortran">
do counter = 1, 5
write(*, '(i2)') counter
write(*, '(i2)') counter
end do
end do
</syntaxhighlight>
</source>
The step part may be omitted if the step is one. Example:

<syntaxhighlight lang="fortranfixed">
Fortran's equivalent of the <code>for</code> loop is the <code>DO</code> loop. The syntax of Fortran's <CODE>DO</CODE> loop is:
* DO loop example.
<source lang=FORTRAN>
DO label counter=initial, final, step
statements
label statement
</source>
Where the step part may be omitted if the step is one. Example: (spaces are irrelevant in Fortran statements, thus SUM SQ is the same as SUMSQ)

<source lang=FORTRAN>
! DO loop example
PROGRAM MAIN
PROGRAM MAIN
SUM SQ = 0
SUM SQ = 0
DO 101 I = 1, 9999999
DO 199 I = 1, 9999999
IF (SUM SQ.GT.1000) GO TO 109
IF (SUM SQ.GT.1000) GO TO 200
SUM SQ = SUM SQ + I**2
199 SUM SQ = SUM SQ + I**2
101 CONTINUE
200 PRINT 206, SUMSQ
109 CONTINUE
206 FORMAT( I2 )
END
END
</syntaxhighlight>
</source>
Spaces are irrelevant in fixed-form Fortran statements, thus {{mono|SUM SQ}} is the same as {{mono|SUMSQ}}. In the modern free-form Fortran style, blanks are significant.


In Fortran 90, the {{mono|GO TO}} may be avoided by using an {{mono|EXIT}} statement.
===1958: Algol===
<syntaxhighlight lang="fortranfixed">
[[ALGOL|Algol]] was first formalised in the Algol58 report.
* DO loop example.
program main
implicit none

integer:: sums
integer:: i

sums = 0
do i = 1, 9999999
if (sums > 1000.0) exit
sums = sums + i**2
end do
print *, sums

end program
</syntaxhighlight>

===1958: ALGOL===
{{Further|ALGOL 58}}
ALGOL 58 introduced the {{code|for}} statement, using the form as Superplan:

FOR ''Identifier'' = ''Base'' (''Difference'') ''Limit''

For example to print 0 to 10 incremented by 1:
<pre>
FOR x = 0 (1) 10 BEGIN
PRINT (FL) = x END
</pre>


===1960: COBOL===
===1960: COBOL===
{{Further|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
[[COBOL]] was formalized in late 1959 and has had many elaborations. It uses the PERFORM verb which has many options. Originally all loops had to be out-of-line with the iterated code occupying a separate paragraph. Ignoring the need for declaring and initializing variables, the COBOL equivalent of a ''for''-loop would be.

<syntaxhighlight lang="cobol">
PERFORM SQ-ROUTINE VARYING I FROM 1 BY 1 UNTIL I > 1000

SQ-ROUTINE
ADD I**2 TO SUM-SQ.
</syntaxhighlight>

In the 1980s, the addition of in-line loops and ''[[structured programming]]'' statements such as END-PERFORM resulted in a ''for''-loop with a more familiar structure.


<source lang=COBOL>
<syntaxhighlight lang="cobol">
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 1000
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 1000
ADD I**2 TO SUM-SQ.
ADD I**2 TO SUM-SQ.
END-PERFORM
END-PERFORM
</syntaxhighlight>
</source>
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.
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.


===1964: BASIC===
===1964: BASIC===
{{Further|BASIC}}
Loops in [[BASIC]] are sometimes called for-next loops.
In [[BASIC]], a loop is sometimes named a ''for-next loop''.


<source lang="freebasic">
<syntaxhighlight lang="basic">
10 REM THIS FOR LOOP PRINTS ODD NUMBERS FROM 1 TO 15
For I = 1 to 5;
20 FOR I = 1 TO 15 STEP 2
Print I;
30 PRINT I
Next I
40 NEXT I
</source>
</syntaxhighlight>
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 (PL/I, FORTRAN 95 and later) 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.
The end-loop marker specifies the name of the index variable, which must correspond to the name of the index variable at the start of the for-loop. Some languages (PL/I, Fortran 95, and later) allow a statement label at 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 {{code|EXIT}} and {{code|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.


===1964: PL/I===
===1964: PL/I===
{{Further|PL/I}}
<source lang=PLI>
<syntaxhighlight lang="rexx">
do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */
do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */
/*statements*/;
/*statements*/;
end;
end;
</syntaxhighlight>
</source>


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.
The {{mono|LEAVE}} statement may be used to exit the loop. Loops can be [[Label (computer science)|labeled]], and ''leave'' may leave a specific labeled loop in a group of nested loops. Some PL/I dialects include the {{mono|ITERATE}} statement to terminate the current loop iteration and begin the next.


===1968: Algol 68===
===1968: ALGOL 68===
{{Further|ALGOL 68}}
[[Algol68]] has what was considered ''the'' universal loop, the full syntax is:
ALGOL 68 has what was considered ''the'' universal loop, the full syntax is:
<source lang=Algol68>
<pre>
FOR i FROM 1 BY 2 TO 3 WHILE i≠4 DO ~ OD
FOR i FROM 1 BY 2 TO 3 WHILE i≠4 DO ~ OD
</source>
</pre>


Further, the single iteration range could be replaced by a list of such ranges. There are several unusual aspects of the construct
Further, the single iteration range could be replaced by a list of such ranges. There are several unusual aspects of the construct
* only the {{code|do ~ od}} portion was compulsory, in which case the loop will iterate indefinitely.
* only the {{code|do ~ od}} portion was compulsory, in which case the loop will iterate indefinitely.
* thus the clause {{code|to 100 do ~ od}}, will iterate exactly 100 times.
* thus the clause {{code|to 100 do ~ od}}, will iterate exactly 100 times.
* the {{code|while}} ''syntactic element'' allowed a programmer to break from a {{code|for}} loop early, as in:
* The {{code|while}} ''syntactic element'' allowed a programmer to break from a {{code|for}} loop early, as in:
<pre>
<source lang="algol68">
INT sum sq := 0;
INT sum sq := 0;
FOR i
FOR i
Line 237: Line 335:
sum sq +:= i↑2
sum sq +:= i↑2
OD
OD
</source>
</pre>


Subsequent ''extensions'' to the standard Algol68 allowed the {{code|to}} syntactic element to be replaced with {{code|{{sic|hide=y|up|to}}}} and {{code|downto}} to achieve a small optimization. The same compilers also incorporated:
Subsequent ''extensions'' to the standard ALGOL 68 allowed the {{code|to}} syntactic element to be replaced with {{code|{{sic|hide=y|up|to}}}} and {{code|downto}} to achieve a small optimization. The same compilers also incorporated:
;{{code|until}}: for late loop termination.
;{{code|until}}: for late loop termination.
;{{code|foreach}}: for working on arrays in [[parallel computing|parallel]].
;{{code|foreach}}: for working on arrays in [[parallel computing|parallel]].


===1970: Pascal===
===1970: Pascal===
{{Further|Pascal (programming language)}}
<source lang=Pascal>
<syntaxhighlight lang="pascal">
for Counter := 1 to 5 do
for Counter:= 1 to 5 do
(*statement*);
(*statement*);
</syntaxhighlight>
</source>


Decrementing (counting backwards) is using {{code|downto}} keyword instead of {{code|to}}, as in:
Decrementing (counting backwards) is using {{code|downto}} keyword instead of {{code|to}}, as in:


<source lang=Pascal>
<syntaxhighlight lang="pascal">
for Counter := 5 downto 1 do
for Counter:= 5 down to 1 do
(*statement*);
(*statement*);
</syntaxhighlight>
</source>


The numeric-range for-loop varies somewhat more.
The numeric range for-loop varies somewhat more.


===1972: C/C++===
===1972: C, C++===
{{further|C syntax#Iteration statements}}
{{Further|C (programming language)|C++|C syntax#Iteration statements}}
<source lang=C>
<syntaxhighlight lang="c">
for (initialization; condition; increment/decrement)
for (initialization; condition; increment/decrement)
statement
statement
</syntaxhighlight>
</source>
The <tt>statement</tt> is often a block statement; an example of this would be:
The {{mono|statement}} is often a block statement; an example of this would be:
<source lang=C>
<syntaxhighlight lang="c">
//Using for-loops to add numbers 1 - 5
//Using for-loops to add numbers 1 - 5
int sum = 0;
int sum = 0;
for (int i = 1; i < 6; ++i) {
for (int i = 1; i <= 5; ++i) {
sum += i;
sum += i;
}
}
</syntaxhighlight>
</source>
The ISO/IEC 9899:1999 publication (commonly known as [[C99]]) also allows initial declarations in <code>for</code> loops.
The ISO/IEC 9899:1999 publication (commonly known as [[C99]]) also allows initial declarations in {{code|for}} loops. All three sections in the for loop are optional, with an empty condition equivalent to true.


===1972: Smalltalk===
===1972: Smalltalk===
{{Further|Smalltalk}}
<source lang=Smalltalk>1 to: 5 do: [ :counter | "statements" ]</source>
<syntaxhighlight lang="smalltalk">1 to: 5 do: [ :counter | "statements" ]</syntaxhighlight>
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 (computer science)|closure]], using self as start value.
Contrary to other languages, in [[Smalltalk]] a for-loop is not a [[language construct]] but is defined in the class Number as a method with two parameters, the end value and a [[Closure (computer science)|closure]], using self as start value.


===1980: Ada===
===1980: Ada===
{{Further|Ada (programming language)}}
<source lang="ada">
<syntaxhighlight lang="ada">
for Counter in 1 .. 5 loop
for Counter in 1 .. 5 loop
-- statements
-- statements
end loop;
end loop;
</syntaxhighlight>
</source>


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:
The ''exit'' statement may be used to exit the loop. Loops can be labeled, and ''exit'' may leave a specifically labeled loop in a group of nested loops:
<source lang="ada">
<syntaxhighlight lang="ada">
Counting:
Counting:
for Counter in 1 .. 5 loop
For Counter in 1 .. 5 loop
Triangle:
Triangle:
for Secondary_Index in 2 .. Counter loop
for Secondary_Index in 2 .. Counter loop
Line 296: Line 397:
end loop Triangle;
end loop Triangle;
end loop Counting;
end loop Counting;
</syntaxhighlight>
</source>


===1980: Maple===
===1980: Maple===
{{Further|Maple (software)}}

Maple has two forms of for-loop, one for iterating of a range of values, and the other for iterating over the contents of a container. The value range form is as follows:
Maple has two forms of for-loop, one for iterating over a range of values, and the other for iterating over the contents of a container. The value range form is as follows:


'''for''' ''i'' '''from''' ''f'' '''by''' ''b'' '''to''' ''t'' '''while''' ''w'' '''do'''
'''for''' ''i'' '''from''' ''f'' '''by''' ''b'' '''to''' ''t'' '''while''' ''w'' '''do'''
Line 306: Line 407:
'''od''';
'''od''';


All parts except <code><b>do</b></code> and <code><b>od</b></code> are optional. The <code><b>for</b> <i>i</i></code> part, if present, must come first. The remaining parts (<code><b>from</b> <i>f</i></code>, <code><b>by</b> <i>b</i></code>, <code><b>to</b> <i>t</i></code>, <code><b>while</b> <i>w</i></code>) can appear in any order.
All parts except <code>'''do'''</code> and <code>'''od'''</code> are optional. The <code>''' for''' ''I''</code> part, if present, must come first. The remaining parts (<code>'''from''' ''f''</code>, <code>'''by''' ''b''</code>, <code>'''to''' ''t''</code>, <code>'''while''' ''w''</code>) can appear in any order.


Iterating over a container is done using this form of loop:
Iterating over a container is done using this form of loop:
Line 314: Line 415:
'''od''';
'''od''';


The <code><b>in</b> <i>c</i></code> clause specifies the container, which may be a list, set, sum, product, unevaluated function, array, or an object implementing an iterator.
The <code>''' in''' ''c''</code> clause specifies the container, which may be a list, set, sum, product, unevaluated function, array, or object implementing an iterator.


A for-loop may be terminated by <code><b>od</b></code>, <code><b>end</b></code>, or <code><b>end do</b></code>.
A for-loop may be terminated by <code>'''od'''</code>, <code>'''end'''</code>, or <code>'''end do'''</code>.


===1982: Maxima CAS===
===1982: Maxima CAS===
{{Further|Maxima (software)}}
In [[Maxima CAS]] one can use also non integer values :
In Maxima CAS, one can use also integer values:
<source lang=Lua>
<syntaxhighlight lang="maxima">
for x:0.5 step 0.1 thru 0.9 do
for x:0.5 step 0.1 thru 0.9 do
/* "Do something with x" */
/* "Do something with x" */
</syntaxhighlight>
</source>


===1982: PostScript===
===1982: PostScript===
{{Further|PostScript}}
The for-loop, written as <code>[initial] [increment] [limit] { ... } for</code> initialises an internal variable, executes the body as long as the internal variable is not more than limit (or not less, if increment is negative) and, at the end of each iteration, increments the internal variable. Before each iteration, the value of the internal variable is pushed onto the stack.<ref>{{cite book|title=PostScript Language Reference|publisher=Addison-Wesley Publishing Company|page=596|isbn=0-201-37922-8}}</ref>
The for-loop, written as {{code|[initial] [increment] [limit] { ... } for}} initializes an internal variable, and executes the body as long as the internal variable is not more than the limit (or not less, if the increment is negative) and, at the end of each iteration, increments the internal variable. Before each iteration, the value of the internal variable is pushed onto the stack.<ref>{{cite book |year=1999 |title=PostScript Language Reference |publisher=Addison-Wesley Publishing Company |page=596 |isbn=0-201-37922-8}}</ref>
<source lang=AppleScript>
<syntaxhighlight lang="applescript">
1 1 6 {STATEMENTS} for
1 1 6 {STATEMENTS} for
</syntaxhighlight>
</source>
There is also a simple repeat-loop.
There is also a simple repeat loop.
The repeat-loop, written as <code>X { ... } repeat</code>, repeats the body exactly X times.<ref>{{cite web|url=http://pscript.dubmun.com/tutorial4.html|title=PostScript Tutorial - Loops}}</ref>
The repeat-loop, written as {{code|X { ... } repeat}}, repeats the body exactly X times.<ref>{{cite web|url=http://pscript.dubmun.com/tutorial4.html|title=PostScript Tutorial - Loops}}</ref>
<source lang=AppleScript>
<syntaxhighlight lang="applescript">
5 { STATEMENTS } repeat
5 { STATEMENTS } repeat
</syntaxhighlight>
</source>


===1983: Ada 83 and above===
===1983: Ada 83 and above===
{{Further|Ada (programming language)}}
<source lang=ADA>
<syntaxhighlight lang="ada">
procedure Main is
procedure Main is
Sum_Sq : Integer := 0;
Sum_Sq : Integer := 0;
begin
begin
for I in 1 .. 9999999 loop
for I in 1 .. 9999999 loop
if Sum_Sq <= 1000 then
if Sum_Sq <= 1000 then
Sum_Sq := Sum_Sq + I**2
Sum_Sq := Sum_Sq + I**2
Line 347: Line 451:
end loop;
end loop;
end;
end;
</syntaxhighlight>
</source>


===1984: MATLAB===
===1984: MATLAB===
<source lang=MATLAB>
{{Further|MATLAB}}
<syntaxhighlight lang="Matlab">
for i = 1:5
for n = 1:5
-- statements
-- statements
end</source>
end</syntaxhighlight>
After the loop, {{code|n}} would be 5 in this example.

As {{code|i}} is used for the [[Imaginary unit]], its use as a loop variable is discouraged.


===1987: Perl===
===1987: Perl===
<source lang=Perl>
{{Further|Perl}}
<syntaxhighlight lang="perl">
for ($counter = 1; $counter <= 5; $counter++) { # implictly or predefined variable
for ($counter = 1; $counter <= 5; $counter++) { # implicitly or predefined variable
# statements;
# statements;
}
}
for (my $counter = 1; $counter <= 5; $counter++) { # variable private to the loop
for (my $counter = 1; $counter <= 5; $counter++) { # variable private to the loop
# statements;
# statements;
}
}
for (1..5) { # variable impicitly called $_; 1..5 creates a list of these 5 elements
for (1..5) { # variable implicitly called $_; 1..5 creates a list of these 5 elements
# statements;
# statements;
}
}
statement for 1..5; # almost same (only 1 statement) with natural language order
statement for 1..5; # almost same (only 1 statement) with natural language order
for my $counter (1..5) { # variable private to the loop
for my $counter (1..5) { # variable private to the loop
# statements;
# statements;
}
}
</syntaxhighlight>
</source>


(Note that "[[there's more than one way to do it]]" is a Perl programming motto.)
"[[There's more than one way to do it]]" is a Perl programming motto.


===1988: Mathematica===
===1988: Mathematica===
{{Further|Wolfram Mathematica|Wolfram Language}}
The construct corresponding to most other languages' for-loop is named ''Do'' in Mathematica.


<syntaxhighlight lang="ruby">
The construct corresponding to most other languages' for-loop is called Do in Mathematica

<source lang=Ruby>
Do[f[x], {x, 0, 1, 0.1}]
Do[f[x], {x, 0, 1, 0.1}]
</syntaxhighlight>
</source>


Mathematica also has a For construct that mimics the for-loop of C-like languages
Mathematica also has a For construct that mimics the for-loop of C-like languages.


<source lang=Ruby>
<syntaxhighlight lang="ruby">
For[x= 0 , x <= 1, x += 0.1,
For[x= 0 , x <= 1, x += 0.1,
f[x]
f[x]
]
]
</syntaxhighlight>
</source>


===1989: Bash===
===1989: Bash===
{{Further|Bash (Unix shell)}}
<source lang="bash">
<syntaxhighlight lang="bash">
# first form
# first form
for i in 1 2 3 4 5
for i in 1 2 3 4 5
do
do
# must have at least one command in loop
# must have at least one command in a loop
echo $i # just print value of i
echo $i # just print the value of i
done
done
</syntaxhighlight>
</source>


<source lang="bash">
<syntaxhighlight lang="bash">
# second form
# second form
for (( i = 1; i <= 5; i++ ))
for (( i = 1; i <= 5; i++ ))
do
do
# must have at least one command in loop
# must have at least one command in a loop
echo $i # just print value of i
echo $i # just print the value of i
done
done
</syntaxhighlight>
</source>


Note that an empty loop (i.e., one with no commands between <code>do</code> and <code>done</code>) is a syntax error. If the above loops contained only comments, execution would result in the message "<code>syntax error near unexpected token 'done'</code>".
An empty loop (i.e., one with no commands between {{code|do}} and {{code|done}}) is a syntax error. If the above loops contained only comments, execution would result in the message "syntax error near unexpected token 'done'".


===1990: Haskell===
===1990: Haskell===
{{Further|Haskell}}
The built-in imperative ''forM_'' maps a [[monad (functional programming)|monadic]] expression into a list, as
The built-in imperative ''forM_'' maps a [[monad (functional programming)|monadic]] expression into a list, as
<source lang="haskell">
<syntaxhighlight lang="haskell">
forM_ [1..5] $ \indx -> do statements
forM_ [1..5] $ \indx -> do statements
</syntaxhighlight>
</source>


or get each iteration result as a list in
or get each iteration result as a list in
<source lang="haskell">
<syntaxhighlight lang="Haskell">
statements_result_list <- forM [1..5] $ \indx -> do statements
statements_result_list <- forM [1..5] $ \indx -> do statements
</syntaxhighlight>
</source>


But, if you want to save the space of the [1..5] list,
But, to save the space of the [1..5] list,
a more authentic [[monad (functional programming)|monadic]] ''forLoop_'' construction can be defined as
a more authentic monadic ''forLoop_'' construction can be defined as


<source lang="haskell">
<syntaxhighlight lang="Haskell">
import Control.Monad as M
import Control.Monad as M


forLoopM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forLoopM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forLoopM_ indx prop incr f = do
forLoopM_ indx prop incr f = do
f indx
f index
M.when (prop next) $ forLoopM_ next prop incr f
M.when (prop next) $ forLoopM_ next prop incr f
where
where
next = incr indx
next = incur index
</syntaxhighlight>
</source>
and used as:
and used as:
<source lang="haskell">
<syntaxhighlight lang="Haskell">
forLoopM_ (0::Int) (< len) (+1) $ \indx -> do -- whatever with the index
forLoopM_ (0::Int) (< len) (+1) $ \indx -> do -- whatever with the index
</syntaxhighlight>
</source>


===1991: Oberon-2, Oberon-07, or Component Pascal===
===1991: Oberon-2, Oberon-07, Component Pascal===
{{Further|Oberon (programming language)|Oberon-2|Component Pascal}}
<source lang=Oberon2>
<syntaxhighlight lang="modula2">
FOR Counter := 1 TO 5 DO
FOR Counter:= 1 TO 5 DO
(* statement sequence *)
(* statement sequence *)
END
END
</syntaxhighlight>
</source>
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.
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.


===1991: Python===
===1991: Python===
{{Further|Python (programming language)}}
<source lang=Python>
Python does not contain the classical for loop, rather a <code>foreach</code> loop is used to iterate over the output of the built-in <code>range()</code> function which returns an iterable sequence of integers.<syntaxhighlight lang="python">
for counter in range(1, 6): # range(1, 6) gives values from 1 to 5 inclusive (but not 6)
for i in range(1, 6): # gives i values from 1 to 5 inclusive (but not 6)
# statements
# statements
</source>
print(i)
# if we want 6 we must do the following
for i in range(1, 6 + 1): # gives i values from 1 to 6
# statements
print(i)
</syntaxhighlight>Using <code>range(6)</code> would run the loop from 0 to 5.


===1993: AppleScript===
===1993: AppleScript===
<source lang=AppleScript>
{{Further|AppleScript}}
<syntaxhighlight lang="applescript">
repeat with i from 1 to 5
repeat with i from 1 to 5
-- statements
-- statements
log i
log i
end repeat
end repeat
</syntaxhighlight>
</source>


You can also iterate through a list of items, similar to what you can do with arrays in other languages:
It can also iterate through a list of items, similar to what can be done with arrays in other languages:
<source lang=AppleScript>
<syntaxhighlight lang="applescript">
set x to {1, "waffles", "bacon", 5.1, false}
set x to {1, "waffles", "bacon", 5.1, false}
repeat with i in x
repeat with i in x
log i
log i
end repeat
end repeat
</syntaxhighlight>
</source>


You may also use {{code|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 a loop.
A {{code|exit repeat}} may also be used to exit a loop at any time. Unlike other languages, AppleScript currently has no command to continue to the next iteration of a loop.


===1993: Lua===
===1993: Crystal===
{{Further|Crystal (programming language)}}
<source lang=Lua>
<syntaxhighlight lang="lua">
for i = start, stop, interval do
for i = start, stop, interval do
-- statements
-- statements
end</source>
end</syntaxhighlight>


So, this code <source lang=Lua>
So, this code <syntaxhighlight lang="lua">
for i = 1, 5, 2 do
for i = 1, 5, 2 do
print(i)
print(i)
end</source> will print:
end</syntaxhighlight> will print:
<source lang=Lua>1 3 5</source>
<syntaxhighlight lang="lua">1 3 5</syntaxhighlight>


For-loops can also loop through a table using <source lang=lua>ipairs()</source> to iterate numerically through arrays and <source lang=lua>pairs()</source> to iterate randomly through dictionaries.
For-loops can also loop through a table using <syntaxhighlight lang="lua">ipairs()</syntaxhighlight> to iterate numerically through arrays and <syntaxhighlight lang="lua">pairs()</syntaxhighlight> to iterate randomly through dictionaries.
Generic for-loop making use of [[Closure (computer science)|closures]]:
Generic for-loop making use of closures:


<source lang=Lua>
<syntaxhighlight lang="lua">
for name, phone, address in contacts() do
for name, phone, and address in contacts() do
-- contacts() must be an iterator function
-- contacts() must be an iterator function
end</source>
end</syntaxhighlight>


===1995: [[CFML]]===
===1995: ColdFusion Markup Language (CFML)===
{{Further|ColdFusion Markup Language}}


====Script syntax====
====Script syntax====
Simple index loop:
Simple index loop:
<source lang=CFM>
<syntaxhighlight lang="cfs">
for (i = 1; i <= 5; i++) {
for (i = 1; i <= 5; i++) {
// statements
// statements
}
}
</syntaxhighlight>
</source>


Using an array:
Using an array:
<source lang=CFM>
<syntaxhighlight lang="cfs">
for (i in [1,2,3,4,5]) {
for (i in [1,2,3,4,5]) {
// statements
// statements
}
}
</syntaxhighlight>
</source>


Using a list of string values:
Using a list of string values:
<source lang=CFM>
<syntaxhighlight lang="cfs">
loop index="i" list="1;2,3;4,5" delimiters=",;" {
loop index="i" list="1;2,3;4,5" delimiters=",;" {
// statements
// statements
}
}
</syntaxhighlight>
</source>


The above {{code|list}} example is only available in the dialect of CFML used by [[Lucee]] and [[Railo]].
The above {{code|list}} example is only available in the dialect of CFML used by [[Lucee]] and [[Railo]].


====Tag syntax====
====Tag syntax====
{{Further|Tag (programming)}}
Simple index loop:
Simple index loop:
<source lang=CFM>
<syntaxhighlight lang="cfm">
<cfloop index="i" from="1" to="5">
<cfloop index="i" from="1" to="5">
<!--- statements --->
<!--- statements --->
</cfloop>
</cfloop>
</syntaxhighlight>
</source>


Using an array:
Using an array:
<source lang=CFM>
<syntaxhighlight lang="cfm">
<cfloop index="i" array="#[1,2,3,4,5]#">
<cfloop index="i" array="#[1,2,3,4,5]#">
<!--- statements --->
<!--- statements --->
</cfloop>
</cfloop>
</syntaxhighlight>
</source>


Using a "list" of string values:
Using a "list" of string values:
<source lang=CFM>
<syntaxhighlight lang="cfm">
<cfloop index="i" list="1;2,3;4,5" delimiters=",;">
<cfloop index="i" list="1;2,3;4,5" delimiters=",;">
<!--- statements --->
<!--- statements --->
</cfloop>
</cfloop>
</syntaxhighlight>
</source>


=== 1995:Java ===
===1995: Java===
{{Further|Java (programming language)}}
<source lang=Java>
<syntaxhighlight lang="java">
for (int i = 0; i < 5; i++) {
for (int i = 0; i < 5; i++) {
//perform functions within the loop;
//perform functions within the loop;
Line 547: Line 670:
//can use the statement 'continue;' to skip the current iteration
//can use the statement 'continue;' to skip the current iteration
}
}
</syntaxhighlight>
</source>


For the extended for-loop, see [[Foreach loop#Java|Foreach loop]]
For the extended for-loop, see {{slink|Foreach loop#Java}}.


===1995:JavaScript===
===1995: JavaScript===
{{Further|JavaScript}}
JavaScript supports C-style "three-expression" loops. The <code>break</code> and <code>continue</code> statements are supported inside loops.
JavaScript supports C-style "three-expression" loops. The {{code|break}} and {{code|continue}} statements are supported inside loops.


<source lang=JavaScript>
<syntaxhighlight lang="javascript">
for (var i = 0; i < 5; i++) {
for (var i = 0; i < 5; i++) {
// ...
// ...
}
}
</syntaxhighlight>
</source>


Alternatively, it is possible to iterate over all keys of an array.
Alternatively, it is possible to iterate over all keys of an array.


<source lang=JavaScript>
<syntaxhighlight lang="javascript">
for (var key in array) { // also works for assoc. arrays
for (var key in array) { // also works for assoc. arrays
// use array[key]
// use array[key]
...
...
}
}
</syntaxhighlight>
</source>


===1995: PHP===
===1995: PHP===
{{Further|PHP}}
<source lang=PHP>
This prints out a triangle of *
for ($i = 0; $i <= 5; $i++)
<syntaxhighlight lang="php">
{
for ($j = 0; $j <= $i; $j++)
for ($i = 0; $i <= 5; $i++) {
for ($j = 0; $j <= $i; $j++) {
{
echo "*";
echo "*";
}
}
echo "<br>";
echo "<br />\n";
}
}
</syntaxhighlight>
</source>


===1995: Ruby===
===1995: Ruby===
{{Further|Ruby (programming language)}}
<source lang=Ruby>
<syntaxhighlight lang="ruby">
for counter in 1..5
for the counter in 1..5
# statements
# statements
end
end
Line 594: Line 719:
# statements
# statements
end
end
</syntaxhighlight>
</source>
[[Ruby programming language|Ruby]] has several possible syntaxes, including the above samples.
[[Ruby programming language|Ruby]] has several possible syntaxes, including the above samples.


===1996: OCaml===
===1996: OCaml===
{{Further|OCaml}}
See expression syntax.<ref>[http://caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html OCaml expression syntax]</ref>
See expression syntax.<ref>{{Cite web |url=http://caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html |title=OCaml expression syntax |access-date=2013-03-19 |archive-date=2013-04-12 |archive-url=https://archive.today/20130412180254/http://caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html |url-status=dead }}</ref>
<source lang="ocaml">
<syntaxhighlight lang="ocaml">
(* for_statement := "for" ident '=' expr ( "to" ∣ "downto" ) expr "do" expr "done" *)
(* for_statement:= "for" ident '=' expr ( "to" ∣ "down to" ) expr "do" expr "done" *)


for i = 1 to 5 do
for i = 1 to 5 do
Line 606: Line 732:
done ;;
done ;;


for j = 5 downto 0 do
for j = 5 down to 0 do
(* statements *)
(* statements *)
done ;;
done ;;
</syntaxhighlight>
</source>


===1998: ActionScript 3===
===1998: ActionScript 3===
{{Further|ActionScript}}
<source lang="actionscript3">
<syntaxhighlight lang="actionscript3">
for (var counter:uint = 1; counter <= 5; counter++){
for (var counter:uint = 1; counter <= 5; counter++){
//statement;
//statement;
}
}
</syntaxhighlight>
</source>


===2008: Small Basic===
==Implementation in interpreted programming languages==
{{Further|Microsoft Small Basic}}
In [[Interpreted language|interpreted programming languages]], for-loops can be implemented in many ways. Oftentimes, the for-loops are directly translated to [[Assembly language|assembly]]-like compare instructions and [[goto|conditional jump]] instructions. However, this is not always so. In some interpreted programming languages, for-loops are simply translated to while-loops.<ref>{{cite web|url=https://piazza.com/class#fall2012/cs61b/1575|title=Computer Science 61B: Data Structures and Algorithms in Java 6 - For Loops}}</ref> For instance, take the following Mint/Horchata code:
<syntaxhighlight lang="vbnet">
For i = 1 To 10
' Statements
EndFor
</syntaxhighlight>


===2008: Nim===
<source lang=text>
{{Further|Nim (programming language)}}
for i = 0; i < 100; i++
[[Nim (programming language)|Nim]] has a <code>foreach</code>-type loop and various operations for creating iterators.<ref>https://nim-lang.org/docs/system.html#...i%2CT%2CT ".. iterator"</ref>
print i
<syntaxhighlight lang="nim">
end
for i in 5 .. 10:
# statements
</syntaxhighlight>


===2009: Go===
for each item of sequence
{{Further|Go (programming language)}}
print item
<syntaxhighlight lang="go">
end
for i := 0; i <= 10; i++ {
// statements
}
</syntaxhighlight>

===2010: Rust===
{{Further|Rust (programming language)}}
<syntaxhighlight lang="rust">
for i in 0..10 {
// statements
}
</syntaxhighlight>


===2012: Julia===
/* 'Translated traditional for-loop' */
{{Further|Julia (programming language)}}
i = 0
<syntaxhighlight lang="Julia">
while i < 100
for j = 1:10
print i
i++
# statements
end
end
</syntaxhighlight>


==See also==
/* 'Translated for each loop' */
SYSTEM_VAR_0000 = 0
while SYSTEM_VAR_0000 < sequence.length()
item = sequence[SYSTEM_VAR_0000]
print item
SYSTEM_VAR_0000++
end</source>

== See also ==
* [[Do while loop]]
* [[Do while loop]]
* [[Foreach]]
* [[Foreach]]
* [[Loop counter]]
* [[While loop]]
* [[While loop]]
* [[Primitive recursive function]]
* [[General recursive function]]


== References ==
==References==
{{Reflist}}
{{Reflist}}


[[Category:Control flow]]
{{DEFAULTSORT:For Loop}}
[[Category:Iteration in programming]]
[[Category:Programming language comparisons]]
<!-- Hidden categories below -->
[[Category:Articles with example Ada code]]
[[Category:Articles with example Ada code]]
[[Category:Articles with example ALGOL 68 code]]
[[Category:Articles with example ALGOL 68 code]]
[[Category:Articles with example BASIC code]]
[[Category:Articles with example C code]]
[[Category:Articles with example C code]]
[[Category:Articles with example C++ code]]
[[Category:Articles with example Fortran code]]
[[Category:Articles with example Fortran code]]
[[Category:Articles with example Haskell code]]
[[Category:Articles with example Java code]]
[[Category:Articles with example JavaScript code]]
[[Category:Articles with example Julia code]]
[[Category:Articles with example MATLAB/Octave code]]
[[Category:Articles with example OCaml code]]
[[Category:Articles with example Pascal code]]
[[Category:Articles with example Perl code]]
[[Category:Articles with example Perl code]]
[[Category:Iteration in programming]]
[[Category:Articles with example PHP code]]
[[Category:Articles with example Python (programming language) code]]
[[Category:Articles with example Ruby code]]
[[Category:Articles with example Rust code]]
[[Category:Articles with example Smalltalk code]]

Latest revision as of 23:01, 21 November 2024

Flow diagram of the following for loop code:
for (i = 0; i < 5; i++)
  printf("*");
The loop will cause five asterisks to be printed.

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.

For-loops have two parts: a header and a body. The header defines the iteration and the body is the code executed once per iteration. The header often declares an explicit loop counter or loop variable. This allows the body to know which iteration is being executed. For-loops are typically used when the number of iterations is known before entering the loop. For-loops can be thought of as shorthands for while-loops which increment and test a loop variable.

Various keywords are used to indicate the usage of a for loop: descendants of ALGOL use "for", while descendants of Fortran use "do". There are other possibilities, for example COBOL which uses PERFORM VARYING.

The name for-loop comes from the word for. For is used as the reserved word (or keyword) in many programming languages to introduce a for-loop. The term in English dates to ALGOL 58 and was popularized in ALGOL 60. It is the direct translation of the earlier German für and was used in Superplan (1949–1951) by Heinz Rutishauser. Rutishauser was involved in defining ALGOL 58 and ALGOL 60.[1] The loop body is executed "for" the given values of the loop variable. This is more explicit in ALGOL versions of the for statement where a list of possible values and increments can be specified.

In Fortran and PL/I, the keyword DO is used for the same thing and it is named a do-loop; this is different from a do while loop.

FOR

[edit]
For loop illustration, from i=0 to i=2, resulting in data1=200

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 four categories:

Traditional for-loops

[edit]

The for-loop of languages like ALGOL, Simula, BASIC, Pascal, Modula, Oberon, Ada, MATLAB, OCaml, F#, and so on, requires a control variable with start- and end-values, which looks something like this:

for i = first to last do statement
(* or just *)
for i = first..last do statement

Depending on the language, an explicit assignment sign may be used in place of the equal sign (and some languages require the word int even in the numerical case). An optional step-value (an increment or decrement ≠ 1) may also be included, although the exact syntaxes used for this differ a bit more between the languages. Some languages require a separate declaration of the control variable, some do not.

Another form was popularized by the C language. It requires 3 parts: the initialization (loop variant), the condition, and the advancement to the next iteration. All these three parts are optional.[2] This type of "semicolon loops" came from B programming language and it was originally invented by Stephen Johnson.[3]

In the initialization part, any variables needed are declared (and usually assigned values). If multiple variables are declared, they should all be the same type. The condition part checks a certain condition and exits the loop if false, even if the loop is never executed. If the condition is true, then the lines of code inside the loop are executed. The advancement to the next iteration part is performed exactly once every time the loop ends. The loop is then repeated if the condition evaluates to true.

Here is an example of the C-style traditional for-loop in Java.

// Prints the numbers from 0 to 99 (and not 100), each followed by a space.

for (int i=0; i<100; i++)
{
    System.out.print(i);
    System.out.print(' ');
}
System.out.println();

These loops are also sometimes named numeric for-loops when contrasted with foreach loops (see below).

Iterator-based for-loops

[edit]

This type of for-loop is a generalization 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 data collection. A representative example in Python is:

for an item in some_iterable_object:
    do_something()
    do_something_else()

Where some_iterable_object is either a data collection that supports implicit iteration (like a list of employee's names), or may 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 (see below) under the name for.

Vectorised for-loops

[edit]

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 statement in the following pseudocode fragment, when calculating the new value for A(i), except for the first (with i = 2) 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 (such as PL/I, Fortran 95) 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

 A(2 : N - 1) := [A(1 : N - 2) + A(2 : N - 1) + A(3 : N)] / 3;

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

[edit]

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 (and if no such, its value will be N + 1), or, with suitable variations, the first non-blank character in a string, and so on.

Loop counters

[edit]

In computer programming, a loop counter is a control variable that controls the iterations of a loop (a computer programming language construct). It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequences (for example., starting at 0 and ending at 10 in increments of 1)

Loop counters change with each iteration of a loop, providing a unique value for each iteration. The loop counter is used to decide when the loop should terminate and for the program flow to continue to the next instruction after the loop.

A common identifier naming convention is for the loop counter to use the variable names i, j, and k (and so on if needed), where i would be the most outer loop, j the next inner loop, etc. The reverse order is also used by some programmers. This style is generally agreed to have originated from the early programming of Fortran[citation needed], where these variable names beginning with these letters were implicitly declared as having an integer type, and so were obvious choices for loop counters that were only temporarily required. The practice dates back further to mathematical notation where indices for sums and multiplications are often i, j, etc. A variant convention is the use of duplicated letters for the index, ii, jj, and kk, as this allows easier searching and search-replacing than using a single letter.[4]

Example

[edit]

An example of C code involving nested for loops, where the loop counter variables are i and j:

for (i = 0; i < 100; i++) {
    for (j = i; j < 10; j++) {
        some_function(i, j);
    }
}

Loops in C can also be used to print the reverse of a word. As:

for (i = 0; i < 6; i++) {
    scanf("%c", &a[i]);
}
for (i = 4; i >= 0; i--) {
    printf("%c", a[i]);
}

Here, if the input is apple, the output will be elppa.

Additional semantics and constructs

[edit]

Use as infinite loops

[edit]

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. When infinite loops are intended, this type of for-loop can be used (with empty expressions), such as:

for (;;)
    //loop body

This style is used instead of infinite while (1) loops to avoid a type conversion warning in some C/C++ compilers.[5] Some programmers prefer the more succinct for (;;) form over the semantically equivalent but more verbose while (true) form.

Early exit and continuation

[edit]

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 innermost 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. A for statement also terminates when a break, goto, or return statement within the statement body is executed.[Wells] Other languages may have similar statements or otherwise provide means to alter the for-loop progress; for example in Fortran 95:

DO I = 1, N
  statements!Executed for all values of "I", up to a disaster if any.
  IF (no good) CYCLE! Skip this value of "I", and continue with the next.
  Statements!Executed only where goodness prevails.
  IF (disaster) EXIT! Abandon the loop.
  Statements!While good and, no disaster.
END DO! Should align with the "DO".

Some languages offer further facilities such as naming the various loop statements so that with multiple nested loops there is no doubt as to which loop is involved. Fortran 95, for example:

X1:DO I = 1, N
     statements
  X2:DO J = 1, M
       statements
       IF (trouble) CYCLE X1
       statements
     END DO X2
     statements
   END DO X1

Thus, when "trouble" is detected in the inner loop, the CYCLE X1 (not X2) means that the skip will be to the next iteration for I, not J. The compiler will also be checking that each END DO has the appropriate label for its position: this is not just a documentation aid. The programmer must still code the problem correctly, but some possible blunders will be blocked.

Loop variable scope and semantics

[edit]

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 in memory. Actual behavior may even vary according to the compiler's optimization settings, as with the Honeywell Fortran66 compiler.

In some languages (not C or C++) 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:

DO I = 1, N
  I = 7!Overt adjustment of the loop variable. Compiler complaint likely.
  Z = ADJUST(I)!Function "ADJUST" might alter "I", to uncertain effect.
  Normal statements! Memory might fade and "I" is the loop variable.
  PRINT (A(I), B(I), I = 1, N, 2)!Implicit for-loop to print odd elements of arrays A and B, reusing "I"...
  PRINT I                         ! What value will be presented?
END DO! How many times will the loop be executed?

A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in for i:= 0: 65535 do ... ; in sixteen-bit integer arithmetic) 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 (possibly altered) current value of I or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element I of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if I is a parameter to some routine (for instance, a print-statement to reveal its value), it would likely be a reference to the proper variable I instead. It is best to avoid such possibilities.

Adjustment of bounds

[edit]

Just as the index variable might be modified within a for-loop, so also may its bounds and direction. But to uncertain effect. A compiler may prevent such attempts, they may have no effect, or they might even work properly - though many would declare that to do so would be wrong. Consider a statement such as

for i := first : last : step do
  A(i) := A(i) / A(last);

If the approach to compiling such a loop was to be the evaluation of first, last and step and the calculation of an iteration count via something like (last - first)/step once only at the start, then if those items were simple variables and their values were somehow adjusted during the iterations, this would have no effect on the iteration count even if the element selected for division by A(last) changed.

List of value ranges

[edit]

PL/I and ALGOL 68, allow 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:

do i = 1, 7, 12 to 15;
  /*statements*/
end;

Equivalence with while-loops

[edit]

A for-loop is generally equivalent to a while-loop:

factorial := 1
 for counter from 2 to 5
     factorial := factorial * counter
counter:= counter - 1
print counter + "! equals " + factorial

Is equivalent to:

factorial := 1
counter := 1
 while counter < 5
    counter := counter + 1
    factorial := factorial * counter
print counter + "! equals " + factorial

As demonstrated by the output of the variables.

Timeline of the for-loop syntax in various programming languages

[edit]

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.

1957: FORTRAN

[edit]

Fortran's equivalent of the for loop is the DO loop, using the keyword do instead of for, The syntax of Fortran's DO loop is:

        DO label counter = first, last, step
          statements
label     statement

The following two examples behave equivalently to the three argument for-loop in other languages, initializing the counter variable to 1, incrementing by 1 each iteration of the loop, and stopping at five (inclusive).

        DO 9, COUNTER = 1, 5, 1
          WRITE (6,8) COUNTER
    8     FORMAT( I2 )
    9   CONTINUE

In Fortran 77 (or later), this may also be written as:

do counter = 1, 5
  write(*, '(i2)') counter
end do

The step part may be omitted if the step is one. Example:

* DO loop example.
       PROGRAM MAIN
         SUM SQ = 0
         DO 199 I = 1, 9999999
           IF (SUM SQ.GT.1000) GO TO 200
199        SUM SQ = SUM SQ + I**2
200      PRINT 206, SUMSQ
206      FORMAT( I2 )
       END

Spaces are irrelevant in fixed-form Fortran statements, thus SUM SQ is the same as SUMSQ. In the modern free-form Fortran style, blanks are significant.

In Fortran 90, the GO TO may be avoided by using an EXIT statement.

* DO loop example.
       program main
         implicit none

         integer:: sums
         integer:: i

         sums = 0
         do i = 1, 9999999
           if (sums > 1000.0) exit
           sums = sums + i**2
          end do
         print *, sums

       end program

1958: ALGOL

[edit]

ALGOL 58 introduced the for statement, using the form as Superplan:

 FOR Identifier = Base (Difference) Limit

For example to print 0 to 10 incremented by 1:

FOR x = 0 (1) 10 BEGIN
PRINT (FL) = x END

1960: COBOL

[edit]

COBOL was formalized in late 1959 and has had many elaborations. It uses the PERFORM verb which has many options. Originally all loops had to be out-of-line with the iterated code occupying a separate paragraph. Ignoring the need for declaring and initializing variables, the COBOL equivalent of a for-loop would be.

      PERFORM SQ-ROUTINE VARYING I FROM 1 BY 1 UNTIL I > 1000

      SQ-ROUTINE
             ADD I**2 TO SUM-SQ.

In the 1980s, the addition of in-line loops and structured programming statements such as END-PERFORM resulted in a for-loop with a more familiar structure.

      PERFORM VARYING I FROM 1 BY 1 UNTIL I > 1000
             ADD I**2 TO SUM-SQ.
      END-PERFORM

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.

1964: BASIC

[edit]

In BASIC, a loop is sometimes named a for-next loop.

10 REM THIS FOR LOOP PRINTS ODD NUMBERS FROM 1 TO 15
20 FOR I = 1 TO 15 STEP 2
30 PRINT I
40 NEXT I

The end-loop marker specifies the name of the index variable, which must correspond to the name of the index variable at the start of the for-loop. Some languages (PL/I, Fortran 95, and later) allow a statement label at 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.

1964: PL/I

[edit]
do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */
  /*statements*/;
  end;

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.

1968: ALGOL 68

[edit]

ALGOL 68 has what was considered the universal loop, the full syntax is:

FOR i FROM 1 BY 2 TO 3 WHILE i≠4 DO ~ OD

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:
INT sum sq := 0;
FOR i
 WHILE
  print(("So far:", i, new line)); # Interposed for tracing purposes. #
  sum sq ≠ 70↑2                    # This is the test for the WHILE   #
DO
  sum sq +:= i↑2
OD

Subsequent extensions to the standard ALGOL 68 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.

1970: Pascal

[edit]
for Counter:= 1 to 5 do
  (*statement*);

Decrementing (counting backwards) is using downto keyword instead of to, as in:

for Counter:= 5 down to 1 do
  (*statement*);

The numeric range for-loop varies somewhat more.

1972: C, C++

[edit]
for (initialization; condition; increment/decrement)
    statement

The statement is often a block statement; an example of this would be:

//Using for-loops to add numbers 1 - 5
int sum = 0;
for (int i = 1; i <= 5; ++i) {
    sum += i;
}

The ISO/IEC 9899:1999 publication (commonly known as C99) also allows initial declarations in for loops. All three sections in the for loop are optional, with an empty condition equivalent to true.

1972: Smalltalk

[edit]
1 to: 5 do: [ :counter | "statements" ]

Contrary to other languages, in Smalltalk a for-loop is not a language construct but is defined in the class Number as a method with two parameters, the end value and a closure, using self as start value.

1980: Ada

[edit]
for Counter in 1 .. 5 loop
   -- statements
end loop;

The exit statement may be used to exit the loop. Loops can be labeled, and exit may leave a specifically labeled loop in a group of nested loops:

Counting:
    For Counter in 1 .. 5 loop
   Triangle:
       for Secondary_Index in 2 .. Counter loop
          -- statements
          exit Counting;
          -- statements
       end loop Triangle;
    end loop Counting;

1980: Maple

[edit]

Maple has two forms of for-loop, one for iterating over a range of values, and the other for iterating over the contents of a container. The value range form is as follows:

for i from f by b to t while w do
    # loop body
od;

All parts except do and od are optional. The for I part, if present, must come first. The remaining parts (from f, by b, to t, while w) can appear in any order.

Iterating over a container is done using this form of loop:

for e in c while w do
    # loop body
od;

The in c clause specifies the container, which may be a list, set, sum, product, unevaluated function, array, or object implementing an iterator.

A for-loop may be terminated by od, end, or end do.

1982: Maxima CAS

[edit]

In Maxima CAS, one can use also integer values:

for x:0.5 step 0.1 thru 0.9 do
    /* "Do something with x" */

1982: PostScript

[edit]

The for-loop, written as [initial] [increment] [limit] { ... } for initializes an internal variable, and executes the body as long as the internal variable is not more than the limit (or not less, if the increment is negative) and, at the end of each iteration, increments the internal variable. Before each iteration, the value of the internal variable is pushed onto the stack.[6]

1 1 6 {STATEMENTS} for

There is also a simple repeat loop. The repeat-loop, written as X { ... } repeat, repeats the body exactly X times.[7]

5 { STATEMENTS } repeat

1983: Ada 83 and above

[edit]
procedure Main is
  Sum_Sq : Integer := 0;
begin
  for I in 1 .. 9999999 loop
    if Sum_Sq <= 1000 then
      Sum_Sq := Sum_Sq + I**2
    end if;
  end loop;
end;

1984: MATLAB

[edit]
for n = 1:5
     -- statements
end

After the loop, n would be 5 in this example.

As i is used for the Imaginary unit, its use as a loop variable is discouraged.

1987: Perl

[edit]
for ($counter = 1; $counter <= 5; $counter++) { # implicitly or predefined variable
    # statements;
}
for (my $counter = 1; $counter <= 5; $counter++) { # variable private to the loop
    # statements;
}
for (1..5) { # variable implicitly called $_; 1..5 creates a list of these 5 elements
    # statements;
}
statement for 1..5; # almost same (only 1 statement) with natural language order
for my $counter (1..5) { # variable private to the loop
    # statements;
}

"There's more than one way to do it" is a Perl programming motto.

1988: Mathematica

[edit]

The construct corresponding to most other languages' for-loop is named Do in Mathematica.

Do[f[x], {x, 0, 1, 0.1}]

Mathematica also has a For construct that mimics the for-loop of C-like languages.

For[x= 0 , x <= 1, x += 0.1,
    f[x]
]

1989: Bash

[edit]
# first form
for i in 1 2 3 4 5
do
    # must have at least one command in a loop
    echo $i  # just print the value of i
done
# second form
for (( i = 1; i <= 5; i++ ))
do
    # must have at least one command in a loop
    echo $i  # just print the value of i
done

An empty loop (i.e., one with no commands between do and done) is a syntax error. If the above loops contained only comments, execution would result in the message "syntax error near unexpected token 'done'".

1990: Haskell

[edit]

The built-in imperative forM_ maps a monadic expression into a list, as

forM_ [1..5] $ \indx -> do statements

or get each iteration result as a list in

statements_result_list <- forM [1..5] $ \indx -> do statements

But, to save the space of the [1..5] list, a more authentic monadic forLoop_ construction can be defined as

import Control.Monad as M

forLoopM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forLoopM_ indx prop incr f = do
        f index
        M.when (prop next) $ forLoopM_ next prop incr f
  where
    next = incur index

and used as:

  forLoopM_ (0::Int) (< len) (+1) $ \indx -> do -- whatever with the index

1991: Oberon-2, Oberon-07, Component Pascal

[edit]
FOR Counter:= 1 TO 5 DO
  (* statement sequence *)
END

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.

1991: Python

[edit]

Python does not contain the classical for loop, rather a foreach loop is used to iterate over the output of the built-in range() function which returns an iterable sequence of integers.

for i in range(1, 6):  # gives i values from 1 to 5 inclusive (but not 6)
    # statements
    print(i)
# if we want 6 we must do the following
for i in range(1, 6 + 1):  # gives i values from 1 to 6
    # statements
    print(i)

Using range(6) would run the loop from 0 to 5.

1993: AppleScript

[edit]
repeat with i from 1 to 5
	-- statements
	log i
end repeat

It can also iterate through a list of items, similar to what can be done with arrays in other languages:

set x to {1, "waffles", "bacon", 5.1, false}
repeat with i in x
	log i
end repeat

A exit repeat may also be used to exit a loop at any time. Unlike other languages, AppleScript currently has no command to continue to the next iteration of a loop.

1993: Crystal

[edit]
for i = start, stop, interval do
  -- statements
end

So, this code

for i = 1, 5, 2 do
  print(i)
end

will print:

1 3 5

For-loops can also loop through a table using

ipairs()

to iterate numerically through arrays and

pairs()

to iterate randomly through dictionaries.

Generic for-loop making use of closures:

for name, phone, and address in contacts() do
  -- contacts() must be an iterator function
end

1995: ColdFusion Markup Language (CFML)

[edit]

Script syntax

[edit]

Simple index loop:

for (i = 1; i <= 5; i++) {
	// statements
}

Using an array:

for (i in [1,2,3,4,5]) {
	// statements
}

Using a list of string values:

loop index="i" list="1;2,3;4,5" delimiters=",;" {
	// statements
}

The above list example is only available in the dialect of CFML used by Lucee and Railo.

Tag syntax

[edit]

Simple index loop:

<cfloop index="i" from="1" to="5">
	<!--- statements --->
</cfloop>

Using an array:

<cfloop index="i" array="#[1,2,3,4,5]#">
	<!--- statements --->
</cfloop>

Using a "list" of string values:

<cfloop index="i" list="1;2,3;4,5" delimiters=",;">
	<!--- statements --->
</cfloop>

1995: Java

[edit]
for (int i = 0; i < 5; i++) {
    //perform functions within the loop;
    //can use the statement 'break;' to exit early;
    //can use the statement 'continue;' to skip the current iteration
}

For the extended for-loop, see Foreach loop § Java.

1995: JavaScript

[edit]

JavaScript supports C-style "three-expression" loops. The break and continue statements are supported inside loops.

for (var i = 0; i < 5; i++) {
    // ...
}

Alternatively, it is possible to iterate over all keys of an array.

for (var key in array) {  // also works for assoc. arrays
    // use array[key]
    ...
}

1995: PHP

[edit]

This prints out a triangle of *

for ($i = 0; $i <= 5; $i++) {
    for ($j = 0; $j <= $i; $j++) {
        echo "*";
    }
    echo "<br />\n";
}

1995: Ruby

[edit]
for the counter in 1..5
  # statements
end

5.times do |counter|  # counter iterates from 0 to 4
  # statements
end

1.upto(5) do |counter|
  # statements
end

Ruby has several possible syntaxes, including the above samples.

1996: OCaml

[edit]

See expression syntax.[8]

 (* for_statement:= "for" ident '='  expr  ( "to" ∣  "down to" ) expr "do" expr "done" *)

for i = 1 to 5 do
    (* statements *)
  done ;;

for j = 5 down to 0 do
    (* statements *)
  done ;;

1998: ActionScript 3

[edit]
for (var counter:uint = 1; counter <= 5; counter++){
    //statement;
}

2008: Small Basic

[edit]
For i = 1 To 10
    ' Statements
EndFor

2008: Nim

[edit]

Nim has a foreach-type loop and various operations for creating iterators.[9]

for i in 5 .. 10:
  # statements

2009: Go

[edit]
for i := 0; i <= 10; i++ {
    // statements
}

2010: Rust

[edit]
for i in 0..10 {
    // statements
}

2012: Julia

[edit]
for j = 1:10
    # statements
end

See also

[edit]

References

[edit]
  1. ^ Wirth, Niklaus (1973). "Preface". Systematic Programming: An Introduction. Prentice-Hall. pp. xiii. ISBN 0138803692.
  2. ^ "For loops in C++". Learn C++.
  3. ^ Thompson, Ken. VCF East 2019 – Brian Kernighan interviews Ken Thompson. YouTube. Archived from the original on 2021-12-12. Retrieved 2020-11-16. I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it.
  4. ^ http://www.knosof.co.uk/vulnerabilities/loopcntrl.pdf Analysis of loop control variables in C
  5. ^ "Compiler Warning (level 4) C4127". Microsoft. Retrieved 29 June 2011.
  6. ^ PostScript Language Reference. Addison-Wesley Publishing Company. 1999. p. 596. ISBN 0-201-37922-8.
  7. ^ "PostScript Tutorial - Loops".
  8. ^ "OCaml expression syntax". Archived from the original on 2013-04-12. Retrieved 2013-03-19.
  9. ^ https://nim-lang.org/docs/system.html#...i%2CT%2CT ".. iterator"