Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
For loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==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=== {{Further|Fortran}} Fortran's equivalent of the {{mono|for}} loop is the {{mono|DO}} loop, using the keyword do instead of for, The syntax of Fortran's {{mono|DO}} 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 {{mono|END DO}} 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 {{mono|GO TO}} may be avoided by using an {{mono|EXIT}} 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 {{mono|DO - WHILE}} 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=== {{Further|ALGOL 58}} ALGOL 58 introduced the {{code|for}} statement, using the form as Superplan: FOR ''Identifier'' = ''Base'' (''Difference'') ''Limit'' For example to print 0 to 10 incremented by 1: <pre> FOR x = 0 (1) 10 BEGIN PRINT (FL) = x END </pre> ===1960: COBOL=== {{Further|COBOL}} [[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=== {{Further|BASIC}} 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 {{code|EXIT}} and {{code|CYCLE}} 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=== {{Further|PL/I}} <syntaxhighlight lang="rexx"> do counter = 1 to 5 by 1; /* "by 1" is the default if not specified */ /*statements*/; end; </syntaxhighlight> The {{mono|LEAVE}} statement may be used to exit the loop. Loops can be [[Label (computer science)|labeled]], and ''leave'' may leave a specific labeled loop in a group of nested loops. Some PL/I dialects include the {{mono|ITERATE}} statement to terminate the current loop iteration and begin the next. ===1968: ALGOL 68=== {{Further|ALGOL 68}} ALGOL 68 has what was considered ''the'' universal loop, the full syntax is: <pre> FOR i FROM 1 BY 2 TO 3 WHILE iβ 4 DO ~ OD </pre> Further, the single iteration range could be replaced by a list of such ranges. There are several unusual aspects of the construct * only the {{code|do ~ od}} portion was compulsory, in which case the loop will iterate indefinitely. * thus the clause {{code|to 100 do ~ od}}, will iterate exactly 100 times. * The {{code|while}} ''syntactic element'' allowed a programmer to break from a {{code|for}} loop early, as in: <pre> 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 </pre> Subsequent ''extensions'' to the standard ALGOL 68 allowed the {{code|to}} syntactic element to be replaced with {{code|{{sic|hide=y|up|to}}}} and {{code|downto}} to achieve a small optimization. The same compilers also incorporated: ;{{code|until}}: for late loop termination. ;{{code|foreach}}: for working on arrays in [[parallel computing|parallel]]. ===1970: Pascal=== {{Further|Pascal (programming language)}} <syntaxhighlight lang="pascal"> for Counter:= 1 to 5 do (*statement*); </syntaxhighlight> Decrementing (counting backwards) is using {{code|downto}} keyword instead of {{code|to}}, as in: <syntaxhighlight lang="pascal"> for Counter:= 5 down to 1 do (*statement*); </syntaxhighlight> The numeric range for-loop varies somewhat more. ===1972: C, C++=== {{Further|C (programming language)|C++|C syntax#Iteration statements}} <syntaxhighlight lang="c"> for (initialization; condition; increment/decrement) statement </syntaxhighlight> The {{mono|statement}} 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 {{code|for}} loops. All three sections in the for loop are optional, with an empty condition equivalent to true. ===1972: Smalltalk=== {{Further|Smalltalk}} <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 (computer science)|closure]], using self as start value. ===1980: Ada=== {{Further|Ada (programming language)}} <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=== {{Further|Maple (software)}} 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 <code>'''do'''</code> and <code>'''od'''</code> are optional. The <code>''' for''' ''I''</code> part, if present, must come first. The remaining parts (<code>'''from''' ''f''</code>, <code>'''by''' ''b''</code>, <code>'''to''' ''t''</code>, <code>'''while''' ''w''</code>) 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 <code>''' in''' ''c''</code> 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 <code>'''od'''</code>, <code>'''end'''</code>, or <code>'''end do'''</code>. ===1982: Maxima CAS=== {{Further|Maxima (software)}} 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=== {{Further|PostScript}} The for-loop, written as {{code|[initial] [increment] [limit] { ... } for}} 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>{{cite book |year=1999 |title=PostScript Language Reference |publisher=Addison-Wesley Publishing Company |page=596 |isbn=0-201-37922-8}}</ref> <syntaxhighlight lang="applescript"> 1 1 6 {STATEMENTS} for </syntaxhighlight> There is also a simple repeat loop. The repeat-loop, written as {{code|X { ... } repeat}}, repeats the body exactly X times.<ref>{{cite web|url=http://pscript.dubmun.com/tutorial4.html|title=PostScript Tutorial - Loops}}</ref> <syntaxhighlight lang="applescript"> 5 { STATEMENTS } repeat </syntaxhighlight> ===1983: Ada 83 and above=== {{Further|Ada (programming language)}} <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=== {{Further|MATLAB}} <syntaxhighlight lang="Matlab"> for n = 1:5 -- statements end</syntaxhighlight> After the loop, {{code|n}} would be 5 in this example. As {{code|i}} is used for the [[Imaginary unit]], its use as a loop variable is discouraged. ===1987: Perl=== {{Further|Perl}} <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=== {{Further|Wolfram Mathematica|Wolfram Language}} The construct corresponding to most other languages' for-loop is named ''Do'' in Mathematica. <syntaxhighlight lang="ruby"> 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="ruby"> For[x= 0 , x <= 1, x += 0.1, f[x] ] </syntaxhighlight> ===1989: Bash=== {{Further|Bash (Unix shell)}} <syntaxhighlight lang="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 </syntaxhighlight> <syntaxhighlight lang="bash"> # 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 {{code|do}} and {{code|done}}) 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=== {{Further|Haskell}} In Haskell98, the function ''mapM_'' maps a [[monad (functional programming)|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=== {{Further|Oberon (programming language)|Oberon-2|Component Pascal}} <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=== {{Further|Python (programming language)}} Python does not contain the classical for loop, rather a <code>foreach</code> loop is used to iterate over the output of the built-in <code>range()</code> 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) # 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 <code>range(6)</code> would run the loop from 0 to 5. When the loop variable is not needed, it is common practice to use an underscore (<code>_</code>) 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=== {{Further|AppleScript}} <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 {{code|exit repeat}} 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=== {{Further|Crystal (programming language)}} <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> For-loops 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)=== {{Further|ColdFusion Markup Language}} ====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 {{code|list}} example is only available in the dialect of CFML used by [[Lucee]] and [[Railo]]. ====Tag syntax==== {{Further|Tag (programming)}} Simple index loop: <syntaxhighlight lang="cfm"> <cfloop index="i" from="1" to="5"> <!--- statements ---> </cfloop> </syntaxhighlight> Using an array: <syntaxhighlight lang="cfm"> <cfloop index="i" array="#[1,2,3,4,5]#"> <!--- statements ---> </cfloop> </syntaxhighlight> Using a "list" of string values: <syntaxhighlight lang="cfm"> <cfloop index="i" list="1;2,3;4,5" delimiters=",;"> <!--- statements ---> </cfloop> </syntaxhighlight> ===1995: Java=== {{Further|Java (programming language)}} <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 {{slink|Foreach loop#Java}}. ===1995: JavaScript=== {{Further|JavaScript}} JavaScript supports C-style "three-expression" loops. The {{code|break}} and {{code|continue}} 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=== {{Further|PHP}} This prints out a triangle of * <syntaxhighlight lang="php"> for ($i = 0; $i <= 5; $i++) { for ($j = 0; $j <= $i; $j++) { echo "*"; } echo "<br />\n"; } </syntaxhighlight> ===1995: Ruby=== {{Further|Ruby (programming language)}} <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 programming language|Ruby]] has several possible syntaxes, including the above samples. ===1996: OCaml=== {{Further|OCaml}} See expression syntax.<ref>{{Cite web |url=http://caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html |title=OCaml expression syntax |access-date=2013-03-19 |archive-date=2013-04-12 |archive-url=https://archive.today/20130412180254/http://caml.inria.fr/pub/docs/manual-ocaml-4.00/expr.html |url-status=dead }}</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=== {{Further|ActionScript}} <syntaxhighlight lang="actionscript3"> for (var counter:uint = 1; counter <= 5; counter++){ //statement; } </syntaxhighlight> ===2008: Small Basic=== {{Further|Microsoft Small Basic}} <syntaxhighlight lang="vbnet"> For i = 1 To 10 ' Statements EndFor </syntaxhighlight> ===2008: Nim=== {{Further|Nim (programming language)}} [[Nim (programming language)|Nim]] has a <code>foreach</code>-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=== {{Further|Go (programming language)}} <syntaxhighlight lang="go"> for i := 0; i <= 10; i++ { // statements } </syntaxhighlight> ===2010: Rust=== {{Further|Rust (programming language)}} <syntaxhighlight lang="rust"> for i in 0..10 { // statements } </syntaxhighlight> ===2012: Julia=== {{Further|Julia (programming language)}} <syntaxhighlight lang="Julia"> for j = 1:10 # statements end </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)