Opentopia Directory Encyclopedia Tools

For loop

Encyclopedia : F : FO : FOR : For loop


In most imperative computer programming languages, a for loop is a control flow statement which allows code to be executed iteratively.

Unlike many other kinds of loops, such as the while loop, the for loop is distinguished by an explicit loop counter or loop variable. This allows the body of the for loop (the code that is being repeatedly executed) to know about the sequencing of each iteration. For loops are also typically used when the number of iterations is known before entering the loop.

The name for loop comes from the English word , which is used as the keyword in most programming languages to introduce a for loop. In FORTRAN though, the keyword DO is used and it is called a do loop, but it is otherwise identical to the for loop described here.

Kinds of for loops

A for loop statement is available in many programming languages, yet even ignoring minor differences in syntax, there are many differences in how these statements work and what level of expressiveness they allow. Generally, for loops in programming languages fall into one of the following catagories:

Numeric ranges

This type of for loop is characterized by counting; enumerating each of the values within a numeric integer range, or arithmetic progression. The range is often specified by a beginning and ending number, and sometimes may include a step value (allowing one to count by two's or to count backwards for instance). A representative example in BASIC is:

FOR I = 1 TO 10
loop body
NEXT I
The loop variable I will take on the values 1, 2, ..., 9, 10 through each of the ten iterations of the loop's body. Different dialects of BASIC as well as other languages usually have different syntax and means of specifing the range of integers. It is common for the loop variable to be immutable within the scope of the loop body. Some languages may also provide another special statement, usually called a break statement, which can be used within the loop body to allow the loop to be terminated early.

Iterator-based for loops

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 orderable data collection. A representative example in Python is:

for item in list:
loop body
Where the list is either a data collection that supports implicit iteratation, or may in fact itself be an explicit iterator. This type of for loop is similar to but often more expressive than the foreach statement of some languages.

Three-expression for loops

for loop diagram
Enlarge
for loop diagram

This type of for loop is found in nearly all languages which share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer, a loop-test, and an incrementor. A representative example in C is:

for (counter = 1; counter <= 10; counter++)
loop body
The three control expressions, separated by semicolons here, are from left to right the initializer expression, the loop test expression, and the incrementer expression. The initializer is evaluated exactly once right at the beginning. The loop test expression is evaluated at the beginning of each iteration through the loop, and determines when the loop should exit. Finally, the incrementer expression is evaluated at the end of each loop iteration, and is usually responsible for altering the loop variable.

This type of for loop is usually the most expressive. It is also 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 is often used (with empty expressions), such as:

for (;;)
loop body

Equivalence with while loops

A for loop can always be converted into an equivalent while loop by incrementing a counter variable directly. The following pseudocode illustrates this technique:

factorial := 1
for counter from 1 to 5:
factorial := factorial * counter
is easily translated into the following while loop:

factorial := 1
counter := 1
while counter <= 5:
factorial := factorial * counter
counter := counter + 1

Examples

These for loops will calculate the factorial of the number five by iterating through all the numbers 1 through 5 and keeping a running product:

factorial=1
for ((i=1; $i<=5; i=$i+1)) do
factorial=$(($factorial * $i))
done
echo $factorial

Dim factorial As Long : factorial = 1
Dim counter As Integer
For counter = 1 To 5
factorial = factorial * counter
Next
Print factorial

Dim factorial As Integer = 1
For counter as Integer = 1 To 5
factorial = factorial * counter
Next counter
MsgBox Str( factorial )

long factorial = 1;
int counter;
for (counter = 1; counter <= 5; counter++)
factorial *= counter;
printf("%ld\n", factorial);

The syntax for the for loop is the same for C++, Java and C#:

long factorial = 1;
for (int counter = 1; counter <= 5; counter++)
factorial *= counter;
And finally, to print the result in each language:

std::cout << factorial << std::endl;    // In C++
System.out.println( factorial );        // In Java
System.Console.WriteLine( factorial );  // In C#

factorial = 1
for counter in range(1, 6):    # range() gives values to one less than the second argument
factorial *= counter
print factorial

var factorial = 1;
for (var counter = 1; counter <= 5; counter++) 
document.write(factorial);

my $factorial = 1;
for ( my $counter = 1; $counter <= 5; $counter++ ) 
print $factorial;
Using Perl's range operator gives the equivalent

my $factorial = 1;
for (1..5) 
print $factorial;

program Factorial
var
Counter, Factorial: integer;
begin
Factorial := 1;
for Counter := 1 to 5 do
Factorial := Factorial * Counter;
WriteLn(Factorial)
end.

Actionscript

for( n = 1 ; n < someConstantOrVar ; n++) 

See also

 


From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.

Search Titles
0123456789
ABCDEFGHIJ
KLMNOPQRST
UVWXYZ?

E-mail this article to:

Personal Message: