The for loop is one of the most common
loop structures available in
procedural and procedural based
object oriented languages. Unfortunately, at some point in the history of these languages, some differences in
syntax and
style have occurred.
In each language group, two snippets will be presented (please note that the exact code may not be correct, however, the for loop will be). The first will be count from '1' to '10'. The second will be count from '100' to '10' - counted by 10s.
The earliest instance of the for loop comes Algol. The following example is from Algol 60
for i := 1 until 10
do
print i
od
for j := 100 step -10 until 10
do
print i
od
This barely shows the power of the for loop and the flexibility it has. Unlike most languages to follow, ALGOL 60 did not need the step to be an integer. '
1 step 3.14159 until 100' was perfectly valid. Furthermore, the range is very flexible as a list of expressions:
for index := 1 step 2 until 50, 60, 70, 80, index +1 until 100 do
results in index = (1, 3, 5, 7, ... , 49, 60, 70, 80, 81, 82, ... , 100). Other oddities of the Algol loop include that the parameter list is re-evaluated every loop. This can cause some hedaches (as seen in the above example).
The iterative loop that is associated with 'for' within FORTRAN is the do loop. This loop provides the same functionality as the for loop.
The do statement has the following format:
DO n I = INITIAL, LIMIT, STEP
The loop
index may not be changed within the loop, and modification of variables in the constraints will have no effect upon the loop itself if done within the loop.
DO 20 i = 1, 10
PRINT*, i
20 CONTINUE
DO 40 j = 100, 10, -10
PRINT*, j
40 CONTINUE
It should be noted that the classic use of indexes starting with 'i' comes from FORTRAN. Within FORTRAN, an
integer value
must begin with one of:
i, j, k, l, m, n.
Real values may start with any other letter. Thus '
i' was the first integer variable for use, '
j' the next and so forth. '
index' was also always an integer variable within FORTRAN, but '
control' was a real variable.
Pascal and various forms of basic use this style of for also though not quite as flexible as Algol's for. Within Pascal:
for i := 1 to 10 do
begin
writeln(i);
end;
for j := 100 downto 10 do
begin
if(j % 10 = 0)
begin
writeln(j);
end
end;
You will note the lack of the step used in the downto. In various dialetcs of the pascal language (unfortunately, it is not well defined) the step option to a for loop is not available. An alternate way would be to count from 10 to 1, and multiply the value by 10 before printing it. Furthermore, there is no way to leave a loop in pascal other than with
goto.
The code in BASIC languages is similar to that of pascal:
for i = 1 to 10
print i
next i
for j = 100 to 10 step 10
print i
next i
As a surprise to some, there was no for loop within the B programing language. The C syntax for loop that is found in C, C++, java, perl, Tcl, and several other languages has 3 parts to it
- Initial values
- test (while true, the loop continues)
- increment
This explicit definition is from the historical close relationship between C and
assembly, allowing for a simpler complier and more explicit control over exactly what is happening. Furthermore, other design choices:
- There is no explicit loop variable
- Everything can be changed in the loop
- Pretest
- The first expression is evaluated once, but the other two are evaluated with each iteration
- This loop statement is the most flexible
(from
http://courses.cs.vt.edu/~cs3304/Fall01/notes/)
for (i = 1; i <= 10; i++)
{ printf("%d\n",i); }
for (j = 100; j > 9; j -= 10)
{ printf("%d\n",j); }
Any of these parts may be
empty, allowing for an
infinite loop if the test is empty. It is not uncommon to see
for (;;) in C code. Furthermore, there is nothing saying that any of these parts have to have anything in common with any other part.
for (line = 1; !feof(file); line++, total++) which runs until the end of a file. Multiple statements may be done within a single expression (in this case, the value would be the last one done, not that it matters here).
C++ and java have the added ability of being able to declare the variable that has the scope of the loop within the initial setup.
Scripting languages often have the array of indexes defined rather than as an expression. In csh one finds 'for file (*.gif)'. Python and perl both allow for similar structures:
Python | Perl
for i in range(10): | for $i (1..10)
print i+1 | { print $i; }
|
(The
range(n) function produces numbers from 0 to
n - 1. Hence, it is necessary to add 1)
This style of for loop is more often thought of as a 'foreach' loop (in perl, for may be used as a C style loop, or an alias for foreach which also exists). Unfortunately, it is not quite as flexible as the for loop because the array needs to be built with all of the indexes. This also means that when a large number of indexes is required (integrating from 1 to 1,000,000), the entire list of 1,000,000 elements must be built. This can be wasteful of memory. Python does have an xrange function that only returns one element at a time, avoiding this problem.
Python:
for j in [100,90,80,70,60,50,40,30,20,10]:
print j
Perl:
for $j (map { $_ * 10} (10 .. 1))
{ print $j; }
This style of loop does have the advantage that it dosn't matter what you stick in it - the foreach style loop can work on anything, be it numbers or words. The order it runs in is the order that the array contains.
Python's for loop also allows the use of multiple indexes at the same time.
for i,j in ['a',1,'b',2,'c',3]:
print '%i - %s' % (i,j)
produces the following output:
a - 1
b - 2
c - 3
The
iterator will assign values in order to each variable from the list that is provided. Combining this with the
zip function that returns an
interwoven list from two or more lists (if they are unequal size, it stops with the shortest one) this can be very useful. The iterator can work over any sequence or object (the list iterator used above simply returns the next element in the list, however, iterators are not confined only to lists but can be used with any object where a
next function can be created).
Please do realize, that in almost every language, the for loop is one of the most flexible loops providing for a large range of possible code solutions that is impossible to do more than hint at. This has been a survey of the for loop and was by no means meant to be an in depth study of the for in various languages.