For loop
From Wikipedia, the free encyclopedia
In most imperative computer programming languages, a for loop is a control flow statement which allows code to be executed iteratively.
Unlike many other kinds of loops, such as the while loop, the for loop is 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.
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. In FORTRAN though, the keyword DO is used and it is called a do loop, but it is otherwise identical to the for loop described here.
Contents |
[edit] Kinds of for loops
A for loop statement is available in many programming languages, yet even ignoring minor differences in syntax, there are many differences in how these statements work and what level of expressiveness they allow. Generally, for loops in programming languages fall into one of the following categories:
[edit] Numeric ranges
This type of for loop is characterized by counting; 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 two's or to count backwards for instance). A representative example in BASIC is:
FOR I = 1 TO 10 loop body NEXT I
The loop variable I will take on the values 1, 2, ..., 9, 10 through each of the ten iterations of the loop's body. Different dialects of BASIC as well as other languages usually have different syntax and means of specifing the range of integers. It is common for the loop variable to be immutable within the scope of the loop body. Some languages may also provide another special statement, usually called a break statement, which can be used within the loop body to allow the loop to be terminated early.
[edit] 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 iterator, 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:
for item in list: loop body
Where the list is either a data collection that supports implicit iteratation, or may in fact itself be an explicit iterator. Some languages have this in addition to another for-loop syntax; notably, PHP has this type of loop under the name foreach
, as well as a three-expression for loop (see below) under the name for
.
[edit] Three-expression for loops
This type of for loop is found in nearly all languages which share a common heritage with the C programming language. 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:
for (counter = 1; counter <= 10; counter++) loop body
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 beginning. 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, and is usually responsible for altering the loop variable.
This type of for loop is usually the most expressive. It is also 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 is often used (with empty expressions), such as:
for (;;) loop body
[edit] Equivalence with while loops
A for loop can always be converted into an equivalent while loop by incrementing a counter variable directly. The following pseudocode illustrates this technique:
factorial := 1 for counter from 1 to 5: factorial := factorial * counter
is easily translated into the following while loop:
factorial := 1 counter := 1 while counter <= 5: factorial := factorial * counter counter := counter + 1
[edit] 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 (example is C):
for(counter = 1; counter <= 5; counter++) statements;
The numeric-range for loop varies somewhat more. Pascal would write it:
for Counter := 1 to 5 do statements;
Whereas Perl would use:
for (1..5) statements;
Iterator for loops most commonly take a form such as this (example is Python):
for counter in range(1, 6): # range() gives values to one less than the second argument statements
But the PHP equivalent (virtually never used for simple repetition but noted here for completeness):
foreach (range(1,5) as $i) statements;
[edit] Timeline of for loop in various programming languages
[edit] 1966: FORTRAN 66
FORTRAN 66's equivalent of the for
loop is the DO
loop. The syntax of Fortran's DO
loop is:
DO label counter=start, stop, step label statements
Example:
PROGRAM MAIN SUM SQ=0 DO 101 I=1,9999999 IF(SUM SQ.GT.1000)GO TO 109 SUM SQ=SUM SQ+I**2 101 CONTINUE 109 CONTINUE END
The fortran DO loop caused a orbit computation error in a Mercury flight, and was long suspected to have caused the crash of the Mariner 1 space rocket on 22 July 1962 - C.A.R. Hoare, in particular a missing comma in the wrong place can drastically alter the meaning of the loop. Example:
DO 101 I=1.9999999 101 CONTINUE
This is actually a single assignment to the undeclared variable DO101I
. In the subsequent FORTRAN 77 specification an additional comma was required in the DO
loop syntax.
[edit] 1968: Algol68
Algol68 has what was considered the universial loop, the full syntax is:
for i from 1 by 1 to 3 while i≠4 do ~ od
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 only 100 times.
- the while "syntatic element" allowed a programmer to break from a for loop early. eg
int sum sq:=0; for i while print(("So far:",i,newline)); sum sq≤1000 do sum sq+:=i↑2 od
Subsequent "extensions" to the standard Algol68 allowed the to syntatic element to be replaced with upto and downto to achieve a small optimisation. The same compilers also incorporated:
- until - for late loop termination.
- foreach - for working on arrays in parallel.
[edit] 1977: FORTRAN 77
FORTRAN 77's equivalent of the for
loop is the DO
loop. The syntax of Fortran's DO
loop is:
DO label, counter=start, stop, step label statements
Example:
PROGRAM MAIN SUM SQ=0 DO 101, I=1,9999999 IF(SUM SQ.GT.1000)GO TO 109 SUM SQ=SUM SQ+I**2 101 CONTINUE 109 CONTINUE END