Loops are useful for having the computer repeat commands over and over. There are three types of loops for Free Pascal. The loops include the While Loop, Repeat Until, and the For Loop. There must be a condition met to end the loop. If the condition is not met the computer will go into a infinite loop. Sometimes the infinite loop will lock the computer or cause the user to have to force quite the program. This tutorial will show each loop by calculating a little math problem, with the output printed on the screen.
While Loop Example Program:
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
x:integer;
begin
x := 1; {starts x equal to 1}
while x <= 10 do
begin
writeln(x, ' * 2 = ' , x * 2);
x := x + 1;
end; {ends while loop}
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
Repeat Until Loop Example Program:
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
x:integer;
begin
x := 1; {starts x equal to 1}
repeat
writeln(x, ' * 2 = ' , x * 2);
x := x + 1;
until x > 10; {ends repeat loop}
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
For Loop Program Example:
program Project1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes
{ you can add units after this };
var
x:integer;
begin
for x := 1 to 10 do {to go backwards: for x:= 10 downto 1 do }
begin
writeln(x, ' * 2 = ' , x * 2);
end; {ends for loop}
writeln;
writeln;
writeln('Press <Enter> To Quit');
readln();
end.
Video: Free Pascal Tutorial 6 - Loops - Lazarus (6:04)