For loop
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.
Contents |
[edit] 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:
[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 some_iterable_object: doSomething doSomethingElse
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 foreach, as well as a three-expression for loop (see below) under the name for.
[edit] Vectorised for loops
Some languages offer a for loop that acts as if processing all iterations in parallel, such as the forall keyword in Fortran 95 which has the interpretation that all right-hand-side expressions are evaluated before any assignments are made, as distinct from the explicit iteration form. For example, in the for loop in the following pseudocode fragment, when calculating the new value for A(i), except for the first (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.
[edit] Compound for loops
Introduced with ALGOL 68 and followed by PL/I, this allows the iteration of a loop to be compounded with a test, as in
for i:=1:N while A(i) > 0 do etc.
That is, a value is assigned to the loop variable i and only if the while expression is true will the loop body be executed. If the result were false the for-loop's execution stops short. Granted that the loop variable's value is defined after the termination of the loop, then the above statement will find the first non-positive element in array A (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.
[edit] Additional semantics and constructs
[edit] Use as infinite loops
This C-style for loop is commonly the source of an infinite loop since the fundamental steps of iteration are completely in the control of the programmer. In fact, when infinite loops are intended, this type of for loop can be used (with empty expressions), such as:
for (;;) //loop body
This style is used instead of infinite while(1) loops to avoid a warning in Visual C++.[1]
[edit] 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:
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", 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".
[edit] 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.
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:
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 that "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?
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.
[edit] Equivalence with while loops
A for loop can be converted into an equivalent while loop by incrementing a counter variable directly. The following pseudocode illustrates this technique:
factorial = 1
for counter from 1 to 5
factorial = factorial * counter
is easily translated into the following while loop:
factorial = 1
counter = 1
while counter <= 5
factorial = factorial * counter
counter = counter + 1
This translation is slightly complicated by languages which allow a statement to jump to the next iteration of the loop (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.
[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.
[edit] ActionScript 3
for (var counter:int = 1; counter <= 5; counter++) //statement;
[edit] C
for (counter = 1; counter <= 5; counter++) //statement;
[edit] C++ and C
for (int counter = 1; counter <= 5; counter++) //statement;
The ISO/IEC 9899:1999 publication (commonly known as C99) also allows initial declarations in for loops.
[edit] 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).
do counter = 1,5,1 write(*,'(i2)') counter end do
[edit] Java
for(int i = 0; i < 5; i++){ //perform functions within the loop; //can use the statement 'break;' to exit early; }
[edit] Bash
# first form for i in 1 2 3 4 5 do # must have at least one command in loop* echo $i # just print value of i done # second form for (( i = 1; i <= 5; i++ )) do # must have at least one command in loop* echo $i # just print value of i done
*Note: In these above languages, 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'".
[edit] Lua
for i = 1,5 do -- Statements end
variable i can be used in statements or just to make something happen X times, here it's 5
[edit] Pascal
for Counter := 1 to 5 do (*statement*);
The numeric-range for loop varies somewhat more. Pascal would use the above-displayed code, whereas Perl would use the following:
[edit] Perl
for ($counter = 1; $counter <= 5; $counter++) { # statements; }
(Note that for(1..5) { } is really a foreach in Perl.)
[edit] PHP
foreach (range(1,5) as $i) # statements;
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):
[edit] Python
for counter in range(1, 6): # range(1, 6) gives values from 1 inclusive to 6 exclusive # statements
[edit] Ruby
for 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.
[edit] Smalltalk
1 to: 5 do: [ :counter | "statements" ]
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.
[edit] Timeline of the for loop in various programming languages
[edit] 1957: FORTRAN
FORTRAN'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
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)
! DO loop 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
[edit] 1958: Algol
Algol was first formalised in the Algol58 report.
[edit] 1960: COBOL
COBOL was formalised in late 1959 and has had many elaborations. It uses the PERFORM verb which has many options, with the later addition of "structured" statements such as END-PERFORM. Ignoring the need for declaring and initialising variables, the equivalent of a for-loop would be
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 1000 ADD I**2 to SumSQ. 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.
[edit] 1968: Algol 68
Algol68 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 Algol68 allowed the "to" syntactic element to be replaced with "upto" and "downto" to achieve a small optimization. The same compilers also incorporated:
- until - for late loop termination.
- foreach - for working on arrays in parallel.
[edit] 1983: Ada 83 and above
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
[edit] See also
[edit] References
- ^ "Compiler Warning (level 4) C4127". Microsoft. http://msdn.microsoft.com/en-us/library/6t66728h.aspx. Retrieved 29 June 2011.
[edit] External links
| The Wikibook Ada_Programming has a page on the topic of |
- For loop implementation in different languages at Wikia:Code