For loop

From Vero - Wikipedia
Jump to navigation Jump to search

Template:Short description {{SAFESUBST:#invoke:Unsubst||date=__DATE__ |$B= {{#switch: |Category=For categories, please use the templates available at Wikipedia:Categories for discussion. |Template=For templates, please use the templates available at Wikipedia:Templates for discussion. }}Template:Mbox{{#switch: |User|User talk= |#default={{#if:||Template:DMC}} }}Template:Merge partner }}

Error creating thumbnail:
Flow diagram of a for loop that prints five asterisks.

Template:Loop constructs

In computer programming, a for loop is a structured control flow statement that repeatedly runs a section of code until a condition is satisfied.

A for loop has two parts: a header and a body. The header defines how the loop iterates, and the body is the code executed once per iteration. The header often declares a loop variable which can be used in the body to know which iteration of the loop is being executed. A relatively simple for loop iterates for a fixed number of times. For example, the following C for loop declares a loop variable Template:Code and prints its value as it increments from 0 to 1 to 2:

<syntaxhighlight lang="c"> for (int i = 0; i < 3; ++i) {

   printf("%d", i);

} </syntaxhighlight>

Depending on programming language, various keywords are used to denote a for loop. For example, descendants of ALGOL use Template:Code,<ref>Template:Cite book</ref> while descendants of Fortran use Template:Code and COBOL uses Template:Code.

Variations

File:For loop.svg
For loop illustration, from i=0 to i=2, resulting in data1=200

Generally, a for loop falls into one of the following categories:

Numeric

A numeric for loop increments a control variable from a start value to and end value. In languages such as ALGOL, Simula, BASIC, Pascal, Modula, Oberon, Ada, MATLAB, OCaml, and F# it looks like:

<syntaxhighlight Lang="pascal"> for i = first to last do statement </syntaxhighlight>

Some languages support an optional step value (increment or decrement). Some languages require a separate declaration of the control variable.

3 part

A 3-part for loop, popularized by C, has the following parts separated by semi-colons: initialization (loop variant), condition, and advancement to the next value. Each part is optional and can be blank. This syntax came from B programming language and was originally invented by Stephen C. Johnson.<ref name="ken">Template:Cite AV mediaTemplate:Cbignore</ref> In the initialization part, any variables needed are declared and assigned values. The condition part checks a condition and exits the loop if false, even if the loop is never executed. If the condition is true, then the loop's block of is executed. The advancement to the next iteration part is performed each time the block is executed.

The following Java code is a C-style numeric loop that prints the numbers from 0 to 99.

<syntaxhighlight Lang="java"> for (int i = 0; i < 100; ++i) {

   System.out.printf("%d", i );

} </syntaxhighlight>

This form is often used like the numeric for loop, but is more flexible and can be used for other patterns. For example, Template:Code calls functions instead of using a control variable. The pattern of an infinite loop is implemented as Template:Code.

Iterator-based

A foreach loop enumerates the items of a sequence. It is usually uses an implicit or explicit iterator, in which the loop variable represents each value of the sequence. The following Python code shows a foreach loop. Template:Code is either a data collection that supports implicit iteration, or may be an iterator itself.

<syntaxhighlight Lang="python"> for item in items:

   do_something(item)

</syntaxhighlight>

Vectorized

Some languages offer a for loop that acts as if processing all iterations in parallel, such as the Template:Code 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 Template:Code statement in the following pseudocode fragment, when calculating the new value for Template:Code, except for the first (with Template:Code) the reference to Template:Code will obtain the new value that had been placed there in the previous step. In the Template:Code version, however, each calculation refers only to the original, unaltered Template:Code.

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 90) also offer array assignment statements, that enable many for loops to be omitted. Thus pseudocode such as Template:Code would set all elements of array A to zero, no matter its size or dimensionality. The example loop could be rendered as <syntaxhighlight lang="Fortran">

A(2 : N - 1) := [A(1 : N - 2) + A(2 : N - 1) + A(3 : N)] / 3;

</syntaxhighlight> 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.

Numeric & while

Introduced with ALGOL 68 and followed by PL/I, the compound numeric and while for loop iterates while the control value increments (as a numeric for loop) and while a condition is true. If the condition evaluates to false, then the loop exits before the loop variable reaches the last value. In the following code, Template:Code starts at 1 and the loops iterates until either Template:Code is Template:Code or Template:Code is true.

for i := 1 : N while not Done do Something()

Loop counters

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 (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 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 FortranTemplate:Citation needed, 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.<ref>http://www.knosof.co.uk/vulnerabilities/loopcntrl.pdf Analysis of loop control variables in C</ref>

Example

An example of C code involving nested for loops, where the loop counter variables are i and j:

<syntaxhighlight lang="c"> for (int i = 0; i < 100; i++) {

   for (int j = i; j < 10; j++) {
       someFunction(i, j);
   }

} </syntaxhighlight>

Loops in C can also be used to print the reverse of a word. As: <syntaxhighlight lang="c"> for (int i = 0; i < 6; i++) {

   scanf("%c", &a[i]);

} for (int i = 4; i >= 0; i--) {

   printf("%c", a[i]);

} </syntaxhighlight> Here, if the input is Template:Code, the output will be Template:Code.

Additional semantics and constructs

Use as infinite loops

Template:Further A loop turns into an infinite loop when its condition never becomes false. This means the loop keeps running endlessly because it either doesn’t have a proper stopping condition, the termination condition is never met, or the loop is repeatedly instructed to restart from the beginning. <ref>Template:Cite web</ref>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. When infinite loops are intended, this type of for loop can be used (with empty expressions), such as:

<syntaxhighlight lang="c"> for (;;) {

   // loop body

} </syntaxhighlight>

This style is used instead of infinite Template:Code loops to avoid a type conversion warning in some C/C++ compilers.<ref>Template:Cite web</ref> Some programmers prefer the more succinct Template:Code form over the semantically equivalent but more verbose Template:Code 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.[Wells] Other languages may have similar statements or otherwise provide means to alter the for loop progress; for example in Fortran 90:

<syntaxhighlight lang="Fortran"> 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". </syntaxhighlight>

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: <syntaxhighlight lang="Fortran"> X1:DO I = 1, N

    statements
 X2:DO J = 1, M
      statements
      IF (trouble) CYCLE X1
      statements
    END DO X2
    statements
  END DO X1

</syntaxhighlight> 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 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, 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:

<syntaxhighlight lang="Fortran"> 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? </syntaxhighlight>

A common approach is to calculate the iteration count at the start of a loop (with careful attention to overflow as in Template:Code in sixteen-bit integer arithmetic) and with each iteration decrement this count while also adjusting the value of Template:Mono: double counting results. However, adjustments to the value of Template:Mono 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 Template:Mono on each iteration. Again, modifications of Template:Mono would not affect the control of the loop, but now a disjunction is possible: within the loop, references to the value of Template:Mono might be to the (possibly altered) current value of Template:Mono or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element Template:Mono of an array would likely employ the auxiliary variable (especially if it were held in a machine register), but if Template:Mono 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 Template:Mono 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 Template:Mono, Template:Mono and Template:Mono and the calculation of an iteration count via something like Template:Code 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 Template:Code 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: <syntaxhighlight lang="rexx"> do i = 1, 7, 12 to 15;

 /*statements*/

end; </syntaxhighlight>

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

Template:Further Fortran's equivalent of the Template:Mono loop is the Template:Mono loop, using the keyword do instead of for, The syntax of Fortran's Template:Mono loop is: <syntaxhighlight lang="fortranfixed">

       DO label counter = first, last, step
         statements

label statement </syntaxhighlight> 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). <syntaxhighlight lang="fortranfixed">

       DO 9, ICOUNT = 1, 5, 1
         WRITE (6,8) ICOUNT
   8     FORMAT( I2 )
   9   CONTINUE

</syntaxhighlight> As of Fortran 90, block structured Template:Mono was added to the language. With this, the end of loop label became optional: <syntaxhighlight lang="Fortran"> do icounter = 1, 5

 write(*, '(i2)') icounter

end do </syntaxhighlight> The step part may be omitted if the step is one. Example: <syntaxhighlight lang="fortranfixed">

  • 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

</syntaxhighlight>

In Fortran 90, the Template:Mono may be avoided by using an Template:Mono statement. <syntaxhighlight lang="fortranfixed">

  • 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

</syntaxhighlight> Alternatively, a Template:Mono construct could be used: <syntaxhighlight lang="fortranfixed">

      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

</syntaxhighlight>

1958: ALGOL

Template:Further ALGOL 58 introduced the Template:Code statement, using the form as Superplan:

 FOR Identifier = Base (Difference) Limit

For example to print 0 to 10 incremented by 1: <syntaxhighlight lang="pascal"> FOR x = 0 (1) 10 BEGIN PRINT (FL) = x END </syntaxhighlight>

In ALGOL 60 the looping construct was changed. A series of 'for list elements', separated by commas, can be specified. An element can either be an arithmetic expression element, a 'step-until' element, or a 'while' element.

To print from 0 to 10, then the number 42: <syntaxhighlight lang="pascal">

 for x := 0 step 1 until 10, 42 do
   begin
     outinteger (1, x);
     outstring (1, "\n")
   end;

</syntaxhighlight>

A mostly equivalent loop using a 'while' element could be written: <syntaxhighlight lang="pascal">

 for x := 0, x while x <= 10, 42 do
   begin
     outinteger (1, x);
     outstring (1, "\n");
     x := x + 1
   end;

</syntaxhighlight>

Note the value of x after the first loop has completed will be 42, whereas in the second loop it will be 43.

1960: COBOL

Template:Further 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 initializing variables, the COBOL equivalent of a for loop would be.

<syntaxhighlight lang="cobol">

     PERFORM SQ-ROUTINE VARYING I FROM 1 BY 1 UNTIL I > 1000
     SQ-ROUTINE
            ADD I**2 TO SUM-SQ.

</syntaxhighlight>

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.

<syntaxhighlight lang="cobol">

     PERFORM VARYING I FROM 1 BY 1 UNTIL I > 1000
            ADD I**2 TO SUM-SQ.
     END-PERFORM

</syntaxhighlight> 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

Template:Further In BASIC, a loop is sometimes named a for-next loop.

<syntaxhighlight lang="basic"> 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 </syntaxhighlight> 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 Template:Code and Template:Code 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

Template:Further The PL/I DO statement can act as either a for loop, a while loop, or a do until loop. <syntaxhighlight lang="rexx"> do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */

 /*statements*/;
 end;

</syntaxhighlight>

The Template:Mono 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 Template:Mono statement to terminate the current loop iteration and begin the next.

1968: ALGOL 68

Template:Further 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 Template:Code portion was compulsory, in which case the loop will iterate indefinitely.
  • thus the clause Template:Code, will iterate exactly 100 times.
  • The Template:Code syntactic element allowed a programmer to break from a Template:Code loop early, as in:

Template:Pre

Subsequent extensions to the standard ALGOL 68 allowed the Template:Code syntactic element to be replaced with Template:Code and Template:Code to achieve a small optimization. The same compilers also incorporated:

Template:Code
for late loop termination.
Template:Code
for working on arrays in parallel.

1970: Pascal

Template:Further <syntaxhighlight lang="pascal"> for Counter:= 1 to 5 do

 (*statement*);

</syntaxhighlight>

Decrementing (counting backwards) is using Template:Code keyword instead of Template:Code, as in:

<syntaxhighlight lang="pascal"> for Counter:= 5 downto 1 do

 (*statement*);

</syntaxhighlight>

The numeric range for loop varies somewhat more.

1972: C, C++

Template:Further <syntaxhighlight lang="c"> for (initialization; condition; increment/decrement)

   statement

</syntaxhighlight> The Template:Mono is often a block statement; an example of this would be: <syntaxhighlight lang="c"> //Using for loops to add numbers 1 - 5 int sum = 0; for (int i = 1; i <= 5; ++i) {

   sum += i;

} </syntaxhighlight> The ISO/IEC 9899:1999 publication (commonly known as C99) also allows initial declarations in Template:Code loops. All three sections in the for loop are optional, with an empty condition equivalent to true.

1972: Smalltalk

Template:Further <syntaxhighlight lang="smalltalk">1 to: 5 do: [ :counter | "statements" ]</syntaxhighlight> Contrary to other languages, in Smalltalk a for loop is not a language construct 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

Template:Further <syntaxhighlight lang="ada"> for Counter in 1 .. 5 loop

  -- statements

end loop; </syntaxhighlight>

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: <syntaxhighlight lang="ada"> 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;

</syntaxhighlight>

1980: Maple

Template:Further 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

Template:Further In Maxima CAS, one can use also integer values: <syntaxhighlight lang="maxima"> for x:0.5 step 0.1 thru 0.9 do

   /* "Do something with x" */

</syntaxhighlight>

1982: PostScript

Template:Further The for loop, written as Template:Code 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.<ref>Template:Cite book</ref> <syntaxhighlight lang="postscript"> 1 1 6 {STATEMENTS} for </syntaxhighlight> There is also a simple repeat loop. The repeat-loop, written as Template:Code, repeats the body exactly X times.<ref>Template:Cite web</ref> <syntaxhighlight lang="postscript"> 5 { STATEMENTS } repeat </syntaxhighlight>

1983: Ada 83 and above

Template:Further <syntaxhighlight lang="ada"> 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; </syntaxhighlight>

1984: MATLAB

Template:Further <syntaxhighlight lang="Matlab"> for n = 1:5

    -- statements

end</syntaxhighlight> After the loop, Template:Code would be 5 in this example.

As Template:Code is used for the Imaginary unit, its use as a loop variable is discouraged.

1987: Perl

Template:Further <syntaxhighlight lang="perl"> for ($counter = 1; $counter <= 5; $counter++) { # implicitly or predefined variable

   # statements;

} for (my $counter = 1; $counter <= 5; $counter++) { # variable private to the loop

   # statements;

} for (1..5) { # variable implicitly called $_; 1..5 creates a list of these 5 elements

   # statements;

} statement for 1..5; # almost same (only 1 statement) with natural language order for my $counter (1..5) { # variable private to the loop

   # statements;

} </syntaxhighlight>

"There's more than one way to do it" is a Perl programming motto.

1988: Mathematica

Template:Further The construct corresponding to most other languages' for loop is named Do in Mathematica.

<syntaxhighlight lang="mathematica"> Do[f[x], {x, 0, 1, 0.1}] </syntaxhighlight>

Mathematica also has a For construct that mimics the for loop of C-like languages.

<syntaxhighlight lang="mathematica"> For[x= 0 , x <= 1, x += 0.1,

   f[x]

] </syntaxhighlight>

1989: Bash

Template:Further <syntaxhighlight lang="bash">

  1. 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 </syntaxhighlight>

<syntaxhighlight lang="bash">

  1. 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 </syntaxhighlight>

An empty loop (i.e., one with no commands between Template:Code and Template:Code) 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

Template:Further

In Haskell98, the function mapM_ maps a monadic function over a list, as <syntaxhighlight lang="haskell"> mapM_ print [4, 3 .. 1] -- prints -- 4 -- 3 -- 2 -- 1 </syntaxhighlight>

The function mapM collects each iteration result in a list: <syntaxhighlight lang="Haskell"> result_list <- mapM (\ indx -> do{ print indx; return (indx - 1) }) [1..4] -- prints -- 1 -- 2 -- 3 -- 4 -- result_list is [0,1,2,3,4] </syntaxhighlight>

Haskell2010 adds functions forM_ and forM, which are equivalent to mapM_ and mapM, but with their arguments flipped: <syntaxhighlight lang="Haskell"> forM_ [0..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'] </syntaxhighlight>

When compiled with optimization, none of the expressions above will create lists. But, to save the space of the [1..5] list if optimization is turned off, a forLoop_ function could be defined as

<syntaxhighlight lang="Haskell"> 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)

</syntaxhighlight> and used as <syntaxhighlight lang="Haskell"> forLoopM_ (0::Int) (< len) (+1) $ \indx -> do

   -- statements

</syntaxhighlight>

1991: Oberon-2, Oberon-07, Component Pascal

Template:Further <syntaxhighlight lang="modula2"> FOR Counter:= 1 TO 5 DO

 (* statement sequence *)

END </syntaxhighlight> 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

Template:Further 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.<syntaxhighlight lang="python"> for i in range(1, 6): # gives i values from 1 to 5 inclusive (but not 6)

   # statements
   print(i)
  1. 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)

</syntaxhighlight>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: <syntaxhighlight lang="python"> for _ in range(5):

   print("Hello")

</syntaxhighlight> This will print “Hello” five times without using the loop variable.

1993: AppleScript

Template:Further <syntaxhighlight lang="applescript"> repeat with i from 1 to 5 -- statements log i end repeat </syntaxhighlight>

It can also iterate through a list of items, similar to what can be done with arrays in other languages: <syntaxhighlight lang="applescript"> set x to {1, "waffles", "bacon", 5.1, false} repeat with i in x log i end repeat </syntaxhighlight>

A Template:Code 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

Template:Further <syntaxhighlight lang="lua"> for i = start, stop, interval do

 -- statements

end</syntaxhighlight>

So, this code <syntaxhighlight lang="lua"> for i = 1, 5, 2 do

 print(i)

end</syntaxhighlight> will print: <syntaxhighlight lang="lua">1 3 5</syntaxhighlight>

A for loop can also loop through a table using <syntaxhighlight lang="lua">ipairs()</syntaxhighlight> to iterate numerically through arrays and <syntaxhighlight lang="lua">pairs()</syntaxhighlight> to iterate randomly through dictionaries. Generic for loop making use of closures:

<syntaxhighlight lang="lua"> for name, phone, and address in contacts() do

 -- contacts() must be an iterator function

end</syntaxhighlight>

1995: ColdFusion Markup Language (CFML)

Template:Further

Script syntax

Simple index loop: <syntaxhighlight lang="cfs"> for (i = 1; i <= 5; i++) { // statements } </syntaxhighlight>

Using an array: <syntaxhighlight lang="cfs"> for (i in [1,2,3,4,5]) { // statements } </syntaxhighlight>

Using a list of string values: <syntaxhighlight lang="cfs"> loop index="i" list="1;2,3;4,5" delimiters=",;" { // statements } </syntaxhighlight>

The above Template:Code example is only available in the dialect of CFML used by Lucee and Railo.

Tag syntax

Template:Further Simple index loop: <syntaxhighlight lang="cfm"> <cfloop index="i" from="1" to="5"> </cfloop> </syntaxhighlight>

Using an array: <syntaxhighlight lang="cfm"> <cfloop index="i" array="#[1,2,3,4,5]#"> </cfloop> </syntaxhighlight>

Using a "list" of string values: <syntaxhighlight lang="cfm"> <cfloop index="i" list="1;2,3;4,5" delimiters=",;"> </cfloop> </syntaxhighlight>

1995: Java

Template:Further <syntaxhighlight lang="java"> for (int i = 0; i < 5; i++) {

   //perform functions within the loop;
   //can use the statement 'break;' to exit early;
   //can use the statement 'continue;' to skip the current iteration

} </syntaxhighlight>

For the extended for loop, see Template:Slink.

1995: JavaScript

Template:Further JavaScript supports C-style "three-expression" loops. The Template:Code and Template:Code statements are supported inside loops.

<syntaxhighlight lang="javascript"> for (var i = 0; i < 5; i++) {

   // ...

} </syntaxhighlight>

Alternatively, it is possible to iterate over all keys of an array.

<syntaxhighlight lang="javascript"> for (var key in array) { // also works for assoc. arrays

   // use array[key]
   ...

} </syntaxhighlight>

1995: PHP

Template:Further This prints out a triangle of * <syntaxhighlight lang="php"> for ($i = 0; $i <= 5; $i++) {

   for ($j = 0; $j <= $i; $j++) {
       echo "*";
   }
   echo "
\n";

} </syntaxhighlight>

1995: Ruby

Template:Further <syntaxhighlight lang="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 </syntaxhighlight> Ruby has several possible syntaxes, including the above samples.

1996: OCaml

Template:Further See expression syntax.<ref>Template:Cite web</ref> <syntaxhighlight lang="ocaml">

(* 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 ;;

</syntaxhighlight>

1998: ActionScript 3

Template:Further <syntaxhighlight lang="actionscript3"> for (var counter:uint = 1; counter <= 5; counter++){

   //statement;

} </syntaxhighlight>

2008: Small Basic

Template:Further <syntaxhighlight lang="vbnet"> For i = 1 To 10

   ' Statements

EndFor </syntaxhighlight>

2008: Nim

Template:Further Nim has a foreach-type loop and various operations for creating iterators.<ref>https://nim-lang.org/docs/system.html#...i%2CT%2CT ".. iterator"</ref> <syntaxhighlight lang="nim"> for i in 5 .. 10:

 # statements

</syntaxhighlight>

2009: Go

Template:Further <syntaxhighlight lang="go"> for i := 0; i <= 10; i++ {

   // statements

} </syntaxhighlight>

2010: Rust

Template:Further <syntaxhighlight lang="rust"> for i in 0..10 {

   // statements

} </syntaxhighlight>

2011: Kotlin

Template:Further <syntaxhighlight lang="kotlin"> for (i in 1..10) {

   // statements

} </syntaxhighlight>


2012: Julia

Template:Further <syntaxhighlight lang="Julia"> for j = 1:10

   # statements

end </syntaxhighlight>

See also

References

Template:Reflist