Tutorial - Numeric 'For' Statement

Structure of the Numeric For Statement

The overall form of a For statement :-

For local_variable From expression To expression [ Step expression ] Do
  statement_list
EndFor ;

The variable must be a local variable ( ideally set as Const ). If no step is indicated then a step of 1 is used. If a positive step is used then the To value must be higher than the From values. If the Step is negative the To must be lower. The value of the control variable may be changed with the loop if it was not set as Const. A new values is always calculated at the start of the loop, based on the original loop specification ( i.e. it ignores any code-generated changes made within the loop ).

Here is an example :-

	For i From 0 To 10  Do
		x := 100 + i * 10;
		height := 100 * 0.9 ^ i;
		Line( {x, 180}, {x, 180 - height} );
	EndFor;
stmt_for_1.grs Output of stmt_for_1.grs stmt_for_1.png

The Step Element

The For loop has an optional Step element. When this is specified the loop variable changes the loop by the specified amount each time around. The last value may not actually match the To value. e.g. "For i From 0 To 10 Step 3" will do 0, 3, 6 and 9.

	For i From 0 To 10 Step 2 Do
		x := 100 + i * 10;
		height := 100 * 0.9 ^ i;
		Line( {x, 180}, {x, 180 - height} );
	EndFor;
stmt_for_2.grs Output of stmt_for_2.grs stmt_for_2.png

It is possible to add a check within the loop to break out in certain circumstances. This is accomplished with the FBreak statement. The format of the FBreak statement is simple the keyword :-

FBreak;

	For i From 0 To 10 Do
		x := 100 + i * 10;
		height := 100 * 1.1 ^ i;
		If height > 180 Then
			Output "Bar too high";
			FBreak;
		EndIf;
		Line( {x, 180}, {x, 180 - height} );
	EndFor;
stmt_for_3.grs Output of stmt_for_3.grs stmt_for_3.png