Iterating with foreach

foreach with Arrays


foreach element in array do statement
foreach element in array collect statement


When using traditional for loops to iterate over an array, it is easy to get the beginning or ending index wrong. Consider the irksome fact that only two of the following for loops correctly indexes through array elements:

for i := 1 to Length(array) do
   Print(array[i]);
for i := 1 to Length(array) - 1 do
   Print(array[i]);
for i := 0 to Length(array) - 1 do
   Print(array[i]);
for i := 0 to Length(array) do
   Print(array[i]);
for i := 1 to Length(array) do
   Print(array[i - 1]);
To avoid this morass, NewtonScript provides you with a bulletproof for loop--foreach.

A foreach loop iterates over each element in an array automatically. Here is the same example using the much simpler syntax of foreach:

foreach element in array do
   Print(element);
The element variable is a loop variable similar to the i loop variable found in the previous examples. There is a crucial difference between the two, however. The element loop variable does not take on successive index values (0, 1, etc.), but rather takes on successive element values (array[0], array[1], etc.).

As is the case with a standard for loop, the loop variable in foreach can be named anything--be it a single letter or a song:

foreach yellowSubmarine in array do
   Print(yellowSubmarine);

An online version of Programming for the Newton using Macintosh, 2nd ed. ©1996, 1994, Julie McKeehan and Neil Rhodes.

Last modified: 1 DEC 1996