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!
==FOR== [[File:For loop.svg|thumb|350px|For loop illustration, from i=0 to i=2, resulting in data1=200]] A for-loop statement is available in most [[imperative programming]] languages. Even ignoring minor differences in [[Syntax (programming languages)|syntax]], there are many differences in how these statements work and the level of expressiveness they support. Generally, for-loops fall into one of four categories: ===Traditional for-loops=== The for-loop of languages like [[ALGOL]], [[Simula]], [[BASIC]], [[Pascal (programming language)|Pascal]], [[Modula]], [[Oberon (programming language)|Oberon]], [[Ada (programming language)|Ada]], [[MATLAB]], [[OCaml]], [[F Sharp (programming language)|F#]], and so on, requires a [[Control flow|control variable]] with start- and end-values, which looks something like this: <syntaxhighlight Lang="pascal"> for i = first to last do statement (* or just *) for i = first..last do statement </syntaxhighlight> Depending on the language, an explicit [[Assignment (computer science)|assignment]] sign may be used in place of the [[equal sign]] (and some languages require the word {{code|int}} 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 (programming language)|C language]]. It requires 3 parts: the [[Declaration (computer programming)|initialization]] ([[loop variant]]), the [[Boolean algebra|condition]], and the advancement to the next iteration. All these three parts are optional. This type of "semicolon loops" came from [[B (programming language)|B programming language]] and it was originally invented by [[Stephen C. Johnson|Stephen Johnson]].<ref name="ken">{{cite AV media |last=Thompson |first=Ken |author-link=Ken Thompson |website=[[YouTube]] |url=https://www.youtube.com/watch?v=EY6q5dv_B-o&t=2330 |title=VCF East 2019 β Brian Kernighan interviews Ken Thompson |archive-url=https://ghostarchive.org/varchive/youtube/20211212/EY6q5dv_B-o |archive-date=2021-12-12 |url-status=live |quote=I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it. |access-date=2020-11-16}}{{cbignore}}</ref> 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 (programming language)|Java]]. <syntaxhighlight Lang="java"> // Prints the numbers from 0 to 99 (and not 100), each followed by a space. for (int i=0; i<100; i++) { System.out.print(i); System.out.print(' '); } System.out.println(); </syntaxhighlight> These loops are also sometimes named ''numeric for-loops'' when contrasted with foreach loops (see below). ===Iterator-based for-loops=== {{Further|Foreach loop}} 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 which the loop variable takes on each of the values in a sequence or other data collection. A representative example in [[Python (programming language)|Python]] is: <syntaxhighlight Lang="python"> for an item in some_iterable_object: do_something() do_something_else() </syntaxhighlight> Where {{code|some_iterable_object}} 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 {{code|for each}}, as well as a three-expression for-loop (see below) under the name {{code|for}}. ===Vectorised for-loops=== Some languages offer a for-loop that acts as if processing all iterations [[Automatic vectorization|in parallel]], such as the {{code|for all}} keyword in [[Fortran 95]] which has the interpretation that ''all'' [[Sides of an equation|right-hand-side]] expressions are evaluated before ''any'' assignments are made, as distinct from the explicit iteration form. For example, in the {{code|for}} statement in the following pseudocode fragment, when calculating the new value for {{code|A(i)}}, except for the first (with {{code|1=i = 2}}) the reference to {{code|A(i - 1)}} will obtain the new value that had been placed there in the previous step. In the {{code|for all}} version, however, each calculation refers only to the original, unaltered {{code|A}}. '''for''' i := 2 : N - 1 '''do''' A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3; '''next''' i; '''for all''' i := 2 : N - 1 '''do''' A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3; The difference may be significant. Some languages (such as PL/I, Fortran 95) also offer array assignment statements, that enable many for-loops to be omitted. Thus pseudocode such as {{code|1=A:= 0;}} 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. ===Compound for-loops=== Introduced with [[ALGOL 68]] and followed by PL/I, this allows the iteration of a loop to be compounded with a test, as in for i := 1 : N while A(i) > 0 do ''etc.'' That is, a value is assigned to the loop variable ''i'' and only if the ''while expression'' is '''true''' will the loop body be executed. If the result were '''false''' the for-loop's execution stops short. Granted that the loop variable's value ''is'' defined after the termination of the loop, then the above statement will find the first non-positive element in array ''A'' (and if no such, its value will be ''N + 1''), or, with suitable variations, the first non-blank character in a string, and so on.
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)