NAME - for statement


for Var = NumExpr1 to NumExpr2 [step NumExpr3]

(loop statements)

next [Var [, Var]...]


The statement is used to perform looping based on a counter variable, Var.  Upon encountering the statement, the numeric expressions NumExpr3, NumExpr2, and NumExpr1 are evaluated (in that order) and become the step, limiting, and initial values, respectively, for the 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 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 statements. 

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


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
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;
	 1  2  3  4  5  6 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



from The Basmark QuickBASIC Programmerís Manual by Lawrence Leinweber