We've been through the FOR loop and the WHILE DO loop in Pascal. Now we'll look at the REPEAT UNTIL loop.
What a REPEAT UNTIL Loop Is
A REPEAT UNTIL loop looks a lot like a WHILE DO loop. Both of them use a boolean expression as their condition. The difference is where the condition sits, and when the loop stops.
In a REPEAT UNTIL loop, the condition is checked at the end of the statement, and the loop keeps running as long as the condition is still false. That is the reverse of WHILE DO, where the check sits at the start and the loop runs while the condition is true.
Let's look at a simple example, still with the bread dough, hehe...
// in Pascal
repeat
aduk_adonan;
until (roti_mengembang);
// or in Indonesian
ulangi
aduk_adonan;
sampai (roti_mengembang);
In that REPEAT UNTIL loop, the aduk_adonan statement keeps running as long as the bread has not risen. Once the bread has risen, the loop stops.
Writing a REPEAT UNTIL Loop in Pascal
As with the WHILE DO loop, the most important parts of a REPEAT UNTIL loop are the condition and the statement to run. The format looks like this.
repeat
{command to be executed}
until ({condition});
Okay, to make it clearer, let's write a simple program with the REPEAT UNTIL loop.
A REPEAT UNTIL Loop Example in Pascal
This time we'll write a program that prints multiples of 2 using a REPEAT UNTIL loop. Type in the code below.
program WhileDoLoop;
uses crt;
var
i: integer;
begin
clrscr;
i := 2;
writeln('Bilangan kelipatan 2');
repeat
write(i, ', ');
i := i+2; // add 2 to i
until(i > 100); // loop until i is greater than 100
readln;
end.
Run it, and the output will look roughly like this.
Bilangan kelipatan 2
2 4 6 8 ... 98 100
In that program the write(i, ' ') statement runs 50 times, because variable i goes up by 2 on every pass. Once variable i is greater than 100 the loop stops and the program ends.
Now try changing the condition a little, to the following.
....
until (i >= 100);
....
Once you've changed it, run it. If you look closely, the output never reaches 100, it only goes up to 98. Why is that?
Because once the value of variable i reaches 100, the loop has already stopped, since 100 >= 100 gives the value true. You have to watch this when you write conditions, because one mistake there throws the program logic off too.
Oh, right: a REPEAT UNTIL loop can also produce an infinite loop, if its logic is always false. For example.
....
until (false); // this produces an infinite loop
....
So always remember to give it logic that can end, so you don't end up with an infinite loop, hehe... :D
As usual, experiment with changing the variable and the loop condition. Have fun...
Wrapping Up
That's enough for this tutorial, hope it helps :D next time we'll come back to branching, like the IF ELSE we covered before. This time it will use a different method, namely branching with the CASE OF condition.