Loops
Okay, this lesson you are going to learn about loops. There are two main types of loop in Turbo Pascal. While loops and For loops.


Loops! Get it?

While


While loops take the form : These are useful for things like waiting until the user presses a key or waiting until a number entered by the user is valid.

For instance you might say :
var
   valueIn : String; {This will be the value the user enters}
   I, code : Integer;
begin
   valueIn := 'abc'; {Fill it with a non integer value}
   code := 1;
   while code <> 0 do {While code is zero do the following}
   begin     writeln('Enter a number:');
    readln(valueIn);
    val(valueIn, I, code);
    {Move the integer value of valueIn to I or if it isn't an}
    {integer then code will be something other than 0. NB: code is}
    {the error code. I can only hold integers so there is an error}
    {raised when the string can't be converted to an integer}
   end;
end.

In this loop as long as condition is true (in this case code <> 0) it will execute the code between the begin and the corresponding end. You can miss out the begin and end but then you will only be able to have one line of code, or even no lines of code at all if you want.

eg:  while not keypressed do;

In the above example as long as there is not a key pressed the instructions in the loop are executed. Since there are no instructions in the loop this stops the program until the user presses a key.



The 'For' Loop


This loop takes the form:

For loops are more useful for iterating through an array. For instance you might want to add 1 to each integer in an array...

This does goes through each item in the array 'MyArray' and adds one to the current value in it.

Repeat


The repeat loop is very similar to the while loop except the condition is at the end, and if you want to execute multiple lines, then you don't need to put begin .. end keywords around the multiple lines. For instance, this loop using while...
Would be like this with a repeat loop...
Notice how the condition has changed slightly. For the while loop, it would do the loop while the condition is true, whereas the repeat loop does it until the condition is true. (Or while the condition is false).

Previous Lesson(Procedures/Functions)     Main Menu     Next Lesson(Flow Control)