JBasic Guide

Page 54

JBasic Userʼs Guide

FOR The FOR statement creates a loop with an index variable that changes value by an incremental value each iteration of the loop. The loop executes as many times as it takes to increment the index variable past a limit.

FOR index = start TO end [ BY increment ] ... statements ... NEXT index

The index is a variable that is initially assigned the start value. The statements are executed, and when the NEXT statement is executed, the index variable has the increment value added to it. If the increment was not specified, then 1.0 is assumed. The index is then compared to the end value, and if the end value has been exceeded (greater than it if the increment is positive; less than it if the increment is negative) then the program continues executing with the next statement after the NEXT. Otherwise, the statement body is executed again. If the index value is already past the limit, the loop does not run at all, but execution continues following the NEXT statement. An increment with a value of zero signals an error. Loop statements such as FOR...NEXT cannot be executed directly from the command line, but are only valid in running programs. An alternate version of the FOR statement allows you to specify a list of values to be assigned to the index variable rather than an incremented value:

NAMES = [“TOM”, “MARY”, “SUE”, “BOB”] FOR NAME = NAMES, “DAVE” PRINT “NAME = “; NAME NEXT NAME

In this example, the index variable NAME will be set to the value of each item in the list that follows the “=” character. There is no TO or BY value. When one of the items in the list is an array, the index variable is set to each value of the array in turn. So in the above case, the index variable will be set to “TOM”, “MARY”, “SUE”, “BOB”, and “DAVE” in turn as the loop body executes. The values list can be a list of one or more expressions, which must be separated by commas. Finally, you can use either form of the FOR statement to execute a single statement as the loop body with an implied NEXT. This is done by using the DO clause on the FOR statement:

FOR N = SYS$PROGRAMS DO PRINT “PROGRAM = “; N

This executes the PRINT statement for each value of N in the SYS$PROGRAMS array. 52


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.