For loop
Encyclopedia
In computer science
a for loop is a programming language
statement
which allows code to be repeatedly executed
. A for loop is classified as an iteration
statement.
Unlike many other kinds of loops, such as the while loop
, the for loop is often distinguished by an explicit loop counter
or loop variable. This allows the body of the for loop (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 shorthand way to make loops when the number of iterations is known, as a for loop can be written as a while loop.
The name for loop comes from the English word for, which is used as the keyword in most programming languages to introduce a for loop. The loop body is executed "for" the given values of the loop variable, though this is more explicit in the ALGOL
version of the statement, in which a list of possible values and/or increments can be specified.
In FORTRAN
and PL/I
though, the keyword DO is used and it is called a do loop, but it is otherwise identical to the for loop described here and is not to be confused with the Do while loop
.
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:
; enumerating each of the values within a numeric integer range, or arithmetic progression
. The range is often specified by a beginning and ending number, and sometimes may include a step value (allowing one to count by twos or to count backwards for instance). A representative example in BASIC is:
The loop variable
A rarely-available generalisation allows the start stop and step values to be specified as items in a list, not just a single arithmetic sequence. For example, most Unix-like shells (bash, sh, csh, etc.) have two distinct forms of for loop and will readily execute the following script:
, in which the loop variable takes on each of the values in a sequence or other orderable data collection. A representative example in Python
is:
Where
expressions are evaluated before any assignments are made, as distinct from the explicit iteration form. For example, in the
for i:=2:N-1 do A(i):=[A(i-1) + A(i) + A(i+1)]/3; next i;
forall i:=2:N-1 do A(i):=[A(i-1) + A(i) + A(i+1)]/3;
The difference may be significant.
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.
. It is characterized by a three-parameter loop control expression; consisting of an initializer, a loop-test, and a counting expression. A representative example in C is:
The three control expressions, separated by semicolons here, are from left to right the initializer expression, the loop test expression, and the counting expression. The initializer is evaluated exactly once right at the start of the loop. The loop test expression is evaluated at the beginning of each iteration through the loop, and determines when the loop should exit. Finally, the counting expression is evaluated at the end of each loop iteration - even if
In most languages which provide this type of for loop, each of the three control loop expressions is optional.
When omitted the loop test expression is taken to always be true, while the initializer and counting expressions are treated as no-ops
when omitted.
The semicolons in the syntax are sufficient to indicate the omission of one of the expressions. Some examples include:
or this,
Notice that in normal usage, the name of the iteration variable is repeated in each of the three parts. Using a different name in any part is valid syntax, though the resulting behaviour might not be desired.
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 style is used instead of infinite while(1) loops to avoid a warning in Visual C++
.
Common among these are the break and continue statements found in C and its derivatives.
The break statement causes the inner-most loop to be terminated immediately when executed.
The continue statement will move at once to the next iteration without further progress through the loop body for the current iteration.
Other languages may have similar statements or otherwise provide means to alter the for loop progress; for example in Fortran 95:
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.
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 behaviour is in general unknowable to the compiler. Some examples in the style of Fortran:
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. In this case, 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.
illustrates this technique:
factorial = 1
for counter from 1 to 5
factorial = factorial * counter
is easily translated into the following while loop:
factorial = 1
counter = 1
while counter <= 5
factorial = factorial * counter
counter = counter + 1
This translation is slightly complicated by languages which allow a statement to jump to the next iteration of the loop (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.
The ISO/IEC 9899:1999 publication (commonly known as C99
) also allows initial declarations in
* Note: In these above languages, an empty loop (i.e., one with no commands between
variable i can be used in statements or just to make somthing happen X times, here it's 5
The numeric-range for loop varies somewhat more. Pascal would use the above-displayed code, whereas Perl would use the following:
(Note that
The PHP equivalent of the below Python code (virtually never used for simple repetition but noted here for completeness)
Iterator for loops most commonly take a form such as this (example is Python):
Ruby has several possible syntaxes, including the above samples.
Contrary to other languages, in Smalltalk
a for loop is not a language construct
but defined in the class Number as a method with two parameters, the end value and a closure
, using self as start value.
Example: (spaces are irrelevant in fortran statements, thus SUM SQ is the same as SUMSQ)
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.
There are several unusual aspects of the construct
Subsequent extensions to the standard Algol68 allowed the "to" syntactic element to be replaced with "" and "downto" to achieve a small optimization. The same compilers also incorporated:
Computer science
Computer science or computing science is the study of the theoretical foundations of information and computation and of practical techniques for their implementation and application in computer systems...
a for loop is a programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
statement
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...
which allows code to be repeatedly executed
Execution (computers)
Execution in computer and software engineering is the process by which a computer or a virtual machine carries out the instructions of a computer program. The instructions in the program trigger sequences of simple actions on the executing machine...
. A for loop is classified as an iteration
Iteration
Iteration means the act of repeating a process usually with the aim of approaching a desired goal or target or result. Each repetition of the process is also called an "iteration," and the results of one iteration are used as the starting point for the next iteration.-Mathematics:Iteration in...
statement.
Unlike many other kinds of loops, such as the while loop
While loop
In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The while loop can be thought of as a repeating if statement....
, the for loop is often distinguished by an explicit loop counter
Loop counter
In software engineering, a loop counter is the term often used to refer to the variable that controls the iterations of a loop...
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 shorthand way to make loops when the number of iterations is known, as a for loop can be written as a while loop.
The name for loop comes from the English word for, which is used as the keyword in most programming languages to introduce a for loop. The loop body is executed "for" the given values of the loop variable, though this is more explicit in the ALGOL
ALGOL
ALGOL is a family of imperative computer programming languages originally developed in the mid 1950s which greatly influenced many other languages and became the de facto way algorithms were described in textbooks and academic works for almost the next 30 years...
version of the statement, in which a list of possible values and/or increments can be specified.
In FORTRAN
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...
and PL/I
PL/I
PL/I is a procedural, imperative computer programming language designed for scientific, engineering, business and systems programming applications...
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
In most computer programming languages, a do while loop, sometimes just called a do loop, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Note though that unlike most languages, Fortran's do loop is actually analogous to the for loop.The...
.
Kinds of for loops
A for loop statement is available in most imperative programmingImperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
languages. Even ignoring minor differences in syntax
Syntax
In linguistics, syntax is the study of the principles and rules for constructing phrases and sentences in natural languages....
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:
Numeric ranges
This type of for loop is characterized by countingCounting
Counting is the action of finding the number of elements of a finite set of objects. The traditional way of counting consists of continually increasing a counter by a unit for every element of the set, in some order, while marking those elements to avoid visiting the same element more than once,...
; enumerating each of the values within a numeric integer range, or arithmetic progression
Arithmetic progression
In mathematics, an arithmetic progression or arithmetic sequence is a sequence of numbers such that the difference between the consecutive terms is constant...
. The range is often specified by a beginning and ending number, and sometimes may include a step value (allowing one to count by twos or to count backwards for instance). A representative example in BASIC is:
The loop variable
I
will take on the values 1, 2, ..., 9, 10 through each of the ten iterations of the loop's body, which will be executed in that order. Each computer language and even different dialects of the same language (e.g. BASIC) has its own syntax, keywords, and means of specifying the start, stop, and step values. (In the above example, BASIC allows for a step size of 1 to be implied, i.e., "FOR I = 1 TO 10
" behaves identically to "FOR I = 1 TO 10 STEP 1
".)A rarely-available generalisation allows the start stop and step values to be specified as items in a list, not just a single arithmetic sequence. For example, most Unix-like shells (bash, sh, csh, etc.) have two distinct forms of for loop and will readily execute the following script:
Iterator-based for loops
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 iteratorIterator
In computer programming, an iterator is an object that enables a programmer to traverse a container. Various types of iterators are often provided via a container's interface...
, in which the loop variable takes on each of the values in a sequence or other orderable data collection. A representative example in Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
is:
Where
some_iterable_object
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 foreachForeachFor each is a computer language idiom for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set",...
, as well as a three-expression for loop (see below) under the name for
.Vectorised for loops
Some languages offer a for loop that acts as if processing all iterations in parallel, such as theforall
keyword in Fortran 95 which has the interpretation that all right-hand-sideSides of an equation
In mathematics, LHS is informal shorthand for the left-hand side of an equation. Similarly, RHS is the right-hand side. Each is solely a name for a term as part of an expression; and they are in practice interchangeable, since equality is symmetric...
expressions are evaluated before any assignments are made, as distinct from the explicit iteration form. For example, in the
for
loop in the following pseudocode fragment, when calculating the new value for A(i)
, except for the first (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 forall
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;
forall i:=2:N-1 do A(i):=[A(i-1) + A(i) + A(i+1)]/3;
The difference may be significant.
Compound for loops
Introduced with ALGOL 68ALGOL 68
ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...
and followed by PL/I
PL/I
PL/I is a procedural, imperative computer programming language designed for scientific, engineering, business and systems programming applications...
, 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.
Three-expression for loops
This type of for loop is found in nearly all languages which share a common heritage with the C programming languageC (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
. It is characterized by a three-parameter loop control expression; consisting of an initializer, a loop-test, and a counting expression. A representative example in C is:
The three control expressions, separated by semicolons here, are from left to right the initializer expression, the loop test expression, and the counting expression. The initializer is evaluated exactly once right at the start of the loop. The loop test expression is evaluated at the beginning of each iteration through the loop, and determines when the loop should exit. Finally, the counting expression is evaluated at the end of each loop iteration - even if
continue
is called - and is usually responsible for altering the loop variable.In most languages which provide this type of for loop, each of the three control loop expressions is optional.
When omitted the loop test expression is taken to always be true, while the initializer and counting expressions are treated as no-ops
NOP
In computer science, NOP or NOOP is an assembly language instruction, sequence of programming language statements, or computer protocol command that effectively does nothing at all....
when omitted.
The semicolons in the syntax are sufficient to indicate the omission of one of the expressions. Some examples include:
or this,
Notice that in normal usage, the name of the iteration variable is repeated in each of the three parts. Using a different name in any part is valid syntax, though the resulting behaviour might not be desired.
Use as infinite loops
This C-style for loop is commonly the source of an infinite loopInfinite loop
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over...
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 style is used instead of infinite while(1) loops to avoid a warning in Visual C++
Visual C++
Microsoft Visual C++ is a commercial , integrated development environment product from Microsoft for the C, C++, and C++/CLI programming languages...
.
Early exit and continuation
Some languages may also provide other supporting statements, which when present can alter how the for loop iteration proceeds.Common among these are the break and continue statements found in C and its derivatives.
The break statement causes the inner-most loop to be terminated immediately when executed.
The continue statement will move at once to the next iteration without further progress through the loop body for the current iteration.
Other languages may have similar statements or otherwise provide means to alter the for loop progress; for example in Fortran 95:
Loop variable scope and semantics
Different languages specify different rules for what value the loop variable will hold on termination of its loop, and indeed some hold that it "becomes undefined". This permits a compilerCompiler
A compiler is a computer program that transforms source code written in a programming language into another computer language...
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.
In some languages (not C or C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
) the loop variable is immutable
Immutable object
In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created...
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
Subroutine
In computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....
make it very difficult to check, because the routine's behaviour is in general unknowable to the compiler. Some examples in the style of Fortran:
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. In this case, 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.
Equivalence with while loops
A for loop can be converted into an equivalent while loop by incrementing a counter variable directly. The following pseudocodePseudocode
In computer science and numerical computation, pseudocode is a compact and informal high-level description of the operating principle of a computer program or other algorithm. It uses the structural conventions of a programming language, but is intended for human reading rather than machine reading...
illustrates this technique:
factorial = 1
for counter from 1 to 5
factorial = factorial * counter
is easily translated into the following while loop:
factorial = 1
counter = 1
while counter <= 5
factorial = factorial * counter
counter = counter + 1
This translation is slightly complicated by languages which allow a statement to jump to the next iteration of the loop (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.
Syntax
Given an action that must be repeated, for instance, five times, different languages' for loops will be written differently. The syntax for a three-expression for loop is nearly identical in all languages that have it, after accounting for different styles of block termination and so on.ActionScript 3
C++ and C
The ISO/IEC 9899:1999 publication (commonly known as C99
C99
C99 is a modern dialect of the C programming language. It extends the previous version with new linguistic and library features, and helps implementations make better use of available computer hardware and compiler technology.-History:...
) also allows initial declarations in
for
loops.Bash
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'
".Lua
variable i can be used in statements or just to make somthing happen X times, here it's 5
Pascal
The numeric-range for loop varies somewhat more. Pascal would use the above-displayed code, whereas Perl would use the following:
Perl
(Note that
for(1..5) { }
is really a foreach in Perl.)PHP
The PHP equivalent of the below Python code (virtually never used for simple repetition but noted here for completeness)
Iterator for loops most commonly take a form such as this (example is Python):
Python
Ruby
Ruby has several possible syntaxes, including the above samples.
Smalltalk
Contrary to other languages, in Smalltalk
Smalltalk
Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...
a for loop is not a language construct
Language construct
A language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of a programming language....
but defined in the class Number as a method with two parameters, the end value and a closure
Closure
Closure may refer to:* Closure used to seal a bottle, jug, jar, can, or other container** Closure , a stopper* Closure , the process by which an organization ceases operations...
, using self as start value.
1957: FORTRAN
FORTRAN's equivalent of thefor
loop is the DO
loop. The syntax of Fortran's DO
loop is:Example: (spaces are irrelevant in fortran statements, thus SUM SQ is the same as SUMSQ)
1960: COBOL
COBOL was formalised in late 1959 and has had many elaborations. It uses the PERFORM verb which has many options, with the later addition of "structured" statements such as END-PERFORM. Ignoring the need for declaring and initialising variables, the equivalent of a for-loop would beIf the PERFORM verb has the optional clause TEST AFTER, the resulting loop is slightly different: the loop body is executed at least once, before any test.
1968: Algol 68
Algol68 has what was considered the universal loop, the full syntax is:There are several unusual aspects of the construct
- only the "do ~ od" portion was compulsory, in which case the loop will iterate indefinitely.
- thus the clause "to 100 do ~ od", will iterate exactly 100 times.
- the "while" syntactic element allowed a programmer to break from a "for" loop early, as in:
Subsequent extensions to the standard Algol68 allowed the "to" syntactic element to be replaced with "" and "downto" to achieve a small optimization. The same compilers also incorporated:
- until - for late loop termination.
- foreach - for working on arrays in parallelParallel computingParallel computing is a form of computation in which many calculations are carried out simultaneously, operating on the principle that large problems can often be divided into smaller ones, which are then solved concurrently . There are several different forms of parallel computing: bit-level,...
.
1983: Ada 83 and above
External links
- For loop implementation in different languages at Wikia:Code