A “for” loop repeats its body a certain number of times. Each time the loop body is executed an index variable is updated to reflect the execution count. The “for” loop takes the form:
For variable = minimum to maximum [step amount] v2.1
code to repeat (aka: the loop's body)
End
Here is a simple example that simply counts the numbers from 1 to 5 (inclusive):
For $number = 1 to 5
# this code is repeated 5 times, with the numbers 1,2,3,4,5
End
The minimum, maximum, and step need not be literal values, but can be any kind of expression, eg:
$count = 5
For $number = 1 to $count
# this code is repeated 5 times, with the numbers 1,2,3,4,5
End
The minimum, maximum, and step values are evaluated just once before the loop executes.
A step can be specified to increment the index variable by more than one each time through the loop:
For $number = 2 to 6 step 2
# this code is repeated 3 times, with the numbers 2,4,6
End
Negative steps allow the index to go from high to low:
For $number = 5 to 1 step -1
# this code is repeated 5 times, with the numbers 5,4,3,2,1
End
If a negative step is not specified, and the starting index is higher than the maximum, then the body is not executed at all:
For $number = 4 to 1
# this code is never executed
End
A more realistic example would be iterating over an array that just happens to be empty:
$array = Array.new
For $index = 0 to $array.count - 1
$value = $array[$index] # never executed
End
Previous Chapter While Loop |
<< index >> |
Next Chapter For Each Loop |