Loops
Description:
A loop allows us to repeat a set of instructions in our code multiple times depending on the value of a condition.
All loops need a counter to keep track of how many times the loop body has been run. Loop counters must be initialized to a starting value and are incremented on each pass of the loop based on the loop type.
There are 3 types of loops we can work with.
For... Next Loops
We use a for loop when we know how many times we want to the loop to repeat.
Basic Structure
For variable-name = start-value To end-value
// loop body - these statements are repeated on each pass through the loop
Next
Example
'Output the numbers 1-5 to a listbox using a For...Loop
'Declare counter variable
Var i as Integer
For i = 1 to 5
lstBox.AddRow(str(i))
Next
Stepping:
With For loops the counter variable is automatically incremented for us once we declare the loop variable. If we want to modify the increment of a for loop, we can use the "Step" command in Xojo. Positive step values increase the counter, while negative step values decrease the counter.
Example
'output the odd numbers from 1-7
'Declare counter variable
Var i as Integer
For i = 1 to 7 step 2
lstBox.AddRow(str(i))
Next