
In
computer science
Computer science is the study of computation, information, and automation. Computer science spans Theoretical computer science, theoretical disciplines (such as algorithms, theory of computation, and information theory) to Applied science, ...
, a for-loop or for loop is a
control flow
In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an '' ...
statement for specifying
iteration
Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next 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
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
use "", while descendants of
Fortran use "". There are other possibilities, for example
COBOL
COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural, and, since 2002, object-oriented language. COBOL is primarily ...
which uses .
The name ''for-loop'' comes from the word
for. ''For'' is used as the
reserved word
In a programming language, a reserved word (sometimes known as a reserved identifier) is a word that cannot be used by a programmer as an identifier, such as the name of a variable, function, or label – it is "reserved from use". In brief, an '' ...
(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
ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a ...
. It is the direct translation of the earlier German and was used in
Superplan (1949–1951) by
Heinz Rutishauser
Heinz Rutishauser (30 January 1918 – 10 November 1970) was a Swiss people, Swiss mathematician and a pioneer of modern numerical mathematics and computer science.
Life
Rutishauser's father died when he was 13 years old and his mother died t ...
. Rutishauser was involved in defining ALGOL 58 and ALGOL 60. The loop body is executed "for" the given values of the loop variable. This is more explicit in
ALGOL
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
versions of the for statement where a list of possible values and increments can be specified.
In Fortran and
PL/I
PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
, the keyword is used for the same thing and it is named a ''do-loop''; this is different from a ''
do while loop
In many computer programming Programming language, languages, a do while loop is a control flow Statement (computer science), statement that executes a block of code and then either repeats the block or exits the loop depending on a given Boolea ...
''.
FOR

A for-loop statement is available in most
imperative programming
In computer science, imperative programming is a programming paradigm of software that uses Statement (computer science), statements that change a program's state (computer science), state. In much the same way that the imperative mood in natural ...
languages. Even ignoring minor differences in
syntax
In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
, 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
The for-loop of languages like
ALGOL
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
,
Simula
Simula is the name of two simulation programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard. Syntactically, it is an approximate superset of AL ...
,
BASIC
Basic or BASIC may refer to:
Science and technology
* BASIC, a computer programming language
* Basic (chemistry), having the properties of a base
* Basic access authentication, in HTTP
Entertainment
* Basic (film), ''Basic'' (film), a 2003 film
...
,
Pascal,
Modula
The Modula programming language is a descendant of the Pascal language. It was developed in Switzerland, at ETH Zurich, in the mid-1970s by Niklaus Wirth, the same person who designed Pascal. The main innovation of Modula over Pascal is a mo ...
,
Oberon
Oberon () is a king of the fairy, fairies in Middle Ages, medieval and Renaissance literature. He is best known as a character in William Shakespeare's play ''A Midsummer Night's Dream'', in which he is King of the Fairies and spouse of Titania ...
,
Ada,
MATLAB
MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementat ...
,
OCaml
OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
,
F#, and so on, requires a
control variable
A control variable (or scientific constant) in scientific experimentation is an experimental element which is constant (controlled) and unchanged throughout the course of the investigation. Control variables could strongly influence experimental ...
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 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
C (''pronounced'' '' – like the letter c'') is a general-purpose programming language. It was created in the 1970s by Dennis Ritchie and remains very widely used and influential. By design, C's features cleanly reflect the capabilities o ...
. It requires 3 parts: the
initialization (
loop variant), the
condition, and the advancement to the next iteration. All these three parts are optional. This type of "semicolon loops" came from
B programming language and it was originally invented by
Stephen Johnson.
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
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
.
// Prints the numbers from 0 to 99 (and not 100), each followed by a space.
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).
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 computer programming, an iterator is an object that progressively provides access to each item of a collection, in order.
A collection may provide multiple iterators via its interface that provide items in different orders, such as forwards ...
, 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 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 , as well as a three-expression for-loop (see below) under the name .
Vectorised for-loops
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) :=
(i - 1) + A(i) + A(i + 1)/ 3; next i;
for all i := 2 : N - 1 do A(i) :=
(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
A(2 : N - 1) := (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
Introduced with
ALGOL 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative programming language member of the ALGOL family that was conceived as a successor to the ALGOL 60 language, designed with the goal of a much wider scope of application and ...
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
In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, a loop counter is a control variable that controls the iterations of a loop (a computer
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
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
In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types, functions, and other entities in source code and documentation.
Reasons for using a nam ...
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
Mathematical notation consists of using glossary of mathematical symbols, symbols for representing operation (mathematics), operations, unspecified numbers, relation (mathematics), relations, and any other mathematical objects and assembling ...
where
indices for
sums and
multiplication
Multiplication is one of the four elementary mathematical operations of arithmetic, with the other ones being addition, subtraction, and division (mathematics), division. The result of a multiplication operation is called a ''Product (mathem ...
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.
Example
An example of C code involving nested for loops, where the loop counter variables are i and j:
for (i = 0; i < 100; i++)
Loops in C can also be used to print the reverse of a word. As:
for (i = 0; i < 6; i++)
for (i = 4; i >= 0; i--)
Here, if the input is , the output will be .
Additional semantics and constructs
Use as infinite loops
This C-style for-loop is commonly the source of an
infinite loop
In computer programming, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs, such as turning off power via a switch or pulling a plug. It may be inte ...
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 loops to avoid a type conversion warning in some C/C++ compilers. Some programmers prefer the more succinct form over the semantically equivalent but more verbose form.
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 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.
ellsOther languages may have similar statements or otherwise provide means to alter the for-loop progress; for example in Fortran 90:
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 constructs so that with multiple nested loops there is no doubt as to which loop is involved. Fortran 90, 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
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
In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
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
In computer programming, a function (also procedure, method, subroutine, routine, or subprogram) is a callable unit of software logic that has a well-defined interface and behavior and can be invoked multiple times.
Callable units provide a ...
, make it very difficult to check because the routine's behavior is in general unknowable to the compiler unless the language supports procedure signatures and argument intents. Some examples in the style of pre-Fortran-90:
DO I = 1, N
I = 7 !Overt adjustment of the loop variable. Compiler should complain
Z = ADJUST(I) !Function "ADJUST" might alter "I", to uncertain effect.
PRINT *, (A(I), B(I), I = 1, N, 2) !Implicit for-loop to print odd elements of arrays A and B, reusing "I"... Compiler should complain.
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 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.
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
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.
List of value ranges
ALGOL 60, 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
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
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
Fortran's equivalent of the loop is the loop,
using the keyword do instead of for,
The syntax of Fortran's 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, ICOUNT = 1, 5, 1
WRITE (6,8) ICOUNT
8 FORMAT( I2 )
9 CONTINUE
As of Fortran 90, block structured was added to the language. With this, the end of loop label became optional:
do icounter = 1, 5
write(*, '(i2)') icounter
end do
The step part may be omitted if the step is one. Example:
* DO loop example.
PROGRAM MAIN
INTEGER SUMSQ
SUMSQ = 0
DO 199 I = 1, 9999999
IF (SUMSQ.GT.1000) GO TO 200
199 SUMSQ = SUMSQ + I**2
200 PRINT 206, SUMSQ
206 FORMAT( I2 )
END
In Fortran 90, the may be avoided by using an statement.
* DO loop example.
program main
implicit none
integer:: sumsq
integer:: i
sumsq = 0
do i = 1, 9999999
if (sumsq > 1000) exit
sumsq = sumsq + i**2
end do
print *, sumsq
end program
Alternatively, a construct could be used:
program main
implicit none
integer:: sumsq
integer:: i
sumsq = 0
i = 0
do while (sumsq <= 1000)
i = i+1
sumsq = sumsq + i**2
end do
print *, sumsq
end program
1958: ALGOL
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
1960: COBOL
COBOL
COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural, and, since 2002, object-oriented language. COBOL is primarily ...
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 Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making specific disciplined use of the structured control flow constructs of selection ( if/then/else) and repet ...
'' 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
In
BASIC
Basic or BASIC may refer to:
Science and technology
* BASIC, a computer programming language
* Basic (chemistry), having the properties of a base
* Basic access authentication, in HTTP
Entertainment
* Basic (film), ''Basic'' (film), a 2003 film
...
, 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 and 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
do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */
/*statements*/;
end;
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.
1968: ALGOL 68
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 portion was compulsory, in which case the loop will iterate indefinitely.
* thus the clause , will iterate exactly 100 times.
* The ''syntactic element'' allowed a programmer to break from a 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 syntactic element to be replaced with and to achieve a small optimization. The same compilers also incorporated:
;: for late loop termination.
;: for working on arrays in
parallel.
1970: Pascal
for Counter:= 1 to 5 do
(*statement*);
Decrementing (counting backwards) is using keyword instead of , as in:
for Counter:= 5 down to 1 do
(*statement*);
The numeric range for-loop varies somewhat more.
1972: C, C++
for (initialization; condition; increment/decrement)
statement
The 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)
The ISO/IEC 9899:1999 publication (commonly known as
C99) also allows initial declarations in loops. All three sections in the for loop are optional, with an empty condition equivalent to true.
1972: Smalltalk
1 to: 5 do: "statements" /syntaxhighlight>
Contrary to other languages, in Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
a for-loop is not a language construct
In computer programming, 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 the programming language", as defined by in the ISO/IEC 2382 stan ...
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
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
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
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
The for-loop, written as 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.
1 1 6 for
There is also a simple repeat loop.
The repeat-loop, written as , repeats the body exactly X times.
5 repeat
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
end if;
end loop;
end;
1984: MATLAB
for n = 1:5
-- statements
end
After the loop, would be 5 in this example.
As is used for the Imaginary unit
The imaginary unit or unit imaginary number () is a mathematical constant that is a solution to the quadratic equation Although there is no real number with this property, can be used to extend the real numbers to what are called complex num ...
, its use as a loop variable is discouraged.
1987: Perl
for ($counter = 1; $counter <= 5; $counter++)
for (my $counter = 1; $counter <= 5; $counter++)
for (1..5)
statement for 1..5; # almost same (only 1 statement) with natural language order
for my $counter (1..5)
"There's more than one way to do it
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed b ...
" is a Perl programming motto.
1988: Mathematica
The construct corresponding to most other languages' for-loop is named ''Do'' in Mathematica.
Do [x ">[x.html" ;"title="[x">[x
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
# 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 and ) 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
In Haskell98, the function ''mapM_'' maps a monadic function over a list, as
mapM_ print , 3 .. 1-- prints
-- 4
-- 3
-- 2
-- 1
The function ''mapM'' collects each iteration result in a list:
result_list <- mapM (\ indx -> do) ..4-- prints
-- 1
-- 2
-- 3
-- 4
-- result_list is ,1,2,3,4
Haskell2010 adds functions ''forM_'' and ''forM'', which are equivalent to ''mapM_'' and ''mapM'', but with their arguments flipped:
forM_ ..3$ \ indx -> do
print indx
-- prints
-- 0
-- 1
-- 2
-- 3
result_list <- forM a'..'d'$ \ indx -> do
print indx
return indx
-- prints
-- 'a'
-- 'b'
-- 'c'
-- 'd'
-- result_list is a','b','c','d'
When compiled with optimization, none of the expressions above will create lists. But, to save the space of the ..5list if optimization is turned off, a ''forLoop_'' function could be defined as
import Control.Monad as M
forLoop_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forLoop_ startIndx test next f = theLoop startIndx
where
theLoop indx = M.when (test indx) $ do
f indx
theLoop (next indx)
and used as
forLoopM_ (0::Int) (< len) (+1) $ \indx -> do
-- statements
1991: Oberon-2, Oberon-07, Component Pascal
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
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.
When the loop variable is not needed, it is common practice to use an underscore (_
) as a placeholder. This convention signals to other developers that the variable will not be used inside the loop. For example:
for _ in range(5):
print("Hello")
This will print “Hello” five times without using the loop variable.
1993: AppleScript
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
repeat with i in x
log i
end repeat
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.
1993: Crystal
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)
Script syntax
Simple index loop:
for (i = 1; i <= 5; i++)
Using an array:
for (i in ,2,3,4,5
Using a list of string values:
loop index="i" list="1;2,3;4,5" delimiters=",;"
The above example is only available in the dialect of CFML used by Lucee and Railo.
Tag syntax
Simple index loop:
Using an array:
,2,3,4,5">
Using a "list" of string values:
1995: Java
for (int i = 0; i < 5; i++)
For the extended for-loop, see .
1995: JavaScript
JavaScript supports C-style "three-expression" loops. The and 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)
1995: PHP
This prints out a triangle of *
for ($i = 0; $i <= 5; $i++)
1995: Ruby
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
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
has several possible syntaxes, including the above samples.
1996: OCaml
See expression syntax.
(* 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
for (var counter:uint = 1; counter <= 5; counter++)
2008: Small Basic
For i = 1 To 10
' Statements
EndFor
2008: Nim
Nim has a foreach
-type loop and various operations for creating iterators.[https://nim-lang.org/docs/system.html#...i%2CT%2CT ".. iterator"]
for i in 5 .. 10:
# statements
2009: Go
for i := 0; i <= 10; i++
2010: Rust
for i in 0..10
2012: Julia
for j = 1:10
# statements
end
See also
* Do while loop
In many computer programming Programming language, languages, a do while loop is a control flow Statement (computer science), statement that executes a block of code and then either repeats the block or exits the loop depending on a given Boolea ...
* Foreach
In computer programming, foreach loop (or for-each loop) is a control flow statement for traversing items in a collection. is usually used in place of a standard loop statement. Unlike other loop constructs, however, loops usually maintai ...
* While loop
In most computer programming languages, a while loop is a control flow Statement (computer science), statement that allows code to be executed repeatedly based on a given Boolean data type, Boolean condition. The ''while'' loop can be thought o ...
* Primitive recursive function
In computability theory, a primitive recursive function is, roughly speaking, a function that can be computed by a computer program whose loops are all "for" loops (that is, an upper bound of the number of iterations of every loop is fixed befor ...
* General recursive function
In mathematical logic and computer science, a general recursive function, partial recursive function, or μ-recursive function is a partial function from natural numbers to natural numbers that is "computable" in an intuitive sense – as well as i ...
References
{{Reflist
Control flow
Iteration in programming
Programming language comparisons
Articles with example Ada code
Articles with example ALGOL 68 code
Articles with example BASIC code
Articles with example C code
Articles with example C++ code
Articles with example Fortran code
Articles with example Haskell code
Articles with example Java code
Articles with example JavaScript code
Articles with example Julia code
Articles with example MATLAB/Octave code
Articles with example OCaml code
Articles with example Pascal code
Articles with example Perl code
Articles with example PHP code
Articles with example Python (programming language) code
Articles with example Ruby code
Articles with example Rust code
Articles with example Smalltalk code