What is the statement or block that is repeated known as in a loop structure?

In computer science a for-loop or for loop is a control flow statement for specifying iteration. Specifically, a for loop functions by running a section of code repeatedly until a certain condition has been satisfied.

For-loops have two parts: a header and a body. The header defines the iteration and the body is the code that is executed once per iteration. The header often declares an explicit or loop variable. This 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 can be thought of as shorthands for while-loops which increment and test a loop variable.

Various keywords are used to indicate the usage of a for loop: descendants of ALGOL use "for", while descendants of Fortran use "do". There are other possibilities, for example COBOL which uses "PERFORM VARYING".

The name for-loop comes from the word for. For 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 ALGOL 60. It is the direct translation of the earlier German and was used in Superplan [1949–1951] by Heinz Rutishauser. Rutishauser was involved in defining ALGOL 58 and ALGOL 60.[citation needed] The loop body is executed "for" the given values of the loop variable. This is more explicit in ALGOL versions of the for statement where a list of possible values and 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 different from a do-while loop.

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 there are many differences in how these statements work and the level of expressiveness they support. Generally, 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 start- and end-values, which looks something like this:

for i = first to last do statement
[* or just *]
for i = first..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 word

for [i = 0; i < 100; i++] {
    for [j = i; j < 10; j++] {
        some_function[i, j];
    }
}
9 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 differs 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. It requires 3 parts: the initialization [loop variant], the condition, and the advancement to the next iteration. All these three parts are optional. This type of "semicolon loops" came from B programming language and it was originally invented by Stephen Johnson.

In the initialization part, any variables needed are declared [and usually assigned values]. If multiple variables are declared, they should all be of 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.

// Prints the numbers from 0 to 99 [and not 100], each followed by a space. 

for [int i=0; i= 0; i--] {
    printf["%c", a[i]];
}
0 is either a data collection that supports implicit iteration [like a list of employee's names], or may in fact 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
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
1, as well as a three-expression for-loop [see below] under the name
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
2.

Vectorised for-loops[edit]

Some languages offer a for-loop that acts as if processing all iterations in parallel, such as the

for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
3 keyword in FORTRAN 95 which has the interpretation that all right-hand-side expressions are evaluated before any assignments are made, as distinct from the explicit iteration form. For example, in the
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
2 statement in the following pseudocode fragment, when calculating the new value for
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
5, except for the first [with
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
6] the reference to
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
7 will obtain the new value that had been placed there in the previous step. In the
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
3 version, however, each calculation refers only to the original, unaltered
for [i = 0; i < 6; i++] {
    scanf["%c", &a[i]];
}
for [i = 4; i >= 0; i--] {
    printf["%c", a[i]];
}
9.

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 FORTRAN 95, PL/I] also offer array assignment statements, that enable many for-loops to be omitted. Thus pseudocode such as

DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".
0 would set all elements of array A to zero, no matter its size or dimensionality. The example loop could be rendered as

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

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[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 : 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.

Loop counters[edit]

In computer programming, a loop counter is a control variable that controls the iterations of a loop [a computer programming language construct]. It is so named because most uses of this construct result in the variable taking on a range of integer values in some orderly sequences [example., starting at 0 and end at 10 in increments of 1]

Loop counters change with each iteration of a loop, providing a unique value for each individual iteration. The loop counter is used to decide when the loop should terminate and for the program flow to continue to the next instruction after the loop.

A common identifier naming convention is for the loop counter to use the variable names i, j, and k [and so on if needed], where i would be the most outer loop, j the next inner loop, etc. The reverse order is also used by some programmers. This style is generally agreed to have originated from the early programming of Fortran[citation needed], where these variable names beginning with these letters were implicitly declared as having an integer type, and so were obvious choices for loop counters that were only temporarily required. The practice dates back further to mathematical notation where indices for sums and multiplications are often i, j, etc. A variant convention is the use of reduplicated letters for the index, ii, jj, and kk, as this allows easier searching and search-replacing than using a single letter.

Example[edit]

An example of C code 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];
    }
}

For loops in C can also be 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]];
}

Here, if the input is

DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".
1, the output will be
DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".
2.

Additional semantics and constructs[edit]

Use as infinite loops[edit]

This C-style for-loop is commonly the source of an infinite loop since the fundamental steps of iteration are completely in the control of the programmer. In fact, when infinite loops are intended, this type of for-loop can be used [with empty expressions], such as:

This style is used instead of infinite

DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".
3 loops to avoid a type conversion warning in some C/C++ compilers. Some programmers prefer the more succinct
DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".
4 form over the semantically equivalent but more verbose
DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".
5 form.

Early exit and continuation[edit]

Some languages may also provide other supporting statements, which when present can alter how the for-loop iteration proceeds. Common among these are the break and statements found in C and its derivatives. The break statement causes the inner-most loop to be terminated immediately when executed. The continue statement will move at once to the next iteration without further progress through the loop body for the current iteration. A for statement also terminates when a break, goto, or return statement within the statement body is executed. [Wells] Other languages may have similar statements or otherwise provide means to alter the for-loop progress; for example in FORTRAN 95:

DO I = 1, N
  statements               !Executed for all values of "I", up to a disaster if any.
  IF [no good] CYCLE       !Skip this value of "I", continue with the next.
  statements               !Executed only where goodness prevails.
  IF [disaster] EXIT       !Abandon the loop.
  statements               !While good and, no disaster.
END DO                     !Should align with the "DO".

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

X1:DO I = 1,N
     statements
  X2:DO J = 1,M
       statements
       IF [trouble] CYCLE X1
       statements
     END DO X2
     statements
   END DO X1

Thus, when "trouble" is detected in the inner loop, the CYCLE X1 [not X2] means that the skip will be to the next iteration for I, not J. The compiler will also be checking that each END DO has the appropriate label for its position: this is not just a documentation aid. The programmer must still code the problem correctly, but some possible blunders will be blocked.

Loop variable scope and semantics[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 any value in the loop variable, or perhaps even leaves it unchanged because the loop value was held in a register and never stored to memory. 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 body, with any attempt to modify its value being regarded as a semantic error. Such modifications are sometimes a consequence of a programmer error, which can be very difficult to identify once made. However, only overt changes are likely to be detected by the compiler. Situations where the address of the loop variable is passed as an argument to a subroutine make it very difficult to check, because the routine's behavior is in general unknowable to the compiler. Some examples in the style of Fortran:

// Prints the numbers from 0 to 99 [and not 100], each followed by a space. 

for [int i=0; i

Chủ Đề