Tutorial - 'While' Statement

There will be a lot of cases where you will want to keep repeating a block of code while some condition remains true.

Structure of the While Statement

The overall form of a While statement is :-

While logical_expression Do
  statement_list
EndWhile ;

Here is an example :-

	While height > 10 Do
		Line({x, 180}, {x, 180 - height});
		height := height * 0.9;
		x := x + 10;
	EndWhile;
stmt_while_1.grs Output of stmt_while_1.grs stmt_while_1.png

You need to be careful that you do not create a loop that keeps going forever. If the scale factor had been 1.1 instead of 0.9 then loop would never end.

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

WBreak;

In the next example we have made the scaling factor 0.99, which means that the line will not reduce to the limit before reaching the edge of the page ( in this case there will be no real problem, but there are cases where it would generate an overflow condition ).

	While height > 10 Do
		Line({x, 180}, {x, 180 - height});
		height := height * 0.99; [= new value =]
		x := x + 10;
		[= check that we have not gone off the page =]
		If x >= 320 Then
			Output "Fell off edge of page";
			WBreak;
		EndIf;
	EndWhile;
stmt_while_2.grs Output of stmt_while_2.grs stmt_while_2.png