In What Order Does a for Loop Statement Read

Control flow statement

In computer science, a for-loop (or just for loop) is a command menstruation statement for specifying iteration, which allows code to exist executed repeatedly. Various keywords are used to specify this statement: descendants of ALGOL use "for", while descendants of Fortran utilize "do". There are other possibilities, for instance COBOL which uses "PERFORM VARYING".

A for-loop has two parts: a header specifying the iteration, and a body which is executed once per iteration. The header oftentimes declares an explicit loop counter or loop variable, which allows the body to know which iteration is being executed. For-loops are typically used when the number of iterations is known before entering the loop. For-loops tin be thought of equally shorthands for while-loops which increment and test a loop variable.

The name for-loop comes from the word for, which is used as the keyword in many programming languages to introduce a for-loop. The term in English dates to ALGOL 58 and was popularized in the influential after ALGOL 60; it is the direct translation of the earlier German für, used in Superplan (1949–1951) by Heinz Rutishauser, who also was involved in defining ALGOL 58 and ALGOL 60.[ citation needed ] The loop body is executed "for" the given values of the loop variable, though this is more explicit in the ALGOL version of the statement, in which a listing of possible values and/or increments can be specified.

In FORTRAN and PL/I, the keyword DO is used for the same thing and it is called a do-loop; this is unlike from a do-while loop.

FOR [edit]

For loop analogy, from i=0 to i=2, resulting in data1=200

A for-loop statement is available in most imperative programming languages. Even ignoring pocket-sized differences in syntax in that location are many differences in how these statements work and the level of expressiveness they support. By and large, for-loops fall into one of the following categories:

Traditional for-loops [edit]

The for-loop of languages like ALGOL, Simula, BASIC, Pascal, Modula, Oberon, Ada, Matlab, Ocaml, F#, and so on, requires a control variable with kickoff- and end-values and looks something similar this:

                        for            i            =            beginning            to            last            do            statement            (* or just *)            for            i            =            showtime            ..            last            do            statement          

Depending on the language, an explicit assignment sign may be used in place of the equal sign (and some languages require the give-and-take int fifty-fifty in the numerical case). An optional footstep-value (an increment or decrement ≠ 1) may also be included, although the exact syntaxes used for this differs a bit more betwixt the languages. Some languages require a split declaration of the control variable, some do not.

Another form was popularized by the C programming language. It requires 3 parts: the initialization (loop variant), the condition, and the advancement to the next iteration. All these three parts are optional.[1] This type of "semicolon loops" came from B programming language and it was originally invented by Stephen Johnson.[ii]

In the initialization part, whatever variables needed are declared (and normally assigned values). If multiple variables are alleged, they should all be of the same blazon. The condition office checks a sure condition and exits the loop if faux, fifty-fifty if the loop is never executed. If the status is true, and then the lines of code within the loop are executed. The advocacy to the next iteration part is performed exactly once every fourth dimension the loop ends. The loop is and then repeated if the condition evaluates to true.

Here is an instance of the C-manner traditional for-loop in Java.

                        // Prints the numbers from 0 to 99 (and not 100), each followed past a space.                        for            (            int            i            =            0            ;            i            <            100            ;            i            ++            )            {            Organization            .            out            .            impress            (            i            );            Arrangement            .            out            .            impress            (            ' '            );            }            Organization            .            out            .            println            ();          

These loops are also sometimes called numeric for-loops when assorted with foreach loops(see below).

Iterator-based for-loops [edit]

This type of for-loop is a generalisation of the numeric range type of for-loop, every bit it allows for the enumeration of sets of items other than number sequences. Information technology 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 is:

                        for            item            in            some_iterable_object            :            do_something            ()            do_something_else            ()          

Where some_iterable_object is either a data drove that supports implicit iteration (like a list of employee's names), or may in fact be an iterator itself. Some languages have this in improver to another for-loop syntax; notably, PHP has this type of loop under the proper name for each, as well every bit a 3-expression for-loop (encounter below) under the name for.

Vectorised for-loops [edit]

Some languages offer a for-loop that acts as if processing all iterations in parallel, such as the for all keyword in FORTRAN 95 which has the interpretation that all right-hand-side expressions are evaluated earlier whatever assignments are made, equally distinct from the explicit iteration grade. For example, in the for statement in the following pseudocode fragment, when computing the new value for A(i), except for the first (with i = 2) the reference to A(i - 1) will obtain the new value that had been placed at that place in the previous step. In the for all version, however, each calculation refers merely to the original, unaltered A.

          for          i := 2 : Northward - 1          practice          A(i) := [A(i - one) + A(i) + A(i + one)] / 3;          adjacent          i;          for all          i := two : N - one          exercise          A(i) := [A(i - 1) + A(i) + A(i + 1)] / 3;        

The difference may be significant.

Some languages (such equally FORTRAN 95, PL/I) also offering array assignment statements, that enable many for-loops to exist omitted. Thus pseudocode such as A := 0; would set all elements of array A to goose egg, no thing its size or dimensionality. The example loop could be rendered equally

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

But whether that would be rendered in the manner of the for-loop or the for all-loop or something else may not exist conspicuously described in the compiler transmission.

Chemical compound for-loops [edit]

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 : Due north while A(i) > 0 exercise          etc.        

That is, a value is assigned to the loop variable i and merely if the while expression is true will the loop body be executed. If the event were false the for-loop's execution stops brusk. Granted that the loop variable's value is defined later on the termination of the loop, and so the higher up argument will discover the first not-positive element in array A (and if no such, its value will be N + one), or, with suitable variations, the beginning non-blank character in a string, and then on.

Loop counters [edit]

In reckoner programming a loop counter is the variable that controls the iterations of a loop (a computer programming linguistic communication construct). It is and so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequences (example., starting at 0 and terminate at 10 in increments of 1)

Loop counters change with each iteration of a loop, providing a unique value for each private iteration. The loop counter is used to decide when the loop should terminate and for the plan flow to go on to the side by side education later on the loop.

A mutual identifier naming convention is for the loop counter to apply the variable names i, j, and k (and so on if needed), where i would be the about outer loop, j the side by side inner loop, etc. The reverse order is also used by some programmers. This fashion is generally agreed to have originated from the early programming of FORTRAN[ citation needed ], where these variable names outset with these messages were implicitly declared every bit having an integer type, and so were obvious choices for loop counters that were simply 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 employ of reduplicated letters for the alphabetize, 2, jj, and kk, as this allows easier searching and search-replacing than using a single letter of the alphabet.[3]

Instance [edit]

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

                        for                                    (            i                                    =                                    0            ;                                    i                                    <                                    100            ;                                    i            ++            )                                    {                                                for                                    (            j                                    =                                    i            ;                                    j                                    <                                    10            ;                                    j            ++            )                                    {                                                some_function            (            i            ,                                    j            );                                                }                        }                      

It has been shown that a nested for loop, as in to a higher place example, performs more computations per unit of measurement time than a loop without it. This machine-independent optimisation means the nested for loop will finish faster, given the aforementioned number of computations to perform. This is an advantage nested for loop has over nested while loop, which behaves differently.[4]

For loops in C can as well exist used to print the reverse of a word. As:

                        for                                    (            i                                    =                                    0            ;                                    i                                    <                                    6            ;                                    i            ++            )                                    {                                                scanf            (            "%c"            ,                                    &            a            [            i            ]);                        }                        for                                    (            i                                    =                                    4            ;                                    i                                    >=                                    0            ;                                    i            --            )                                    {                                                printf            (            "%c"            ,                                    a            [            i            ]);                        }                      

Hither, if the input is apple tree, the output will be elppa.

Additional semantics and constructs [edit]

Use as space loops [edit]

This C-style for-loop is usually the source of an space loop since the fundamental steps of iteration are completely in the control of the programmer. In fact, when infinite loops are intended, this type of for-loop tin be used (with empty expressions), such every bit:

This style is used instead of space while (ane) loops to avert a type conversion alert in some C/C++ compilers.[5] Some programmers prefer the more succinct for (;;) course over the semantically equivalent but more verbose while (truthful) form.

Early leave and continuation [edit]

Some languages may also provide other supporting statements, which when present tin alter how the for-loop iteration proceeds. Common among these are the break and continue statements establish in C and its derivatives. The break statement causes the inner-most loop to exist terminated immediately when executed. The go on argument will move at in one case to the next iteration without farther progress through the loop body for the electric current iteration. A for statement besides terminates when a break, goto, or return statement inside 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 95:

                        DO                        I            =            1            ,            Northward            statements            !Executed for all values of "I", up to a disaster if whatsoever.            IF            (            no            good            )            CYCLE            !Skip this value of "I", continue with the adjacent.            statements            !Executed only where goodness prevails.            IF            (            disaster            )            EXIT            !Carelessness the loop.            statements            !While good and, no disaster.            END DO            !Should align with the "DO".          

Some languages offer further facilities such as naming the diverse loop statements so that with multiple nested loops there is no doubt equally to which loop is involved. Fortran 95, for example:

                        X1            :            Practise                        I            =            ane            ,            N            statements            X2            :            DO                        J            =            1            ,            K            statements            IF            (            trouble            )            CYCLE                        X1            statements            Finish DO                        X2            statements            END DO                        X1          

Thus, when "trouble" is detected in the inner loop, the Bike X1 (not X2) means that the skip will be to the side by side iteration for I, not J. The compiler will too be checking that each Stop Exercise has the appropriate label for its position: this is not just a documentation aid. The programmer must still lawmaking the problem correctly, but some possible blunders will be blocked.

Loop variable scope and semantics [edit]

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 whatsoever value in the loop variable, or perchance even leaves it unchanged because the loop value was held in a register and never stored to retentivity. Actual behaviour may even vary according to the compiler's optimization settings, as with the Honywell Fortran66 compiler.

In some languages (not C or C++) the loop variable is immutable within the scope of the loop trunk, with any attempt to modify its value being regarded every bit a semantic error. Such modifications are sometimes a result of a developer fault, which can be very difficult to identify once fabricated. However, merely overt changes are probable to be detected by the compiler. Situations where the accost of the loop variable is passed as an statement to a subroutine brand it very difficult to check, considering the routine's behavior is in general unknowable to the compiler. Some examples in the mode of Fortran:

                        DO                        I            =            i            ,            N            I            =            7            !Overt aligning of the loop variable. Compiler complaint likely.            Z            =            ADJUST            (            I            )            !Function "ADJUST" might change "I", to uncertain issue.            normal            statements            !Retentiveness might fade that "I" is the loop variable.            Impress            (            A            (            I            ),            B            (            I            ),            I            =            1            ,            N            ,            2            )            !Implicit for-loop to impress odd elements of arrays A and B, reusing "I"...            Print                        I            !What value volition be presented?            END DO            !How many times will the loop be executed?          

A common approach is to calculate the iteration count at the start of a loop (with conscientious attention to overflow as in for i := 0 : 65535 practice ... ; in sixteen-chip integer arithmetic) and with each iteration decrement this count while too adjusting the value of I: double counting results. Notwithstanding, adjustments to the value of I within the loop will not change the number of iterations executed.

Still another possibility is that the code generated may employ an auxiliary variable every bit the loop variable, peradventure held in a auto register, whose value may or may not exist copied to I on each iteration. Again, modifications of I would not affect the command of the loop, but at present a disjunction is possible: within the loop, references to the value of I might be to the (peradventure altered) electric current value of I or to the auxiliary variable (held safe from improper modification) and confusing results are guaranteed. For instance, within the loop a reference to element I of an assortment would probable employ the auxiliary variable (especially if information technology were held in a machine register), but if I is a parameter to some routine (for case, a print-argument to reveal its value), information technology would likely be a reference to the proper variable I instead. Information technology is all-time to avoid such possibilities.

Adjustment of bounds [edit]

Simply equally the index variable might be modified within a for-loop, and so also may its premises and management. But to uncertain effect. A compiler may prevent such attempts, they may take no effect, or they might fifty-fifty work properly - though many would declare that to do so would be incorrect. Consider a statement such as

          for          i := commencement : final : step          do          A(i) := A(i) / A(final);        

If the approach to compiling such a loop was to be the evaluation of outset, concluding and step and the calculation of an iteration count via something like (last - start)/step once just at the first, then if those items were simple variables and their values were somehow adjusted during the iterations, this would have no event on the iteration count even if the element selected for division by A(terminal) changed.

List of value ranges [edit]

PL/I and Algol 68, allows 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 volition execute the loop with half-dozen values of i: 1, vii, 12, thirteen, 14, 15:

                        do                        i                        =                                    1            ,                                    seven            ,                                    12                                    to                                    15            ;                                                /*statements*/                        cease            ;                      

Equivalence with while-loops [edit]

A for-loop is by and large 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 < v     counter := counter + i     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 [edit]

Given an action that must be repeated, for instance, five times, different languages' for-loops will be written differently. The syntax for a iii-expression for-loop is nearly identical in all languages that accept it, after accounting for different styles of block termination and so on.

1957: FORTRAN [edit]

Fortran'south equivalent of the for loop is the DO loop, using the keyword do instead of for, The syntax of Fortran's Exercise loop is:

                                                DO                        characterization            counter            =            commencement            ,            last            ,            step                                    statements            characterization            argument          

The following ii examples conduct 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 5 (inclusive).

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

In Fortran 77 (or later on), this may besides be written as:

                        do                        counter            =            i            ,            v            write            (            *            ,            '(i2)'            )            counter            end exercise          

The stride part may be omitted if the step is 1. Example:

                        * DO loop example.                                    Program                        MAIN                                    SUM                        SQ            =            0                                    Exercise                        199            I            =            1            ,            9999999                                    IF            (            SUM                        SQ            .            GT            .            1000            )            Get            TO            200            199                        SUM                        SQ            =            SUM                        SQ            +            I            **            two            200                        Print                        206            ,            SUMSQ            206                        FORMAT            (            I2            )                                    Cease          

Spaces are irrelevant in fixed-form Fortran statements, thus SUM SQ is the same as SUMSQ. In the modern free-grade Fortran fashion, blanks are pregnant.

In Fortran 90, the Get TO may be avoided past using an Exit statement.

                        * Practise loop example.                                    program                        main                                    implicit none                                    integer            ::            sumsq                                    integer            ::            i                                    sumsq            =            0                                    do                        i            =            one            ,            9999999                                    if            (            sumsq            >            100            0.0            )            exit                                    sumsq            =            sumsq            +            i            **            2                                    end do                                    print            *            ,            sumsq                                    end program          

1958: ALGOL [edit]

ALGOL 58 introduced the for statement, using the grade as Superplan:

          FOR          Identifier          =          Base of operations          (Divergence)          Limit        

For case to impress 0 to 10 incremented by 1:

FOR 10 = 0 (1) 10 Begin Impress (FL) = x END        

1960: COBOL [edit]

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 lawmaking occupying a separate paragraph. Ignoring the need for declaring and initialising variables, the COBOL equivalent of a for-loop would be.

                                                PERFORM            SQ-ROUTINE            VARYING            I            FROM            one                        BY            1                        UNTIL            I            >            1000                                    SQ-ROUTINE                                    Add together            I            **            ii                        TO            SUM-SQ            .          

In the 1980s the addition of in-line loops and "structured" statements such every bit END-PERFORM resulted in a for-loop with a more familiar structure.

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

If the PERFORM verb has the optional clause Test AFTER, the resulting loop is slightly different: the loop body is executed at least once, earlier any test.

1964: BASIC [edit]

Loops in BASIC are sometimes called for-next loops.

                        10                                    REM THIS FOR LOOP PRINTS ODD NUMBERS FROM one TO fifteen            20                                    FOR                                    I                                    =                                    1                                    TO                                    15                                    Footstep                                    2            30                                    PRINT                                    I            40                                    NEXT                                    I          

Notice that the terminate-loop marker specifies the proper noun of the alphabetize variable, which must correspond to the name of the alphabetize variable in the start of the for-loop. Some languages (PL/I, FORTRAN 95 and later) allow a argument label on the start of a for-loop that can be matched by the compiler confronting the aforementioned text on the corresponding end-loop argument. Fortran also allows the EXIT and Cycle statements to proper noun this text; in a nest of loops this makes articulate 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 tin a characterization be the same equally the name of a variable, such as the index variable for the loop.

1964: PL/I [edit]

                        exercise                        counter                        =                                    ane                                    to                                    5                                    by                                    ane            ;                                    /* "by 1" is the default if non specified */                                                /*statements*/            ;                                                terminate            ;                      

The Leave 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 ITERATE argument to terminate the electric current loop iteration and brainstorm the adjacent.

1968: Algol 68 [edit]

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 listing of such ranges. In that location are several unusual aspects of the construct

  • only the practise ~ od portion was compulsory, in which instance the loop will iterate indefinitely.
  • thus the clause to 100 exercise ~ od, will iterate exactly 100 times.
  • the while syntactic chemical element allowed a programmer to break from a for loop early, every bit in:
INT sum sq := 0; FOR i  WHILE   impress(("And then far:", i, new line)); # Interposed for tracing purposes. #   sum sq ≠ lxx↑2                    # This is the test for the WHILE   # DO   sum sq +:= i↑2 OD        

Subsequent extensions to the standard Algol68 allowed the to syntactic element to exist replaced with upto and downto to achieve a pocket-size optimization. The same compilers also incorporated:

until
for late loop termination.
foreach
for working on arrays in parallel.

1970: Pascal [edit]

                        for            Counter            :=            one            to            five            do            (*statement*)            ;          

Decrementing (counting backwards) is using downto keyword instead of to, as in:

                        for            Counter            :=            5            downto            1            do            (*statement*)            ;          

The numeric-range for-loop varies somewhat more.

1972: C/C++ [edit]

                        for                                    (            initialization            ;                                    condition            ;                                    increment            /            decrement            )                                                statement                      

The statement is often a block statement; an example of this would be:

                        //Using for-loops to add numbers ane - 5            int                                    sum                                    =                                    0            ;                        for                                    (            int                                    i                                    =                                    1            ;                                    i                                    <                                    6            ;                                    ++            i            )                                    {                                                sum                                    +=                                    i            ;                        }                      

The ISO/IEC 9899:1999 publication (normally known as C99) also allows initial declarations in for loops. All the three sections in the for loop are optional.

1972: Smalltalk [edit]

                        i            to:            v            practice:            [            :            counter            |            "statements"            ]          

Opposite to other languages, in Smalltalk a for-loop is not a linguistic communication construct but divers in the class Number as a method with two parameters, the terminate value and a closure, using self as start value.

1980: Ada [edit]

                        for            Counter            in            ane            ..            5            loop            -- statements            cease            loop            ;          

The exit statement may exist used to exit the loop. Loops can be labeled, and go out may leave a specifically labeled loop in a group of nested loops:

                        Counting            :            for            Counter            in            ane            ..            five            loop            Triangle            :            for            Secondary_Index            in            2            ..            Counter            loop            -- statements            exit            Counting            ;            -- statements            terminate            loop            Triangle            ;            end            loop            Counting            ;          

1980: Maple [edit]

Maple has ii forms of for-loop, one for iterating of 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 office, if present, must come up first. The remaining parts ( from f , past b , to t , while westward ) can announced in whatever order.

Iterating over a container is done using this form of loop:

          for          e          in          c          while          w          exercise          # loop body          od;        

The in c clause specifies the container, which may be a listing, set, sum, product, unevaluated function, assortment, or an object implementing an iterator.

A for-loop may be terminated by od , end , or end exercise .

1982: Maxima CAS [edit]

In Maxima CAS one can employ too not integer values :

            for x:0.5 step 0.1 thru 0.nine do     /* "Do something with x" */          

1982: PostScript [edit]

The for-loop, written every bit [initial] [increase] [limit] { ... } for initialises an internal variable, executes the body as long as the internal variable is not more than limit (or not less, if 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.[6]

There is also a simple repeat-loop. The repeat-loop, written as X { ... } repeat, repeats the trunk exactly Ten times.[7]

1983: Ada 83 and above [edit]

                        procedure            Main            is            Sum_Sq            :            Integer            :=            0            ;            begin            for            I            in            1            ..            9999999            loop            if            Sum_Sq            <=            yard            then            Sum_Sq            :=            Sum_Sq            +            I            **            2            end            if            ;            end            loop            ;            end            ;          

1984: MATLAB [edit]

                        for                                    northward                                    =                                    1            :            5                                                            --                                    statements                        terminate                      

After the loop, northward would be v in this instance.

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

1987: Perl [edit]

                        for            (            $counter            =            1            ;            $counter            <=            v            ;            $counter            ++            )            {            # implicitly or predefined variable            # statements;            }            for            (            my            $counter            =            1            ;            $counter            <=            5            ;            $counter            ++            )            {            # variable individual to the loop            # statements;            }            for            (            1            ..            5            )            {            # variable implicitly chosen $_; 1..v creates a listing of these v elements            # statements;            }            statement            for            1            ..            5            ;            # about same (only 1 statement) with natural language order            for            my            $counter            (            one            ..            5            )            {            # variable private to the loop            # statements;            }          

(Note that "there's more than one way to practice it" is a Perl programming motto.)

1988: Mathematica [edit]

The construct corresponding to most other languages' for-loop is called Practise in Mathematica

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

                        For            [            10            =            0            ,            ten            <=            i            ,            x            +=            0            .            1            ,            f            [            x            ]            ]          

1989: Bash [edit]

                        # first grade            for            i            in            one            2            iii            iv            5            do            # must accept at to the lowest degree one command in loop            echo            $i            # just print value of i            done          
                        # second form            for            ((            i            =            1            ;            i <=            5            ;            i++            ))            do            # must take at least ane command in loop            echo            $i            # only print value of i            done          

Note that an empty loop (i.e., i with no commands between do and washed) is a syntax error. If the in a higher place loops contained merely comments, execution would event in the message "syntax error near unexpected token 'done'".

1990: Haskell [edit]

The built-in imperative forM_ maps a monadic expression into a list, every bit

                        forM_            [            1            ..            five            ]            $            \            indx            ->            do            statements          

or get each iteration result as a list in

                        statements_result_list            <-            class            [            ane            ..            5            ]            $            \            indx            ->            do            statements          

But, if you want to relieve the infinite of the [i..5] list, a more accurate monadic forLoop_ structure tin exist defined every bit

                        import            Control.Monad            as            Yard            forLoopM_            ::            Monad            m            =>            a            ->            (            a            ->            Bool            )            ->            (            a            ->            a            )            ->            (            a            ->            m            ()            )            ->            thousand            ()            forLoopM_            indx            prop            incr            f            =            exercise            f            indx            M            .            when            (            prop            next            )            $            forLoopM_            next            prop            incr            f            where            next            =            incr            indx          

and used as:

                        forLoopM_            (            0            ::            Int            )            (            <            len            )            (            +            1            )            $            \            indx            ->            do            -- whatever with the alphabetize          

1991: Oberon-2, Oberon-07, or Component Pascal [edit]

                        FOR            Counter            :=            1            TO            five            DO            (* statement sequence *)            Terminate          

Note that in the original Oberon linguistic communication the for-loop was omitted in favor of the more full general Oberon loop construct. The for-loop was reintroduced in Oberon-two.

1991: Python [edit]

Python does non contain the classical for loop, rather a foreach loop is used to iterate over the output of the builtin range() function which returns an iterable list of integers.

                        for            i            in            range            (            i            ,            6            ):            # gives i values from 1 to v inclusive (merely non 6)            # statements            print            (            i            )            # if nosotros want 6 we must exercise the following            for            i            in            range            (            1            ,            6            +            1            ):            # gives i values from one to 6            # statements            print            (            i            )          

Using range(6) would run the loop from 0 to 5.

1993: AppleScript [edit]

                        repeat            with            i            from            1            to            5            -- statements            log            i            end            repeat          

You can also iterate through a listing of items, like to what y'all can do with arrays in other languages:

                        gear up            x            to            {            1            ,            "waffles"            ,            "bacon"            ,            5.ane            ,            faux            }            repeat            with            i            in            x            log            i            end            repeat          

Yous may also utilise get out echo to get out a loop at whatsoever time. Unlike other languages, AppleScript does non currently have whatever command to continue to the next iteration of a loop.

1993: Lua [edit]

                        for            i            =            commencement            ,            cease            ,            interval            exercise            -- statements            terminate          

So, this code

                        for            i            =            i            ,            5            ,            2            do            print            (            i            )            cease          

will print:

For-loops can also loop through a table using

to iterate numerically through arrays and

to iterate randomly through dictionaries.

Generic for-loop making use of closures:

                        for            name            ,            phone            ,            accost            in            contacts            ()            practice            -- contacts() must exist an iterator function            stop          

1995: CFML [edit]

Script syntax [edit]

Simple index loop:

                        for            (            i            =            1            ;            i            <=            5            ;            i            ++            )            {            // statements            }          

Using an array:

                        for            (            i            in            [            i            ,            2            ,            3            ,            four            ,            v            ])            {            // statements            }          

Using a list of cord values:

                        loop            alphabetize            =            "i"            list            =            "1;ii,iii;4,5"            delimiters            =            ",;"            {            // statements            }          

The above list case is only available in the dialect of CFML used by Lucee and Railo.

Tag syntax [edit]

Simple alphabetize loop:

                        <cfloop            alphabetize            =            "i"            from            =            "1"            to            =            "5"            >            <!--- statements --->            </cfloop>          

Using an array:

                        <cfloop            index            =            "i"            array            =            "            #[one,ii,3,iv,5]#            "            >            <!--- statements --->            </cfloop>          

Using a "list" of string values:

                        <cfloop            index            =            "i"            list            =            "ane;ii,three;four,5"            delimiters            =            ",;"            >            <!--- statements --->            </cfloop>          

1995: Java [edit]

                        for            (            int            i            =            0            ;            i            <            5            ;            i            ++            )            {            //perform functions within the loop;            //can apply the statement 'break;' to exit early;            //can use the statement 'go along;' to skip the current iteration            }          

For the extended for-loop, see Foreach loop § Coffee.

1995: JavaScript [edit]

JavaScript supports C-style "three-expression" loops. The break and continue statements are supported inside loops.

                        for            (            var            i            =            0            ;            i            <            5            ;            i            ++            )            {            // ...            }          

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

                        for            (            var            fundamental            in            array            )            {            // also works for assoc. arrays            // use array[key]            ...            }          

1995: PHP [edit]

This prints out a triangle of *

                        for            (            $i            =            0            ;            $i            <=            5            ;            $i            ++            )            {            for            (            $j            =            0            ;            $j            <=            $i            ;            $j            ++            )            {            echo            "*"            ;            }            repeat            "<br />            \north            "            ;            }          

1995: Cherry [edit]

                        for            counter            in            ane            ..            five            # statements            end            5            .            times            do            |            counter            |            # counter iterates from 0 to 4            # statements            terminate            1            .            upto            (            5            )            exercise            |            counter            |            # statements            end          

Ruby has several possible syntaxes, including the above samples.

1996: OCaml [edit]

Meet expression syntax.[viii]

                        (* for_statement := "for" ident '='  expr  ( "to" ∣  "downto" ) expr "do" expr "done" *)            for            i            =            1            to            5            do            (* statements *)            done            ;;            for            j            =            5            downto            0            exercise            (* statements *)            done            ;;          

1998: ActionScript 3 [edit]

                        for            (            var            counter            :            uint            =            i            ;            counter            <=            five            ;            counter            ++){            //argument;            }          

2008: Small Basic [edit]

                        For            i            =            1            To            x            ' Statements            EndFor          

2008: Nim [edit]

Nim has a foreach-blazon loop and various operations for creating iterators.[9]

                        for            i            in            5            ..            10            :            # statements          

2009: Go [edit]

                        for            i            :=            0            ;            i            <=            10            ;            i            ++            {            // statements            }          

2010: Rust [edit]

                        for                                    i                                    in                                    0            ..            10                                    {                                                // statements            }                      

2012: Julia [edit]

                        for            j            =            1            :            10            # statements            end          

See too [edit]

  • Do while loop
  • Foreach
  • While loop

References [edit]

  1. ^ "For loops in C++".
  2. ^ Ken Thompson. "VCF Due east 2019 -- Brian Kernighan interviews Ken Thompson". Archived from the original on 2021-12-12. Retrieved 2020-11-16 . I saw Johnson's semicolon version of the for loop and I put that in [B], I stole it.
  3. ^ http://www.knosof.co.uk/vulnerabilities/loopcntrl.pdf Analysis of loop control variables in C
  4. ^ Inner loop program construct: A faster way for program execution
  5. ^ "Compiler Alarm (level four) C4127". Microsoft. Retrieved 29 June 2011.
  6. ^ PostScript Language Reference. Addison-Wesley Publishing Visitor. p. 596. ISBN0-201-37922-8.
  7. ^ "PostScript Tutorial - Loops".
  8. ^ "OCaml expression syntax". Archived from the original on 2013-04-12. Retrieved 2013-03-19 .
  9. ^ https://nim-lang.org/docs/arrangement.html#...i%2CT%2CT ".. iterator"

scotttherhang.blogspot.com

Source: https://en.wikipedia.org/wiki/For_loop

0 Response to "In What Order Does a for Loop Statement Read"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel