NAME

for...next - for statement

SYNOPSIS

for Var = NumExpr1 to NumExpr2 [step NumExpr3]



(loop statements)



next [Var [, Var]...]

DESCRIPTION

The for...next statement is used to perform looping based on a counter variable, Var.  Upon encountering the for...next statement, the numeric expressions NumExpr3, NumExpr2, and NumExpr1 are evaluated (in that order) and become the step, limiting, and initial values, respectively, for the for...next statement; if NumExpr3 is omitted, its value is assumed to be 1.  Then, Var is initialized to the initial value.  The value of Var is compared to the limiting value.  If this comparison indicates that Var has moved beyond the limiting value (greater than the limiting value if the step value is positive, or less than the limiting value if the step value is negative), looping stops and control passes to the statement in the program which follows the for...next statement.  Otherwise, if Var has not moved beyond the limiting value, the loop statements are executed, the step value is added to Var, the comparison occurs again, and the entire process repeats.  Note that it is possible that the loop statements are never executed if the first comparison indicates that Var is beyond the limiting value. 

There is no limit on the depth of nesting of for...next statements. 

If Var is omitted from the next statement, it is assumed to be the counter variable for the most recent for statement. 

EXAMPLE

This example sorts the elements of the string array a$ into lexicographic order based on the ASCII representation.  The array a$ was defined with j elements. 
	undone = 1
	while undone
		undone = 0
		for i = 1 to j - 1
			if a$(i) > a$(i + 1) then_
				swap a$(i), a$(i + 1) : undone = 1
		next i
	wend
In the next example, the loop executes six times.  The final value for the loop variable is set before the initial value is set.  The program
	j = 3
	for j = 1 to j + 3
		print j;
	next
produces
	 1  2  3  4  5  6
For...next loops may be nested, with one or more loops inside another loop.  Each loop must have a unique variable as its counter.  Each next statement must correspond with the most recently occurring for statement.  If several nested loops share the same end point, one next statement may be used for all of them.  The final example illustrates this.  The program
	dim a(6, 6)
	for j = 1 to 5
		for k = 1 to 5
			a(j, k) = j + k
	next k, j
is equivalent to
	dim a(6, 6)
	for j = 1 to 5
		for k = 1 to 5
			a(j, k) = j + k
		next k
	next j
A next statement of the form
	next Var1, Var2, ..., VarN
is equivalent to the sequence of statements
	next Var1
	next Var2
	    .
	    .
	    .
	next VarN

SEE ALSO

while...wend

from The Basmark QuickBASIC Programmer’s Manual by Lawrence Leinweber