Loop constructs |
---|
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 loop counter 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 reserved word (or 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 für and was used in Superplan (1949–1951) by Heinz Rutishauser. Rutishauser was involved in defining ALGOL 58 and ALGOL 60.[1] 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 named a do-loop; this is different from a do while loop.