600 Looping Statements Looping Statements A looping statement repeats one or more commands for a fixed number of times or until a certain Boolean condition becomes True. To create a loop that repeats for a fixed number of times, use the FOR-NEXT loop, which looks like this: FOR variable = Start TO End Command NEXT If you wanted the FOR-NEXT loop to run five times, you’d set the Start value to 1 and the End value to 5, such as FOR variable = 1 TO 5 Command NEXT Normally the FOR-NEXT loop counts by one, but you can use the STEP keyword to make the FOR-NEXT loop count by any value, such as by three, as shown in this example: FOR variable = 1 TO 36 STEP 3 Command NEXT Rather than count up, the FOR-NEXT loop can also count down. In Visual Basic, you can count down by using a negative number after the STEP keywords, such as FOR variable = 100 TO 1 STEP -1 Command NEXT In REALbasic, you can count down by replacing the TO keyword with the DOWNTO keyword, such as FOR variable = 100 DOWNTO 1 Command NEXT If you don’t know how many times you need to repeat commands, use a DO loop. The two variations of a DO loop are DO-UNTIL and DO-WHILE (available only in Visual Basic).
Creating Subprograms and Functions 601 The DO-UNTIL loop repeats until a certain condition becomes True. The DO-WHILE loop repeats while a certain condition remains True. The two variations of the DO-UNTIL loop look like this: Book VI Chapter 5 DO UNTIL condition Command Loop In this version, the DO-UNTIL loop checks if a condition is True. If so, this loop never runs. If not, this loop runs at least once. The second variation of the DO-UNTIL loop looks like this: Visual Basic and REALbasic DO Command Loop UNTIL condition This loop runs at least once before checking a condition. If the condition is True, the loop stops. The DO-WHILE loops work nearly identically. If you want to make a loop that may run zero or more times, you’d use this DO- WHILE loop: DO WHILE condition Command Loop If you want a DO-WHILE loop that runs at least once, you’d use this variation: DO Command Loop WHILE condition Although REALbasic lacks the DO-WHILE loop, it does offer a WHILE-WEND loop, which looks like this: WHILE condition Command WEND Creating Subprograms and Functions You can create a subprogram (or a procedure) by using the SUB keyword as follows: SUB Name (Parameter list) Command END SUB