Talk:For loop

Explanation of the three-part loop syntax
...seems to be entirely absent from this article. It's well-known, but for a beginner, it's not immediately obvious what they each do. They have generally accepted names, correct? Would someone who knows those names add them? 24.58.56.142 (talk) 22:50, 17 May 2012 (UTC)
 * Requested quite a while ago. I attempted to fix this, along with a citation from a C++ website. -- Carrot Lord (talk) 17:17, 21 December 2012 (UTC)

Agreed; and for C there should be an example of another form such as: for( p = head; p != NULL; p = p->next ) 184.147.226.214 (talk) — Preceding undated comment added 00:58, 13 September 2014 (UTC)

Factorials?
hmm is the factorial example the best and most easy to understand example? because i don't really think it is. Matthew 12:14, 21 January 2006 (UTC)


 * I would tend to agree. We should use something that isn't math-specific. --Hooperbloob 19:11, 21 January 2006 (UTC)


 * I've ditched it in favor of no actual content in the example. Stuff like factorials, declaring variables, and printing were distracting from the actual for loop. —Simetrical (talk • contribs) 04:40, 25 August 2006 (UTC)


 * This might be true - but Do while loop and While loop still have the factorial examples and in a larger picture is was quite nice to see the same algorithm with different loop constructs and different languages.  —Preceding unsigned comment added by Krischik (talk • contribs) 14:44, 1 February 2008 (UTC)

bash
From the bash section (before I changed it): function range {	if [ $1 -ge $2 ]; then return fi i=$1 while [ $i -le $2 ]; do		echo $i; i=$(($i+1)); done }
 * 1) subroutine for listing consecutive integers

factorial=1 for counter in $(range 1 5) do factorial=$(($factorial * $counter)) done echo $factorial
 * 1) main

Note that bash does not have the built-in ability to list consecutive integers&hellip;

Is this really correct? The following code works perfect in my bash 3.00: factorial=1 for ((i=1; $i<=5; i=$i+1)) do     factorial=$(($factorial * $i)) done echo $factorial

Am I missing something? –Gustavb 02:59, 11 February 2006 (UTC)

Merge Foreach into this article
I propose that the Foreach article should be merged into this one. That other article significantly overlaps this one, now that more detail has been created here which describes the variety of for loops. Although it may use the keyword foreach rather than for, the semantics of the loops are the same, and in fact the foreach loop is really just a specific kind of for loop. — Dmeranda 17:02, 17 May 2006 (UTC)


 * I disagree. The examples of for loops discussed in the for loop article are exclusively about traversing a numeric range with a loop counter, whether using the "numeric ranges" or the "three-expression for loops".  The foreach loop is semantically very different, and is characterized by the lack of a loop counter (and sometimes lack of guarantee on order of traversal), and is specifically used to operate on each item of a collection.  In any language that supports both the for loop and the foreach loop, they are treated as very different constructs, syntatically and semantically.  I think that the "for loop" article should not include the "foreach loop" as a type of for loop, even though they sound the same; and instead link to it as a different type of thing.  --Spoon! 23:26, 17 August 2006 (UTC)

They are two similar but distinct concepts, it would confuse anyone who didn't understand the differences. —Preceding unsigned comment added by 82.41.27.90 (talk • contribs) 20:23, 15 July 2006

Keep For and Foreach separate. They are not the same things. You can reference this article from for and the for article from this one but don't merge them. —Preceding unsigned comment added by 69.95.130.62 (talk • contribs) 20:21, 20 July 2006


 * The thing is, Python and many other languages use the keyword  for what PHP calls  .  We can't say that that's not a "real" for loop; it has to be discussed here.  I've linked to it as the main article for the iterator loop: is that good with everyone? —Simetrical (talk • contribs) 04:16, 25 August 2006 (UTC)
 * What languages other than PHP actually use the term  anyway? —Simetrical (talk • contribs) 04:41, 25 August 2006 (UTC)


 * Apparently the last edit to the Foreach article deleted all the code samples. Looking over what was there, C#, Perl (although confusingly "for" can also be used), PHP, Realbasic (two words "for each"), Tcl, and maybe others --Spoon! 01:53, 2 September 2006 (UTC)
 * Correct. The goal of the Foreach article shouldn't be to tell you how every last language writes its foreach loops, it should just give an overview of the general syntaxes used.  I may have been slightly overzealous, though; I've added a sentence to the "Syntaxes" section to expand a bit on the differences. —Simetrical (talk • contribs) 21:29, 3 September 2006 (UTC)

Fortran has both 'DO' and 'FOR' loops
Need to update article. Rwwww 07:33, 31 July 2006 (UTC)
 * Can you provide a reference for this assertion? According to the ISO/IEC DIS 1539-1:2004(E), 2004-May-3  (e.g., FORTRAN 2003) there is no   statement, only a   and a  .  There is though a   construct, but it is not a loop control statement.--Dmeranda 20:47, 31 July 2006 (UTC)  —Edit: Sorry, meant , not  .--Dmeranda 20:53, 31 July 2006 (UTC)

When did this name appear?
Does anybody know when the first use of the word "for loop" for this concept occured? Heinz Rutishauser had a so called "Für"-loop in his language "Superplan" (designed from 1949 to 1951) which has the same semantics as the for loop in ALGOL 60 (to which Rustishauser contributed). It would be interesting to find out where and when exactly the name originated.

Für i=2(1)n :  $$a_i $$ + 3 = $$a_i $$

means, that in an array a all elements i (steps of 1) from 2 to n are incremented by 3. (cf. discussion of Plankalkül) 217.236.218.47 19:38, 26 June 2007 (UTC)


 * It may be difficult to determine the exact origin because those are also ordinary English words and their meaning in "for loop" is really not very far from their non-technical use. There may also be a distinction between a language having a construct that is similar to the for loop or that uses a keyword "for", versus casual discussion of it using the term "for loop".  That being said, it is possible that it derives from the mathematical universal quantifier ($$ \forall $$), which is typically read aloud as "for all".  Among early languages ALGOL 58 certainly had a for loop although the syntax would be considered unusual today.  Another early language, BCPL, from 1966 also had a for loop, and a being a predecessor to C looked more like the modern for loop and may have been more widely discussed (thus leading to the use of the term "for loop", although this would be conjecture).  Note though that Fortran, one of the most popular 1950s language had a "DO" loop, which aside from using "do" rather than "for" is semantically quite similar to the modern for loop. - Dmeranda 13:21, 28 June 2007 (UTC)


 * Right, tracing back the semantics should be difficult, and consequently also the "casual discussion use" of "for loops". But is there any earlier explicit use of "for", German "Für" as a keyword for this concept? Rutishauser was a member of both meetings, the one that developed ALGOL 58, as well as the one that conceived ALGOL 60, and the syntax of his for loop looks pretty much like the ALGOL one - even considering ALGOL 68 it only misses the condition. A probable guess is that this part was contributed to ALGOL by Rutishauser - and "für" simply translated to "for" as a keyword suggestion.
 * 217.236.210.65 09:52, 30 June 2007 (UTC)
 * PS Concerning the origin of the use of for/für: having designed Superplan from 1949 to 1951, the only other higher level language was Plankalkül, anyway - no FORTRAN etc. around at that time.
 * If you can cite a verifiable reference to the Superplan language and this loop construct you are talking about then please add it, especially if there is a documented direct or indirect lineage to ALGOL. - Dmeranda 07:08, 2 July 2007 (UTC)


 * Hello


 * The following is a German book by Dr. Hans Willy-Hohn
 * ,
 * And on page 185 he writes the following:
 * Here is a translation (the original follows):
 * "Thus through the involvement of the Institute for Practical Mathematics in Zürich Zuse's Plankalkül was by chance again part of their considerations – Bauer and Samelson had beforehand ignored it. The Institute for Practical Mathematics had bought Zuse's Z4 in 1949 (...). H. Rutishauser, one of the members of the institute, who was in charge of programming the machine, got to know Zuse's Plankalkül-writings. Rutishauser published an essay on Automatische Rechenplanfertigung [meaning: automatical generation of machine code] in the Magazine for Applied Mathematics in 1951, in which he showed, that die programmgesteuerte Rechenmaschine selbst dank ihrer Vielseitigkeit als Planfertigungsgerät [meaning: a programmed computing machine can – thanks to its diversity -  itself be used as a means to produce machine code]. There he described for a simple algebraic programming language which referring to Zuse's terminology he called Superplan, one of the first compilers (...). For Bauer and Samelson this essay was the reason to ask Rutishauser to join in the development of ALGOL. Hereby parts of Plankalkül influenced ALGOL (Bauer 1980)."
 * original:
 * "Durch einen Zufall kam als folge der Beteiligung des Instituts für praktische Mathematik in Zürich auch der Plankalkül von Konrad Zuse wieder ins Spiel, nachdem auch Bauer und Samelson dieser Programmiersprache zunächst keine Beachtung geschenkt hatten. Das Institut für praktische Mathematik hatte 1949 Zuses Z4 erworben (...). H. Rutishauser, einer der Mitarbeiter des Instituts, der für die Programmierung der Maschine zuständig war, hatte dabei auch Zuses Arbeiten über den Plankalkül kennengelernt. In der Zeitschrift für angewandte Mathematik veröffentlichte Rutishauser 1951 einen Aufsatz über Automatische Rechenplanfertigung, in dem er zeigte, daß sich die programmgesteuerte Rechenmaschine selbst dank ihrer Vielseitigkeit als Planfertigungsgerät (...) verwenden ließ. Er beschrieb dort für eine einfache algebraische Programmiersprache, die er in Anlehnung an Zuses Terminologie als Superplan bezeichnete, einen der weltweit ersten Compiler (...). ... Bauer und Samelson wiederum nahmen dann diesen Aufsatz zum Anlaß, Rutishauser an der Entwicklung von ALGOL zu beteiligen. Hierdurch wiederum sind Teile des Plankalküls in ALGOL eingeflossen (Bauer 1980)."


 * In this paper on the development of ALGOL you can see an example of the syntax of Rutishauser's language.
 * HT de Beer, The History of the ALGOL Effort (PDF)


 * Superplan is mentioned here, too.


 * Sincerely, 217.236.255.112 09:50, 2 July 2007 (UTC)


 * This looks like good research material related to this article, unfortunately I don't read German (thanks for the translation). Why don't you take the opportunity and jump in and add some of this information to the article itself.  I'd suggest creating a Wikipedia account first, and if you need it there's a lot of help on editing Wikipedia. There's also specific guidance on how to cite sources. - Dmeranda


 * Actually I have an account – I just don't always bother to sign in.
 * Maybe somebody else has further info on the first appearance of the keyword "for" or explicit and forthright evidence that Rutishauser was the source for this keyword and syntax used in ALGOL.
 * I think the best way to proceed would be to create sourced articles about Superplan and Rutishauser, anyway. But I don't have further information about Superplan.
 * Christian Storm 18:41, 3 July 2007 (UTC)


 * I don't know much on Superplan. If you don't get any help here I'd suggest going over to the talk pages for ALGOL, it probably has a much larger audience than this article.  Or better yet just go ahead and start a stub article for Superplan with the material you seem to have; it's already linked from Timeline of programming languages.  Since it looks like your cited materials are of German origin, you may also find some information or helpers on the German Wikipedia site. And you may want to see what's up in the WikiProject Programming languages too. -- Dmeranda 21:16, 3 July 2007 (UTC)

Distinguishing iterator-based and numeric for loops
I've marked the section Distinguishing iterator-based and numeric for loops with a no original research tag. Please note that I am not saying that the information presented is incorrect or not worthy or inclusion. However, as this section is highly technical and is presented in a casual prescriptive style, it would be useful if some citations were made in this case. Additionally, I'm not entirely sure the subject belongs in this article, as it really seems to be more about loop optimization or vectorization than it is about the for loop in particular. Consider perhaps moving or merging the bulk of this section to another article as well as trying to cite some references. Welcome to discuss further if other opinions exist. - Dmeranda 21:32, 2 July 2007 (UTC)
 * As the guilty party, I wonder at the "no original research" marker - is this an assertion that x is original research, or a prescription that there should not be such, somewhere? Anyway, I recall last year coding a LU-decomposition using both for and forall and experimenting to establish that indeed the compiler does generate code that behaves as described in the manual for the compaq fortran 95 compiler, and indeed that ignoring the detail I described leads to wrong results. This is hardly original research, simply a direct report of experience as warning to others who might not notice yet another vaguely general statement in some manual with (as so often) no example to illustrate the consequences. (My copy has handwritten annotations, though I'm the only user) References to a specific compiler manual seem otiose.
 * As for the style, I can't be bothered with a prim pseudo-generality that obscures simple details (nor am I being paid for it): the text is of course subject to the whims of all. The best location is in doubt for me also. Loop optimisation and array manipulation is a large subject with many details, and indeed there could be links to that. But an article that discusses both for and forall loops should be able to distinguish them. NickyMcLean 22:30, 2 July 2007 (UTC)


 * This isn't the place for your criticisms of the design of a language. 76.175.72.51 (talk) 05:54, 4 December 2008 (UTC)


 * I've just stumbled upon this article, and I'm somewhat inclined to agree with the original sentiment. My suggestions for improvement would be:
 * Cite an actual language that has a "forall" construct (or something semantically equivalent), rather than what currently reads as a thought experiment. Off the top of my head, I can't actually think of a language that offers an iterator-based loop construct at the same time as presenting the loop index.
 * Remove the material on optimisation; again, this is pure hypothesis, and probably out-of-scope for this article.
 * Remove the final sentence on languages that support matrix manipulation as an intrinsic. This is out of scope, as no logical loop exists at all.
 * I believe the structure of the section should be:
 * Some languages (cite example) offer a "forall" keyword.
 * This is similar, but different.
 * The averaging example.
 * Oli Filth(talk 18:21, 31 May 2009 (UTC)


 * Oh, apparently Fortran 95 is such an example (I'm not familiar with Fortran). I've implemented my suggested changes by creating a sub-section in the "Kinds of for loop" section.  I have no idea whether the code example I've taken is valid Fortran or not, so perhaps someone could check this.  Oli Filth(talk 18:42, 31 May 2009 (UTC)


 * Yes indeed, fortran 95 is such an example, as indicated by the words "fortran 95" after "Compaq". I used pseudocode in the article because the syntax differences are a distraction. Using actually correct fortran 95 syntax, the two forms become (with variations in layout and spacing to taste):

DO I = 2,N - 1 A(I) = (A(I - 1) + A(I) + A(I + 1))/3 END DO and FOR ALL (I = 2:N - 1) A(I) = (A(I - 1) + A(I) + A(I + 1))/3 and because fortran 95+ (and pl/1 and some others) allow array assignments there is yet a third form, in one language, (and further, which also supplies matrix manipulation features): A(2:N - 1) = (A(1:N - 2) + A(2:N - 1) + A(3:N))/3 But exactly how this might be executed is not clearly described: like the iterated loop, or like the forall loop, or, something else? I could prepare test programmes and report the results, but Dmeranda would no doubt decry it as Original Research, so I won't bother. NickyMcLean (talk) 22:20, 2 June 2009 (UTC)


 * Apologies, I managed to completely miss that you'd referenced Fortran 95 in your original reply!
 * That looks like Matlab. If so, the answer is that, again, the RHS is fully evaluated before any assignments occur.  However, given that there's no actual loop construct, I feel that it would be out of place in this article.  Oli Filth(talk 22:48, 2 June 2009 (UTC)


 * I suppose one could talk of implicit loops, implied by the array assignment, and further attempt a merger/redistribution of the various related articles, but no matter. Descriptions, as found in manuals, are often maddeningly vague. It is doubtless very pleasing to write at a high level of abstraction and design, but I want specifics. I also use Matlab (with no few mutterings, especially over text handling) and so, what actually happens with an array assignment, such as the averaging example? If all RHS expressions are computed before any assignments, does this mean that a temporary array T is produced, whose contents are then copied to A at the end? This is obviously ungood, even though it allows a simple description. With MatLab and perhaps others, tricks could be played: the storage associated with A could be returned to the pool, and A redirected to finger the just-completed temporary array T which thus becomes lasting. Such tricks make array manipulation much more complex and thus slower but avoiding the copy loop would be an improvement though still ungood: imagine that A mostly filled the fast storage available (on-chip, or whatever) so that there was insufficient space for a copy as well, and contrast with the situation where A was updated in place by the computation, indeed by a succession of similar computations with successive statements. Could not each array computation be performed as if all RHS expressions were evaluated and then all assignments done? This is certainly possible for the example via a few temporary (simple) variables in an explicit iterative loop, and I have done this, and gained performance improvements as well as interesting changes in the path to convergence for an electric field polarisation computation. But more analysis would be required by the compiler if this were to be supplied by it. As another example, consider the ALL(array logical expression) test; the description speaks of computing the expression's array of true/false results. Well, I want no such (temporary) array to be allocated, calculated, inspected and deallocated, and, I want the ALL calculation to terminate on the first "false" too. Details, details. NickyMcLean (talk) 22:24, 3 June 2009 (UTC)

Contradiction between text and diagram
The diagram shows that for(A;B;C) D; does NOT execute C in the last loop iteration, however the text states: "Finally, the counting expression is evaluated at the end of each loop iteration."

This gives conflicting results for the following code:

int i; for(i=0;i<10;i++); // do nothing

Now i may be either 10 (according to the diagram) or 11 (according to the text).

A quick test with java told me 10 is the correct value so at least for java the diagram is correct and the text is wrong. As I'm not used to editing wikipedia I just put it in the discussion however should there may be some mistake on my part :-) — Preceding unsigned comment added by 139.18.8.113 (talk) 13:51, 28 June 2011 (UTC)


 * Seems to have been corrected in the meantime - the diagram shows correctly that C will be executed after the last D, then condition B will return false, thus exiting the loop. And how should i get 11? The condition is already false when i is 10 (10<10 is false). Bfroehler (talk) 08:22, 27 September 2011 (UTC)

Algol Example a puzzle
The Algol example, before or after the recent re-prettying is a puzzle to me. Does the Algol syntax really allow a print statement before the logical expression of a WHILE clause? And although it may be fashionable now to put various clauses on a line of their own, it took me a while to realise that the vertical straggle was indeed one FOR ... WHILE ... DO construction and thus that the "print" was interposed. It is useful to have the various examples compute the same thing in their different ways, and show the same exit-from-loop if the sum of squares exceeds 1000, but, the Algol example appears to use the test Sum Sq not equal to seventy squared - which it will be for i = 24, but Sum Sq passes 1000 with i = 14. And does Algol allow spaces in names - I thought only Fortran was space-ignoring? And, I don't see any increment of the index variable in the Algol example either! Is this some default? I could rejigger the example as I have used Algol, but I did not use an Algol with the preceeding abilities, or so I thought at the time. Confusion! NickyMcLean (talk) 21:09, 10 July 2011 (UTC)
 * The "reprettying" has lost the structure of the statement. In Algol, the compound statement   executes   and   in sequence, and has the value of , and   means the same as  . --Macrakis (talk) 19:08, 11 July 2011 (UTC)

Immutable loop variable in C++?
Does anybody have a reference to an official document (like the ISO standard) to where it says that in C++, for loop variables are immutable in the loop body (see section "Loop variable scope and semantics", second abstract)? The compiler I use (Microsoft Visual C++ 2010) does NOT behave like it was immutable - no warning from the compiler when I modify the variable, and the behavior of the program is also as I would expect; example:

int main(int argc, char** argv) { 	for (int i=0; i<3; ++i) { 		if (i == 1) { 			++i; } 		std::cout << i << std::endl; } } // output: 0 2
 * 1) include

I don't mean to say that Visual C++ is generally very good at keeping standards, but they sure have improved a lot in that respect, so I would wonder if they hadn't implemented such a relatively small check... Bfroehler (talk) 08:17, 27 September 2011 (UTC)

No, in C/C++ loop variables are *not* immutable in the loop body, and this is what the article says. The 'open' form of the "for" statement (with explicit initialization, test, and increment) means there's no confusion (at least, not to the compiler!) as to what happens when you modify the variable inside the loop.

There are use cases - 'skipping over' a number of loop iterations when traversing an array, for instance.

It should be noted, though, that modifying the loop index inside a simple for( i = ... ; i < .. ; i++ ) loop will often prevent the compiler from performing certain optimizations; many optimizations only apply when the loop index changes in a simple, uniform way. 184.147.226.214 (talk) — Preceding undated comment added 01:14, 13 September 2014 (UTC)

Recomputing limits, step?
One item that I would like to see discussed is how the various languages with numeric for-loops involving an initial value, final value, and the optional step evaluate the limits. I believe a FORTRAN DO-loop evaluates all 2 or 3 items exactly once at the beginning, not before every loop, but not sure about the others. In C and its descendant languages the answer is of course "every time", but I don't think its syntax can be called a true for-loop, it is just syntactic sugar for a particular kind of while-loop. ErkkiRuohtula (talk) 11:47, 19 October 2011 (UTC)
 * This is an established problem and has been left to compiler writers to choose for particular implementations. For a loop from 1 to N, a question arises as what happens if the value of N is changed during the loop? For instance, during the processing of a list, an element may be removed from or added to the list. Another point is that the upper bound may be more complex than a simple value, such as N + 1, or generally, an expression. Re-evaluating that expression every iteration would be extra effort. Further difficulties arise if the direction of iteration may not always be positive. In Pascal there is "to" ("upto") and "downto", but here I mean that the direction can be specified by a variable, as in for i:=1:N:way do ... next i; where way may be +1, -1, or -3, etc. For the full case, the specification would be for i:=first:last:way (or first:way:last as in MatLab) with all entries as possible expressions, and potentially varying during execution, and the loop terminating whenever the next value for i is outside the bounds of the moment. Obviously, the general case could be reduced for specific cases involving simple variables or reduced further for literal constants.
 * A second problem arises with integer arithmetic, and overflow. Suppose with 16-bit two's complement, the plan was to attempt for i:=1:32767. After i = 32767 is performed, the next value would be 32768 and so the loop should end, but alas, there will be integer overflow and the result will be -32768 which is less than 32767, and so the loop will continue forever, though other problems may arise. This difficulty can be handled by the compiler writer producing code that attends to the occurrence of an overflow during the computation of the next value for the index variable and its comparison against the upper bound. Alternatively, it may be possible that the iteration control calculation proceed with a larger size of integer, say 32-bit. Or 64-bit. Or 128-bit?
 * Thus, the usual approach is to compute an iteration count at the start of the loop. This must be done in unsigned arithmetic to handle the likes of for i:=-32000:+32000 and means that any complex of expressions are evaluated once. It also means duplication: there is an iteration counter that is reduced by one each time around, and also, the value of the specified index variable must be adjusted. These points are explicity made in my copy of the Compaq Fortran manual, paragraph 5 in section 7-18 Execution Control. But this is one implementation of one language.
 * There is still a difficulty should there be an attempt on a maximal loop: that is for i:=-32768:+32767 or for unsigned integers, for i:=0:65535 as the number of iterations (ignoring |way| > 1) is last - first + 1 which is to say 65536, a number that cannot be represented in sixteen bits. In pseudocode, the expression for i:=first:last do ...stuff... next i; (avoiding the complications caused by expressions, and way ≠ 1) could be handled somewhat as follows. Actual machine code could avoid the repeated evaluation of last - first (in the if test and the evaluation of more) by paying attention to overflow and carry flags.

i:=first; if last < first then go to done;    Thus possibly not executing the loop. more:=last - first;            Not adding one. xeq:execute the stuff i:=i + 1;                      Next index value. if more <= 0 then go to done; more:=more - 1; go to xeq; done:
 * C-language followers should note the frequent use of slanted loops. Instead of for i:=1:N they often use 0:N - 1, expressed as < N rather than <= N, and this gets around the problem of < 32767 rather than <= 32767 as the only way that second test can return "false" is for the index variable to have a value greater than 32767, and it can't. Again, the compiler writer could pay attention to overflow flags, but, in the C-style, the index increment and index test expressions are separate, so carrying this state across the two is unlikely. Exactly the same problems apply with 32-bit integers, but the digit strings are longer. NickyMcLean (talk) 21:49, 19 October 2011 (UTC)

For-loop for loop?
As can be seen from the heading, the individual words "for" and "loop" are normal common words that could be read as having the normal meaning, not the special meaning of "for loop" with the words set off by quoting in the normal way. The first apeparance in the text outside of quotes is ... the for loop  ... While I was looking at other stuff, not having read the article from the beginning and so not having read the sequence "for loop" to for loop, [see?] this seemed unnecessarily ambiguous. So I tried changing to for-loop to make a clearly compounded word. In other cases, such as e-mail, as time passes, email becomes common - though forloop still looks odd, and I still write e-mail from my mudhole where I am stuck. Since different computer languages use different terms, there is no single usage to follow in English text describing them. Humm... How about for loop for for loop [see?]? Anyway, I thought I'd protected the usage of W-links; if I'd mistakenly zapped any, they could have been repaired. NickyMcLean (talk) 20:41, 9 December 2012 (UTC)


 * Well, in all the programming books and tutorials I have read I never encountered "for-loop" with a hyphen, it has always been "for loop" (and "while loop" and "do loop" and so on). But I don't feel very strongly about this, and I won't revert if you change "for loop" to "for-loop" again. However, please be careful to check your edit ("Show changes") before saving. — Tobias Bergemann (talk) 08:50, 11 December 2012 (UTC)


 * The more correct form is for-loop with the hyphen (as well as while-loop, do-loop, do-while-loop, repeat-loop, foreach-loop, etc.), for exactly the reasons stated by NickyMcLean. The same goes for other constructs, such as if-then-else, do-while, repeat-until, try-catch, test-and-set, etc. It is indeed confusing to parse a sentence such as "for for loops with controlling expressions..." or "while while loops are preferred over for loops for simple testing, for more control, for loops are preferred." Consequently, I have changed all of the occurrences in the article to use the hyphenated form. That being done, note that the title of this article should still remain as "For loop". — Loadmaster (talk) 17:59, 7 May 2015 (UTC)

BASIC "step" keyword
Some versions of BASIC (various flavors from Microsoft, like QuickBASIC and Visual Basic ) offer an optional STEP keyword on for-loops:

REM this will print 1, 3, 5, 7, 9 FOR i = 1 to 10 STEP 2 PRINT i NEXT

Since several of the language examples discuss step syntax, it should probably be mentioned here, too.

Ryancgordon (talk) 21:16, 25 September 2015 (UTC)

Merge with Control_flow#Loops
Duplication makes it harder to pick details about for loops (for example, there a timeline at this page). IMO it is better to define loops in single place (Control flow) and then only refer to this page. Ushkin N (talk) 05:04, 22 May 2016 (UTC)
 * Oppose merge, on the grounds that the current summary/main format seem to work well (that is, that Control flow contains a template:main to For loop) and that a merge page would be too long and unbalanced towards for loops. Klbrain (talk) 16:44, 28 February 2018 (UTC)
 * Closing, given no support for the merge over almost 2 years, and no comment on the "oppose" over the course of month. Klbrain (talk) 16:36, 29 March 2018 (UTC)

COBOL Performs CIRCA 1960
The section marked COBOL 1960 - uses an in-line PERFORM VARYING and an END-PERFORM. These constructs didn't exist in 1960. It was around 1980 that these became part of the language. Anyone care if I make an edit? — Preceding unsigned comment added by 206.248.171.144 (talk) 17:33, 12 July 2020 (UTC)

Computer
The for loop is used when the number of iteration are known before the loop entered 103.7.79.52 (talk) 14:53, 29 November 2021 (UTC)
 * Or not -- e.g.: for {do something forever}. Wtmitchell  (talk) (earlier Boracay Bill) 14:56, 29 November 2021 (UTC)

Should Crystal (1993) be Lua?
The section Crystal (1993) seems to be referring to the programming language Lua, which was released in 1993 and which is the only language I know that uses  and   functions for looping. The only language called Crystal (programming language) I can find was created in 2014. If this is more than just a simple mistake, then it should be explained in the article. Sam A Hill (talk) 04:58, 6 December 2023 (UTC)

C's for loop is primitive
C's for loop is a very poor example and should not be given pride of place.Control structures should be semantic, yet C's for loop is a level below that where the programmer must increment the control variable. Here is a further explanation.

The for loop takes a range variable and loops on that range. The range can be explicit as in: for I := 1, 4, 7, 34, 78, 97 do …

or specified by bounds:

for I := 0 until 9 do …

or the steps may be specified:

for I := 0 step 2 until 9 do …

Note how the for loop handles the increments for you.

There is a primitive form where the programmer must do this detail as in

for (I := 0, I <= 9, I++) …

(Also note syntactically that the two characters ‘do’ that are easy to type have been replaced by the harder to type ‘’.)

This is a primitive low-level form of for and is inferior to the more semantic forms above. What we are interested in with syntactic forms is the meaning of the construct as in the first three, not the mechanics of the loop as in the more primitive form. Ian.joyner (talk) 04:59, 12 April 2024 (UTC)