Download objects

Transcript
84 - 03: Language Statements
note
You will have noticed that in both the while and repeat conditions I have enclosed the “subconditions” in parentheses. It is necessary in this case, as the compiler will execute or before performing the comparisons (as I covered in the section about operators of Chapter 2).
If the initial value of I or J is greater than 100, the while loop is completely skipped,
while statements inside the repeat loop are executed once anyway.
The other key difference between these two loops is that the repeat-until loop has
a reversed condition. This loop is executed as long as the condition is not met.
When the condition is met, the loop terminates. This is the opposite of a while-do
loop, which is executed while the condition is true. For this reason I had to reverse
the condition in the code above to obtain a similar effect.
note
The “reverse condition” is formally known as the “De Morgan's” laws (described, for example, on
Wikipedia at http://en.wikipedia.org/wiki/De_Morgan%27s_laws).
Examples of Loops
To explore some more details of loops, let's look at a small practical example. The
LoopsTest program highlights the difference between a loop with a fixed counter
and a loop with an open counter. The first fixed counter loop, a for loop, displays
numbers in sequence:
var
I: Integer;
begin
for I := 1 to 20 do
Show ( 'Number ' + IntToStr (I));
end;
The same could have been obtained also with a while loop, with an internal increment of one (notice you increment the value after using the current one). With a
while loop, however, you are free to set a custom increment, for example by 2:
var
I: Integer;
begin
I := 1;
while I <= 20 do
begin
Show ( 'Number ' + IntToStr (I));
Inc (I, 2)
end;
end;
Marco Cantù, Object Pascal Handbook