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 that is 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 "", while descendants of Fortran use "". There are other possibilities, for example COBOL which uses .
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 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 is used for the same thing and it is named a do-loop; this is different from a do while loop.
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:
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:
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 of 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.
for (int i=0; i<100; i++)System.out.println;
These loops are also sometimes named numeric for-loops when contrasted with foreach loops (see below).
This type of for-loop is a generalisation 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:
Where 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, as well as a three-expression for-loop (see below) under the name .
Some languages offer a for-loop that acts as if processing all iterations in parallel, such as the 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 statement in the following pseudocode fragment, when calculating the new value for, except for the first (with) the reference to will obtain the new value that had been placed there in the previous step. In the version, however, each calculation refers only to the original, unaltered . 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 would set all elements of array A to zero, no matter its size or dimensionality. The example loop could be rendered as
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.
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 (example., starting at 0 and end at 10 in increments of 1)
Loop counters change with each iteration of a loop, providing a unique value for each individual 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, 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]
An example of C code involving nested for loops, where the loop counter variables are i and j:
For loops in C can also be used to print the reverse of a word. 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. 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 loops to avoid a type conversion warning in some C/C++ compilers.[5] Some programmers prefer the more succinct form over the semantically equivalent but more verbose form.
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. 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 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:
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 optimization settings, as with the Honywell 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:
A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in in sixteen-bit integer arithmetic) and with each iteration decrement this count while also adjusting the value of : double counting results. However, adjustments to the value of 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 on each iteration. Again, modifications of would not affect the control of the loop, but now a disjunction is possible: within the loop, references to the value of might be to the (possibly altered) current value of or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if 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 instead. It is best to avoid such possibilities.
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, and and the calculation of an iteration count via something like 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 changed.
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:
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.
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.
Fortran's equivalent of the loop is the loop,using the keyword do instead of for,The syntax of Fortran's loop is:
PROGRAM MAIN SUM SQ = 0 DO 199 I = 1, 9999999 IF (SUM SQ.GT.1000) GO TO 200199 SUM SQ = SUM SQ + I**2200 PRINT 206, SUMSQ206 FORMAT(I2) ENDSpaces are irrelevant in fixed-form Fortran statements, thus is the same as . In the modern free-form Fortran style, blanks are significant.
In Fortran 90, the may be avoided by using an statement.
program main implicit none
integer :: sumsq integer :: i
sumsq = 0 do i = 1, 9999999 if (sumsq > 1000.0) exit sumsq = sumsq + i**2 end do print *, sumsq
end program
ALGOL 58 introduced the 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
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 initialising variables, the COBOL equivalent of a for-loop would be.
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.
In BASIC, a loop is sometimes named a for-next loop.
The 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 statement to terminate the current loop iteration and begin the next.
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
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 syntactic element to be replaced with and to achieve a small optimization. The same compilers also incorporated:
Decrementing (counting backwards) is using keyword instead of, as in:
The numeric-range for-loop varies somewhat more.
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:
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:
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 an object implementing an iterator.
A for-loop may be terminated by '''od'''
, '''end'''
, or '''end do'''
.
In Maxima CAS, one can use also non integer values:
The for-loop, written as 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.[6]
As is used for the Imaginary unit, its use as a loop variable is discouraged.
"There's more than one way to do it" is a Perl programming motto.
The construct corresponding to most other languages' for-loop is named Do in Mathematica.
Mathematica also has a For construct that mimics the for-loop of C-like languages
for i in 1 2 3 4 5do # must have at least one command in loop echo $i # just print value of idone
for ((i = 1; i <= 5; i++))do # must have at least one command in loop echo $i # just print value of idone
An empty loop (i.e., one with no commands between and) is a syntax error. If the above loops contained only comments, execution would result in the message "syntax error near unexpected token 'done'".
The built-in imperative forM_ maps a monadic expression into a list, as
or get each iteration result as a list in
But, to save the space of the [1..5] list,a more authentic monadic forLoop_ construction can be defined as
forLoopM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m) -> m forLoopM_ indx prop incr f = do f indx M.when (prop next) $ forLoopM_ next prop incr f where next = incr indxand used as:
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 + 1): # gives i values from 1 to 6 # statements print(i)Using range(6)
would run the loop from 0 to 5.
It can also iterate through a list of items, similar to what can be done with arrays in other languages:
A 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.
So, this code
For-loops can also loop through a table using
Simple index loop:
Using an array:
Using a list of string values:
The above example is only available in the dialect of CFML used by Lucee and Railo.
Simple index loop:
Using an array:
Using a "list" of string values:
For the extended for-loop, see .
JavaScript supports C-style "three-expression" loops. The and statements are supported inside loops.
Alternatively, it is possible to iterate over all keys of an array.
This prints out a triangle of *
5.times do |counter| # counter iterates from 0 to 4 # statementsend
1.upto(5) do |counter| # statementsendRuby has several possible syntaxes, including the above samples.
See expression syntax.[8]
for i = 1 to 5 do (* statements *) done ;;
for j = 5 downto 0 do (* statements *) done ;;
Nim has a foreach
-type loop and various operations for creating iterators.[9]