for each over arrays
for each walks an array in index order without an index. It has two forms, and the difference is whether you can change the elements:
'' for each gives a copy of each element; for each byref gives the
'' element itself.
dim as int32 prices( 1 to 4 ) = { 10, 20, 30, 40 }
for each p in prices
p = 0 '' changes the copy only
next
print "after writing to copies:";
for each p in prices : print p; : next
print
for each byref p in prices
p += p \ 10 '' changes the array
next
print "after for each byref:";
for each p in prices : print p; : next
print
'' The same works for an array of your own type.
type Item
as ustring label
as int32 count
end type
dim as Item stock( 0 to 2 )
stock( 0 ).label = "nuts" : stock( 1 ).label = "bolts"
stock( 2 ).label = "washers"
for each byref it in stock
it.count = len( it.label )
next
for each it in stock
print it.label; it.count
next
'' A grid is walked one row at a time, with the order written out.
dim as int32 grid( 1 to 2, 1 to 3 ) = { { 1, 2, 3 }, { 4, 5, 6 } }
dim as int32 total = 0
for r as int32 = lbound( grid, 1 ) to ubound( grid, 1 )
for c as int32 = lbound( grid, 2 ) to ubound( grid, 2 )
total += grid( r, c )
next
next
print "grid total:"; total
Output
after writing to copies: 10 20 30 40
after for each byref: 11 22 33 44
nuts 4
bolts 5
washers 7
grid total: 21
for each p in priceshands you a copy of each element. Writingp = 0changes the copy, and the array is untouched.for each byref p in priceshands you the element itself, sop += p \ 10changes the array.
byref also avoids copying each element, which matters when the elements are
large, as records with text fields are. The stock loop sets a field of each
Item through the reference.
for each does not walk an array of more than one dimension:
'' for each refuses a grid: the order is not defined. Does not compile.
dim as int32 grid( 1 to 2, 1 to 3 ) = { { 1, 2, 3 }, { 4, 5, 6 } }
for each v in grid
print v;
next
foreach2d.tiko(4,1): error TKO0608: 'for each' over a multi-dimensional array has no defined order
Rows first or columns first is a decision the program should state, so the compiler does not choose one. Write the two counting loops, as the last part of the first example does, in the order you want.
Activities
- Use
for each byrefto round every price up to the next multiple of 25. - Find the
Itemwith the largestcountusingfor eachand no index.