This time we're still on loops in Pascal. After the FOR loop, we'll now try the WHILE DO loop.
What a WHILE DO Loop Is
A WHILE DO loop is a Pascal loop that uses a condition in the form of a boolean expression as the marker for repeating. The loop does not stop as long as its condition still has the value true.
If the FOR loop is like taking medicine exactly 3 times a day, the WHILE DO loop is more like stirring bread dough.
When you stir bread dough, you can't really work with a fixed number, like:
Stir the dough 50 times
Who wants to stir dough while counting, hehe... instead you usually run into an instruction like this:
Stir the dough until it rises
Instead of a number like 50, that instruction uses a condition, namely "until the bread rises".
It means that as long as the dough has not risen, the stirring keeps going. Once the dough has risen, the stirring is done.
Translated into Pascal, it would look something like this.
// in Pascal
while (adonan_belum_mengembang) do
aduk_adonan;
// or in Indonesian
selama (adonan_belum_mengembang) lakukan
aduk_adonan;
That's roughly how you use while in Pascal. Reading it in plain words does make it easier to follow, hehe....
Writing a WHILE DO Loop in Pascal
In a WHILE DO loop, the most important component is a condition in the form of a boolean expression. Next comes the statement we want to run. Here is the format for writing a WHILE DO loop.
while ({condition}) do
begin
{command to be executed}
end;
Okay, to make it clearer, let's write a simple program with the WHILE DO loop.
A WHILE DO Loop Example in Pascal
This time we'll print the numbers between 1 and 100 with a WHILE DO loop. Try typing in the code below.
program WhileDoLoop;
uses crt;
var
i: integer;
begin
clrscr;
i := 1;
while (i <= 100) do // as long as i is less than or equal to 100
begin
writeln(i); // output the value of variable i
i := i + 1; // add 1 to the value of i
end;
readln;
end.
If you run it, the output will be the numbers from 1 to 100. Roughly like this.
1
2
.
.
99
100
We get that output because the WHILE DO loop uses the condition i <= 100. Inside the loop we run writeln, and the last step adds 1 to the value of i (i := i + 1).
Adding to the value of variable i matters a lot. Without it the WHILE DO loop runs forever, and the only output you get is the number 1 over and over. You get the same result when you fill the while condition with the value true.
while (true) do
....
That code runs forever :D, or what we usually call infinite looping.
Infinite looping is very useful in game programming, because a game holds plenty of complex work that has to keep running
As usual, for an experiment you can swap the variable and play with the condition. Go wild... have fun, hehe..
Wrapping Up
That's enough for this tutorial, hope it helps :D next time we're still on looping, so don't get bored, hehe... We'll cover the repeat until loop in Pascal.