Upload
sebastian-martinez
View
226
Download
0
Embed Size (px)
Citation preview
8/13/2019 Start Prog Using Pascal
1/152
Start programming
using
Object Pascal
Written by: Motaz Abdel AzeemEdited by: Pat Anderson, Jason Hackney
code.sd
18.June.211
http://code.sd/http://code.sd/8/13/2019 Start Prog Using Pascal
2/152
!ntroduction
This book is written for programmers who want to learn the Object Pascal Language. It is also suitable
as a first programming book for new students and non-programmers. It illustrates programming
techniques in general in addition to the Object Pascal Language.
"#e $b%ect Pascal &an'ua'e
The first appearance of the Pascal Language supporting Object Oriented programming was in 1983 by
Apple computer company. After that Borland supported Object Oriented programming for their famous
Turbo Pascal line.
Object Pascal is a general purpose hybrid (structured and object oriented programming) language. It
can be used for a vast range of applications, like learning, game development, business applications,Internet applications, communication applications, tools development, and OS kernels.
(el)#i
After the success of Turbo Pascal, Borland decided to port it to Windows and introduced component
driven technology to it. Soon Delphi became the best RAD (Rapid Application Development) tool at
that time.
The first version of Delphi was released in 1995 with a rich set of components and packages thatsupported Windows and Database applications development.
*ree Pascal
After Borland dropped support for the Turbo Pascal line, the Free Pascal team started an open source
project to write a compatible compiler for Turbo Pascal from scratch, and then make it compatible with
Delphi. This time the Free Pascal compiler was targeting additional platforms and operating systems
like Windows, Linux, Mac, ARM, and WinCE.
Version 1.0 of the Free Pascal compiler was released in July 2000.
&azarus
Free Pascal is a compiler, and it lacks an Integrated Development Environment (IDE) similar to the
8/13/2019 Start Prog Using Pascal
3/152
Delphi IDE for Windows. The Lazarus project was started to provide an IDE for Free Pascal. It
provides a source code editor, debugger, and contains a lot of frameworks, packages, and component
libraries similar to the Delphi IDE.
Version 1.0 of Lazarus has not been released yet, but there are a lot of applications developed with beta
versions of Lazarus. A lot of volunteers write packages and components for Lazarus, and the
community is growing.
$b%ect Pascal +eatures
Object Pascal is a very easy and readable language for beginners, its compilers are very fast, and the
applications it produces are reliable, fast and can be compared with C, and C++. You can write robust
and large applications with its IDEs (Lazarus and Delphi) without complexity.
Aut#or: Motaz Abdel Azeem
I am graduated from Sudan University of Science and Technology in 1999. and I started learning
Pascal as a second language after BASIC. Since then, I've been using it continuously, and I found it a
very easy and powerful tool, specially after I studied C, and C++. Then I moved to Delphi. Since then I
have been using Delphi and Lazarus for all my applications.
I live in Khartoum. My current job is Software Developer.
*irst EditorPat Anderson graduated from Western Washington State College in 1968 and Rutgers Law School in
1975. He works as the City Attorney of Snoqualmie, Washington. Pat began programming on a Radio
Shack TRS-80 Model III in 1982 with the built-in BASIC interpreter, but soon discovered Turbo Pascal.
He has owned all versions of Turbo Pascal from 4.0 to 7.0, and every version of Delphi from 1.0 to 4.0.
Pat took a hiatus from programming from 1998 until 2009, when he came upon Free Pascal / Lazarus,
which reignited his passion for programming.
econd Editor
Jason Hackney is a graduate of Western Michigan University's
College of Aviation. He works full-time as a professional pilot for a
power company based in southeast Michigan. Jason has been a casual
programmer since his first exposure to the Commodore 64 around 1984.
Briefly introduced to Turbo Pascal in 1990, he recently rekindled
latent programming interest after discovering Linux, Lazarus, and Free
Pascal.
8/13/2019 Start Prog Using Pascal
4/152
&icense:
The License for this book is Creative Commons.
En-ironment +or book eam)les
We will use Lazarus and Free Pascal for all the examples in this book. You can get the Lazarus IDE,
including the Free Pascal compiler, from this site: http://lazarus.freepascal.org .
If you are using Linux, then you can get Lazarus from the software repository. In Ubuntu you can use
the command:
sudo apt-get install lazarus
In Fedora you can use the command:
yum install lazarus
Lazarus is a free and open source application. And it is available on many platforms. Applications
written in Lazarus can be re-compiled on another platform to produce executables for that platform. For
example if you write an application using Lazarus in Windows, and you want to produce a Linux
executable for that application, you only need to copy your source code to Lazarus under Linux, then
compile it.
Lazarus produces applications that are native to each operating system, and it does not require anyadditional libraries or virtual machines. For that reason, it is easy to deploy and fast in execution.
/sin' "et mode
All examples in the first chapters of this book will be console applications (text mode applications/
command line applications), because they are easy to understand and standard. Graphical user interface
applications will be introduced in later chapters.
http://lazarus.freepascal.org/http://lazarus.freepascal.org/8/13/2019 Start Prog Using Pascal
5/152
8/13/2019 Start Prog Using Pascal
6/152
Multiplication Table using for loop.........................................................................................................30
Factorial program....................................................................................................................................31
Repeat Until loop.....................................................................................................................................32
Restaurant program using Repeat loop...................................................................................................32
While loop................................................................................................................................................34
Factorial program using while loop........................................................................................................34
Strings......................................................................................................................................................36
Copy function...........................................................................................................................................39
Insert procedure.......................................................................................................................................40
Delete procedure......................................................................................................................................41
Trim function............................................................................................................................................41
StringReplace function.............................................................................................................................42
Arrays.......................................................................................................................................................44
Records....................................................................................................................................................47
Files.........................................................................................................................................................49
Text files...................................................................................................................................................50
Reading text file program........................................................................................................................50
Creating and writing into text file............................................................................................................52
Appending to a text file............................................................................................................................55
Add to text file program...........................................................................................................................55
Random access files.................................................................................................................................56
Typed files................................................................................................................................................56
Marks program........................................................................................................................................56
Reading student marks.............................................................................................................................57
Appending student marks program..........................................................................................................58
Create and append student marks program.............................................................................................59
Cars database program...........................................................................................................................60
File copying.............................................................................................................................................62
Copy files using file of byte......................................................................................................................62
Untyped files............................................................................................................................................64
Copy files using untyped files program...................................................................................................64
Display file contents program..................................................................................................................66
Date and Time..........................................................................................................................................68
8/13/2019 Start Prog Using Pascal
7/152
Date/time comparison..............................................................................................................................70
News recorder program............................................................................................................................71
Constants..................................................................................................................................................73
Fuel Consumption program.....................................................................................................................73
Ordinal types............................................................................................................................................75
Sets...........................................................................................................................................................77
Exception handling..................................................................................................................................79
Try except statement.................................................................................................................................79
Try finally.................................................................................................................................................80
Raise an exception..................................................................................................................................81
Chapter TwoChapter Two
Structured ProgrammingStructured ProgrammingIntroduction.............................................................................................................................................84
Procedures...............................................................................................................................................84
Parameters...............................................................................................................................................85
Restaurant program using procedures.....................................................................................................86
Functions..................................................................................................................................................87
Restaurant program using functions........................................................................................................88
Local Variables........................................................................................................................................89
News database application......................................................................................................................90
Functions as input parameters.................................................................................................................93
Procedure and function output parameters.............................................................................................94
Calling by reference.................................................................................................................................95
Units.........................................................................................................................................................97
Units in Lazarus and Free Pascal............................................................................................................99
Units written by the programmer.............................................................................................................99Hejri Calendar.......................................................................................................................................100
Procedure and function Overloading.....................................................................................................103
Default value parameters.......................................................................................................................104
Sorting....................................................................................................................................................105
Bubble sort algorithm............................................................................................................................105
8/13/2019 Start Prog Using Pascal
8/152
8/13/2019 Start Prog Using Pascal
9/152
Chapter OneChapter One
Language BasicsLanguage Basics
8/13/2019 Start Prog Using Pascal
10/152
Our First ApplicationOur First Application
After installing and running Lazarus, we can start a new program from the main menu:
Project/New Project/Program
We will get this code in the Source Editor window:
programProject1;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads)
{$"!I}{$"!I} &lasses { you can add units after this };
{$I!" *I!*,}{$ project1.rc}{$"!I}
beginend.
We can save this program by clicking File/Savefrom the main menu, and then we can name it, for
example, first.lpi
Then we can write these lines between the beginandendstatements:
*riteln/0'(is is ree Pascal and azarus02; *riteln/0Press enter 3ey to close02; eadln;
The complete source code will be:
programfirst;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses { you can add units after this };
8/13/2019 Start Prog Using Pascal
11/152
{$I!" *I!*,}{$ first.rc}{$"!I}
begin *riteln/0'(is is ree Pascal and azarus02; *riteln/0Press enter 3ey to close02;
eadln;end.
The Writelnstatement displays the text on the screen (Console window).Readlnhalts execution to let
the user read the displayed text until he/she presses enter to close the application and return to the
Lazarus IDE.
Then press F9to run the application or click the button:
After running the first program, we will get this output text:
'(is is ree Pascal and azarusPress enter 3ey to close
If we are using Linux, we will find a new file in a program directory called (first), and in Windows we
will get a file named first.exe. Both files can be executed directly by double clicking with the mouse.
The executable file can be copied to other computers to run without the need of the Lazarus IDE.
NotesIf the console application window does not appear, we can disable the debugger from the Lazarus
menu:
Environment/Options/Debugger
In Debugger typeand pathselect (None)
8/13/2019 Start Prog Using Pascal
12/152
$t#er eam)les
In the previous program change this line:
*riteln/0'(is is ree Pascal and azarus02;
to this one:
*riteln/0'(is is a number4 0) 152;
Then press F9to run the application.
You will get this result:
'(is is a number4 15
Change the previous line as shown below, and run the application each time:
Code:
*riteln/0'(is is a number4 0) 6+ 72;
Output:
'(is is a number4 5
Code:
*riteln/05 8 7 9 0) 58 72;
Output:
5 8 7 9 1:
Code:
*riteln/0'(is is real number4 0) .72;
8/13/2019 Start Prog Using Pascal
13/152
Output:
'(is is real number4 .7::::::::::::"+::::
Code:
*riteln/0ne) '
8/13/2019 Start Prog Using Pascal
14/152
0ariables
Variables are data containers. For example, when we say that X = 5, that means Xis a variable, and it
contains the value 5.
Object Pascal is a strongly typed language, which means we should declare a variable's type before
putting values into it. If we declare X as an integer, that means we should put only integer numbers into
X during its life time in the application.
Examples of declaring and using variables:
programirst=ar;
{$mode objfpc}{$H+}
uses
{$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses { you can add units after this };
var x4 Integer;begin x49 5; *riteln/x8 72;
*riteln/0Press enter 3ey to close02; eadln;end.
We will get 10 in the application's output.
Note that we used the reserved word Var, which means the following lines will be variable declarations:
>4 Integer;
This means two things:1. The variable's name is X; and
2. the type of this variable is Integer, which can hold only integer numbers without a fraction. It
could also hold negative values as well as positive values.
And the statement:
>49 5;
8/13/2019 Start Prog Using Pascal
15/152
means put the value 5in the variable X.
In the next example we have added the variable Y:
var >) y4 Integer;begin >49 5; y49 1:; *riteln/> 8 y2; *riteln/0Press enter 3ey to close02; eadln;end.
The output of the previous application is:
5:Press enter 3ey to close
50 is the result of the formula (x * y).
In the next example we introduce a new data type calledcharacter:
var c4 &(ar;begin c49 0?0; *riteln/0?y first letter is4 0) c2; *riteln/0Press enter 3ey to close02; eadln;end.
This type can hold only one letter, or a number as an alphanumeric character, not as value.
In the next example we introduce the realnumber type, which can have a fractional part:
var >4 ,ingle;begin >49 1.@; *riteln/0?y &ar engine capacity is 0) >) 0 liters02; *riteln/0Press enter 3ey to close02;
8/13/2019 Start Prog Using Pascal
16/152
eadln;end.
To write more interactive and flexible applications, we need to accept input from the user. For example,
we could ask the user to enter a number, and then get this number from the user input using the Readln
statement / procedure:
var >4 Integer;begin Write/0Please input any number402; Readln/x2; *riteln/0Aou (aBe entered4 0) >2; *riteln/0Press enter 3ey to close02; eadln;end.
In this example, assigning a value toXis done through the keyboard instead of assigning it a constantvalue in the application.
In the example below we show a multiplication table for a number entered by the user:
program?ult'able;
{$mode objfpc}{$H+}
uses
{$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses { you can add units after this };
var >4 Integer;begin Write/0Please input any number402; eadln/>2; *riteln/>) 0 8 1 9 0) > 8 12; *riteln/>) 0 8 7 9 0) > 8 72; *riteln/>) 0 8 6 9 0) > 8 62; *riteln/>) 0 8 C 9 0) > 8 C2; *riteln/>) 0 8 5 9 0) > 8 52; *riteln/>) 0 8 D 9 0) > 8 D2; *riteln/>) 0 8 9 0) > 8 2; *riteln/>) 0 8 @ 9 0) > 8 @2;
8/13/2019 Start Prog Using Pascal
17/152
*riteln/>) 0 8 E 9 0) > 8 E2; *riteln/>) 0 8 1: 9 0) > 8 1:2; *riteln/>) 0 8 11 9 0) > 8 112; *riteln/>) 0 8 17 9 0) > 8 172; *riteln/0Press enter 3ey to close02; eadln;
end.Note that in the previous example all the text between single quotation marks (') is displayed in the
console window as is, for example:
0 8 1 9 0
Variables and expressions that are written without single quotation marks are evaluated and written as
values.
See the difference between the two statements below:
*riteln/05 8 602; *riteln/58 62;
The result of first statement is:
5 8 6
Result of the second statement is evaluated then displayed:
15
In the next example, we will do mathematical operations on two numbers (x, y), and we will put the
result in a third variable (Res):
var >) y4 Integer; Res4 ,ingle;begin Write/0Input a number4 02; eadln/>2;
Write/0Input anot(er number4 02; eadln/y2; Res49 > F y; *riteln/>) 0 F 0) y) 0 9 0) Res2; *riteln/0Press enter 3ey to close02; eadln;end.
Since the operation is division, it might result in a number with a fraction, so for that reason we have
8/13/2019 Start Prog Using Pascal
18/152
declared the Result variable (Res) as a real number (Single). Singlemeans a real number with single
precision floating point.
8/13/2019 Start Prog Using Pascal
19/152
ub ty)es
There are many sub types for variables, for example, Integer number subtypes differ in the range and
the number of required bytes to store values in memory.
The table below contains integer types, value ranges, and required bytes in memory:
Size in BytesMax ValueMin valueType
12550Byte
1127-128ShortInt
232767-32768SmallInt
2655350Word
42147483647-2147483648Integer
42147483647-2147483648LongInt
442949672950Cardinal
89223372036854775807-9223372036854780000Int64
We can get the minimum and maximum values and bytes sizes for each type by using the Low, High,
and SizeOffunctions respectively, as in the example below:
program'ypes;
{$mode objfpc}{$H+}uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses;
begin *riteln/0Gyte4 ,ize 9 0) ,izef/Gyte2) 0) ?inimum Balue 9 0) oimum Balue 9 0)
Hig(/Gyte22; *riteln/0Integer4 ,ize 9 0) ,izef/Integer2)
0) ?inimum Balue 9 0) oimum Balue 9 0) Hig(/Integer22;Write/0Press enter 3ey to close02;
eadln;end.
8/13/2019 Start Prog Using Pascal
20/152
onditional ranc#in'
One of the most important features of intelligent devices (like computers, programmable devices) is
that they can take actions in different conditions. This can be done by using conditional branching. For
example, some cars lock the door when the speed reaches or exceeds 40 K/h. The condition in this case
will be:
If speed is >= 40and doors are unlocked, then lock door.
Cars, washing machines, and many other gadgets contains programmable circuits like micro controllers,
or small processors like ARM. Such circuits can be programmed using assembly, C, or Free Pascal
according to their architecture.
"#e !+ condition
The If condition statement in the Pascal language is very easy and clear. In the example below, we want
to decide whether to turn on the air-conditioner or turn it off, according to the entered room
temperature:
Air-Conditioner program:Air-Conditioner program:
var 'emp4 ,ingle;begin Write/0Please enter 'emperature of t(is room 402; eadln/'emp2; if'emp 77then *riteln/0Please turn on air-condition02 else *riteln/0Please turn off air-condition02;Write/0Press enter 3ey to close02;
eadln;end.
We have introduced the if then elsestatement, and in this example: if the temperature is greater than 22,
then display the first sentence::
Please turn on air-conditioner
else, if the condition is not met (less than or equal to 22) , then display this line:
8/13/2019 Start Prog Using Pascal
21/152
Please turn off air-conditioner
We can write multiple conditions like:
var 'emp4 ,ingle;begin Write/0Please enter 'emperature of t(is room 402; eadln/'emp2; if'emp 77then *riteln/0Please turn on air-conditioner02 else if'emp 1@then *riteln/0Please turn off air-conditioner02 else
*riteln/0!o not(ing02;You can test the above example with different temperature values to see the results.
We can make conditions more complex to be more useful:
var 'emp4 ,ingle; J&Isn4 Gyte;
begin Write/0Please enter 'emperature of t(is room 4 02; eadln/'emp2; Write/0Is air conditioner onK if it is /n2
8/13/2019 Start Prog Using Pascal
22/152
Write/0Press enter 3ey to close02;
eadln;end.
In the above example, we have used the new keyword (and) which means if the first condition returns
True (ACIsOn = 1), and the second condition returns True (Temp > 22), then execute the Writelnstatement. If one condition or both of them return False, then it will go to the else part.
If the air-conditioner is connected to a computer via the serial port for example, then we can turn it
on/off from that application, using serial port procedures/components. In this case we need to add extra
parameters for the if condition, like for how long the air-conditioner was operating. If it exceeds the
allowable time (for example, 1 hour) then it should be turned off regardless of room temperature. Also
we can consider the rate of losing coolness, if it is very slow (at night), then we could turn if off for
longer time.
Weight programWeight program
In this example, we ask the user to enter his/her height in meters, and weight in Kilos. Then the
program will calculate the suitable weight for that person according to the entered data, and then it will
tell him/her the results:
program*eig(t;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var
Heig(t4 !ouble; *eig(t4 !ouble; Ideal*eig(t4 !ouble;begin Write/0*(at is your (eig(t in meters /e.g. 1.@ meter2 4 02; eadln/Heig(t2; Write/0*(at is your
8/13/2019 Start Prog Using Pascal
23/152
Ideal*eig(t49 /Heig(t - 12 8 1:: else Ideal*eig(t49 Heig(t 8 7:;
if/Heig(t :.C2 or/Heig(t 7.52 or/*eig(t 62 or/*eig(t 7::2 then
begin *riteln/0InBalid Balues02; *riteln/0Please enter proper Balues02; end else ifIdeal*eig(t 9 *eig(t then *riteln/0Aour
8/13/2019 Start Prog Using Pascal
24/152
/*eig(t 7::2 then begin *riteln/0InBalid Balues02; *riteln/0Please enter proper Balues02; end
4. We have used the procedure Format, which displays values in a specific format. In this case weneed to display only 2 digits after the decimal point. We need to add the SysUtilsunit to the
Usesclause in order to use this function.
*(at is your (eig(t in meters /e.g. 1.@ meter2 4 1.@*(at is your
8/13/2019 Start Prog Using Pascal
25/152
ase .. o+ statement
There is another method for conditional branching, which is the Case .. Of statement. It branches
execution according to the caseordinal value. The Restaurant program will illustrate the use of the
case ofstatement:
Restaurant programRestaurant program
var ?eal4 Gyte;begin
*riteln/0*elcome to Pascal estaurant. Please select your order02; *riteln/01 - &(ic3en /1:$202;
*riteln/07 - is( /$202; *riteln/06 - ?eat /@$202; *riteln/0C ,alad /7$202; *riteln/05 - range Quice /1$202; *riteln/0D - ?il3 /1$202; *riteln; Write/0Please enter your selection4 02; eadln/?eal2;
case?eal of 14 *riteln/0Aou (aBe ordered &(ic3en)0)
0 t(is
8/13/2019 Start Prog Using Pascal
26/152
Restaurant program usingRestaurant program usingIf conditionIf condition
var ?eal4 Gyte;begin
*riteln/0*elcome to Pascal restaurant) please select your meal02; *riteln/01 - &(ic3en /1:$202; *riteln/07 - is( /$202; *riteln/06 - ?eat /@$202; *riteln/0C - ,alad /7$202; *riteln/05 - range Quice /1$202; *riteln/0D - ?il3 /1$202; *riteln; Write/0Please enter your selection4 02; eadln/?eal2;
if?eal 9 1then *riteln/0Aou (aBe ordered &(ic3en) t(is
8/13/2019 Start Prog Using Pascal
27/152
Students' Grades programStudents' Grades program
var ?ar34 Integer;begin
Write/0Please enter student mar34 02; eadln/?ar32; *riteln;
case?ar3 of :.. 6E4 *riteln/0,tudent grade is4 02; C:.. CE4 *riteln/0,tudent grade is4 "02; 5:.. 5E4 *riteln/0,tudent grade is4 !02; D:.. DE4 *riteln/0,tudent grade is4 &02; :.. @C4 *riteln/0,tudent grade is4 G02; @5.. 1::4 *riteln/0,tudent grade is4 J02; else *riteln/0*rong mar302; end;
Write/0Press enter 3ey to close02; eadln;end.
In the previous sample we have used a range, like (0 .. 39), which means the condition will return True
if theMarkvalue exists in this range.
Note:The Case statement works only with ordinal types likeIntegers, char, but it doesn't work with other
types like strings, and realnumbers.
Keyboard programKeyboard program
In this example, we will get a character from keyboard and the application will tell us the row number
of the entered key on the keyboard:
var Oey4 &(ar;begin Write/0Please enter any "nglis( letter4 02; eadln/Oey2; *riteln;
8/13/2019 Start Prog Using Pascal
28/152
caseOey of 0R0) 00) 0c0) 0B0) 0b0) 0n0) 0m04 *riteln/0'(is is in t(e fourt( ro< in 3eyboard02; else *riteln/0#n3no0) 0c0) 0B0) 0b0) 0n0) 0m04
which means execute case branch statement if the Key was one of these values set:
z, x, c, v, b, nor m
We can also mix ranges with values set like this:
0a0 .. 0d0) 0>0) 0y0) 0z04
which means execute the statement if the value falls between aand d, or equal to x, yor z.
8/13/2019 Start Prog Using Pascal
29/152
&oo)s
Loops are used to execute certain parts of code (statements) for a specific number of times, or until a
condition is satisfied.
*or loo)
You can execute for statements for a specific number of cycles using a counter like this example:
var i4 Integer; &ount4 Integer;begin Write/0Ho< many timesK 02; eadln/&ount2; fori49 1to&ount do *riteln/0Hello t(ere02;
Write/0Press enter 3ey to close02; eadln;end.
We should use ordinal types likeInteger,Byte, and Charinfor loop variables. We call this variable a
loop variableor loop counter. The value of loop countercan be initialized with any number, and we
can also determine the last value of loop counter. For example, if we need to count from 5 to 10, then
we can do this:
fori:= 5to10do
We can display loop counterin every cycle of the loop, as in the modified example below:
var i4 Integer; &ount4 Integer;begin Write/0Ho< many timesK 02; eadln/&ount2; fori49 1to&ount do begin *riteln/0&ycle number4 0) i2; *riteln/0Hello t(ere02; end;
Write/0Press enter 3ey to close02; eadln;end.
Note that this time we need to repeat two statements, and for that reason we have used the begin . . end
keywords to make them one statement.
8/13/2019 Start Prog Using Pascal
30/152
Multi)lication "able usin' for loo)
The for loop version of the Multiplication Table program is easier and more concise:
program?ult'able*it(oroop;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses { you can add units after this };
var >) i4 Integer;begin Write/0Please input any number4 02;
eadln/>2; fori49 1to17do *riteln/>) 0 8 0) i) 0 9 0) > 8 i2;
*riteln/0Press enter 3ey to close02; eadln;end.
Instead of writing the Writelnstatement 12 times, we write it once inside a loop which is executed 12
times.
We can make the for loop statement iterate in a backward direction usingdowntokeyword instead oftokeyword using this syntax:
fori49 17 downto1 do
8/13/2019 Start Prog Using Pascal
31/152
Factorial programFactorial program
Factorial in mathematics is the multiplication of a number by each one of its predecessors down to the number 1.
For example, 3! = 3 * 2 * 1 = 6.
var
ac) um) i4 Integer;begin Write/0Please input any number4 02; eadln/um2; ac49 1; fori49 um downto1do ac49 ac 8 i; *riteln/0actorial of 0) um )0 is 0) ac2;
*riteln/0Press enter 3ey to close02; eadln;end.
8/13/2019 Start Prog Using Pascal
32/152
3e)eat /ntil loo)
Unlike thefor loop which repeats for a specific number of cycles, theRepeat loop has no counter. It
loops until a certain condition occurs (Returns True), then it will go to the next statement after the loop.
Example:
var um 4 Integer;begin repeat Write/0Please input a number4 02; eadln/um2; untilum 9 :; *riteln/0inis(ed) please press enter 3ey to close02; eadln;end.
In the previous example, the program enters the loop, then it asks the user to enter a number. If thenumber is less than or equal to zero, it will exit the loop. If the entered number is greater than zero, the
loop will continue.
Restaurant program using Repeat loopRestaurant program using Repeat loop
var ,election4 &(ar; Price4 Integer;
'otal4 Integer;begin 'otal49 :; repeat *riteln/0*elcome to Pascal estaurant. Please select your order02; *riteln/01 - &(ic3en /1: Sene(202; *riteln/07 - is( / Sene(202; *riteln/06 - ?eat /@ Sene(202; *riteln/0C ,alad /7 Sene(202; *riteln/05 - range Quice /1 Sene(202; *riteln/0D - ?il3 /1 Sene(202; *riteln/0% - not(ing02; *riteln;
Write/0Please enter your selection4 02; eadln/,election2;
case,election of 0104 begin *riteln/0Aou (aBe ordered &(ic3en) t(is
8/13/2019 Start Prog Using Pascal
33/152
end; 0604 begin *riteln/0Aou (aBe ordered meat) t(is
8/13/2019 Start Prog Using Pascal
34/152
W#ile loo)
The while loop is similar to the repeat loop, but it differs from it in these aspects:
1. In the while , the condition is checked first before entering the loop, but repeatenters the loop
first then it checks the condition. That means repeat always executes its statement(s) once at
least, but while loop could prevent entering the first cycle if the condition returns Falsefrom the
beginning.
2. while loop needs begin endif there are multiple statements that need to be executed in a loop,
but repeatdoes not need begin end, its block (repeated statements) starts from the repeat
keyword to the untilkeyword.
Example:
var um4 Integer;begin Write/0Input a number4 02; eadln/um2; whileum :do begin Write/0rom inside loop4 Input a number 4 02; eadln/um2; end; Write/0Press enter 3ey to close02; eadln;end.
Factorial program using while loopFactorial program using while loop
var ac) um) i4 Integer;begin Write/0Please input any number4 02; eadln/um2;
ac49 1; i49 um; whilei 1do begin ac49 ac 8 i; i49 i - 1; end; *riteln/0actorial of 0) um )0 is 0) ac2;
*riteln/0Press enter 3ey to close02; eadln;
8/13/2019 Start Prog Using Pascal
35/152
end.
The while loop has no loop counter, and for that reason we have used the variable ito work as a loop
counter. The loop counter value is initialized by the number for which we need to get its factorial, then
we decrease it manually in each cycle of the loop. When ireaches 1, the loop will break.
8/13/2019 Start Prog Using Pascal
36/152
trin's
The Stringtype is used to declare variables that can hold a chain of characters. It can be used to store
text, a name, or a combination of characters and digits like a car license plate number.
In this example we will see how we can use the stringvariable to accept a user name:
var ame4 string;begin Write/0Please enter your name 4 02; eadln/ame2; *riteln/0Hello 0) ame2;
*riteln/0Press enter 3ey to close02; eadln;
end.
In the next example, we will use strings to store information about a person:
var ame4 string; Jddress4 string; I!4 string; !G4 string;begin Write/0Please enter your name 4 02;
eadln/ame2; Write/0Please enter your address 4 02; eadln/Jddress2; Write/0Please enter your I! number 4 02; eadln/I!2; Write/0Please enter your date of birt( 4 02; eadln/!G2; *riteln; *riteln/0&ard402; *riteln/0------------------------------------------0 2; *riteln/0T ame 4 0) ame2; *riteln/0T Jddress 4 0) Jddress2; *riteln/0T I! 4 0) I!2;
*riteln/0T !G 4 0) !G2; *riteln/0------------------------------------------0 2;
*riteln/0Press enter 3ey to close02; eadln;end.
Strings can be concatenated to produce larger strings. For example we can concatenate FirstName,
SecondName, and FamilyNameinto another string called FullName, similar to the next example:
8/13/2019 Start Prog Using Pascal
37/152
var Aourame4 string; at(er4 string; Srandat(er4 string; ullame4 string;begin Write/0Please enter your first name 4 02; eadln/Aourame2; Write/0Please enter your fat(er name 4 02; eadln/at(er2; Write/0Please enter your grand fat(er name 4 02; eadln/Srandat(er2; ullame49 Aourame + 0 0+ at(er + 0 0+ Srandat(er; *riteln/0Aour full name is4 0) ullame2;
*riteln/0Press enter 3ey to close02; eadln;end.
Note that in this example we have added a space ( ' ')between names (like YourName + ' ' + Father) tomake a separation between names. The space is a character too.
We can do many operations on strings, like searching for subtext in a string, copying one string to
another string variable, or converting text characters to capital or lowercase like the examples below:
This line converts the letters in the FullNamestring value to capital letters:
ullame49 UpperCase/ullame2;
And this converts it to lowercase letters:
ullame49 LowerCase/ullame2;
In the next example, we need to search for the letter ain a user name using the Posfunction. The Pos
function returns the first occurrence (Index) of that character in a string, or returnszeroif that letter or
substring does not exist in the searched text:
var Aourame4 string;
begin Write/0Please enter your name 4 02; eadln/Aourame2; IfPos/0a0) Aourame2 :then *riteln/0Aour name contains a02 else *riteln/0Aour name does not contain a letter02;
*riteln/0Press enter 3ey to close02; eadln;end.
8/13/2019 Start Prog Using Pascal
38/152
If the name contains a capitalA, then Posfunction will not point to it, becauseAis different from aas
we mentioned earlier.
To solve this problem we can convert all user name letters to lowercase case, and then we can do the
search:
If Pos/0a0) o
8/13/2019 Start Prog Using Pascal
39/152
fori49 1toengt(/Aourame2 do *riteln/AourameMiN2;
o)y +unctionWe can copy part of a string using the function copy. For example, if we need to extract the word
'world'from the string 'hello world', we can do it if we know the position of that part, as we have done
in the example below:
var ine4 string; Part4 string;begin ine49 0Hello
8/13/2019 Start Prog Using Pascal
40/152
,(ortame49 &opy/?ont() 1) 62;
*riteln/?ont() 0 is abbreBiated as 4 0) ,(ortame2;
*riteln/0Press enter 3ey to close02; eadln;end.
!nsert )rocedure
TheInsert procedure inserts a substring into a string. Unlike the string concatenation operator (+)
which links two substrings together,Insertadds the substring in the middle of another string.
For example, we can insert the word Pascalinto the string 'Hello world', resulting in 'Hello PascalWorld' as in the following example:
var ine4 string;begin ine49 0Hello
8/13/2019 Start Prog Using Pascal
41/152
(elete )rocedure
This procedure is used to delete a character or substring from a string. We need to know the start
position and the length of substring that should be deleted.
For example, if we need to delete the letters llfrom the string 'Hello World' to make 'Heo World', we
can do it like this:
var ine4 string;begin ine49 0Hello
8/13/2019 Start Prog Using Pascal
42/152
In the foregoing example, we have used the unit SysUtils,which contains the Trimfunction.
There are another two functions that remove spaces from only one side of a string, before/after. These
functions are: TrimRight, TrimLeft.
trin'3e)lace +unction
The StringReplacefunction replaces characters or substrings with other characters or substrings in the
desired string.
programU,treplace;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var ine4 string; ine74 string;begin ine49 0'(is is a test for string replacement0; ine749 !tringReplace/ine) 0 0) 0-0) MrfeplaceJllN2;
*riteln/ine2; *riteln/ine72; Write/0Press enter 3ey to close02; eadln;end.
The parameters of the StringReplacefunction are:
1. Line: This is the original string that we need to modify.
2. ' ': This is the substring that we need to replace. It is spacein this example.
3. '-': This is the alternative substring that we want to replace the previous one in original string.
4. [rfReplaceAll]: This is the replacement type. In this case we need to replace all occurrence of
the spacesubstring.
We can use only one string variable and discard the variable Line2as modified example shows, but we
will lose the original text value.
8/13/2019 Start Prog Using Pascal
43/152
var ine4 string;begin ine49 0'(is is a test for string replacement0; *riteln/ine2; ine49 !tringReplace/ine) 0 0) 0-0) MrfeplaceJllN2; *riteln/ine2; Write/0Press enter 3ey to close02; eadln;end.
8/13/2019 Start Prog Using Pascal
44/152
Arrays
An Array is a chain of variables of the same type. If we need to declare an array of 10 Integer variables,
we can do it like this:
umbers4 arrayM1.. 1:N ofInteger;
We can access single variables in the array using its index. For example, to put a value in the first
variable in the array we can write it as:
umbersM1N49 6:;
To put a value in the second variable, use the index 2:
umbersM7N49 615;
In the next example, we will ask the user to enter 10 student marks and put them in an array. Eventually
we will go through them to extract pass/fail results:
var ?ar3s4 arrayM1.. 1:N ofInteger; i4 Integer;begin fori49 1to1:do begin Write/0Input student number 0) i) 0 mar34 02; eadln/?ar3sMiN2; end;
fori49 1to1:do begin Write/0,tudent number 0) i) 0 mar3 is 4 0) ?ar3sMiN2; if?ar3sMiN 9 C:then *riteln/0 Pass02 else *riteln/0 ail02; end;
*riteln/0Press enter 3ey to close02; eadln;end.
We can modify the previous code to get the highest and lowest student marks:
var ?ar3s4 arrayM1.. 1:N ofInteger; i4 Integer; ?a>) ?in4 Integer;begin
8/13/2019 Start Prog Using Pascal
45/152
fori49 1to1:do begin Write/0Input student number 0) i) 0 mar34 02; eadln/?ar3sMiN2; end;
?a>49 ?ar3sM1N; ?in49 ?ar3sM1N;
fori49 1to1:do begin // Check if current Mark is maximum mark or not if?ar3sMiN ?a> then ?a>49 ?ar3sMiN;
// Check if current value is minimum mark or not if?ar3sMiN ?in then ?in49 ?ar3sMiN;
Write/0,tudent number 0) i) 0 mar3 is 4 0) ?ar3sMiN2;
if?ar3sMiN 9 C:then *riteln/0 Pass02 else *riteln/0 ail02; end;
*riteln/0?a> mar3 is4 0) ?a>2; *riteln/0?in mar3 is4 0) ?in2; *riteln/0Press enter 3ey to close02; eadln;end.
Note that we consider the first mark (Marks[1]) as the maximum and minimum mark, and then we will
compare it with the rest of the marks.
?a>49 ?ar3sM1N; ?in49 ?ar3sM1N;
Inside the loop we compareMax,Minwith each mark. If we find a number that is larger than Max, we
will replaceMaxvalue with it. If we find a number that is less thanMin, then we will replaceMinwith
it.
In the previous example we have introduced comments:
// Check if current Mark is maximum mark or not
We have started the line with the characters //, which means that this line is a comment and will not
affect the code and will not be compiled. This technique is used to describe parts of code to other
programmers or to the programmer himself/herself.
// is used for short comments. If we need to write multi-line comments we can surround them by {}or
(**)
8/13/2019 Start Prog Using Pascal
46/152
Example:
fori49 1to1:do begin { Checkif current Mark is maximum mark or not check if Mark is greater than Max then put it in Max }
if?ar3sMiN ?a> then ?a>49 ?ar3sMiN;
(* Check if current value is minimum mark or not if Min is less than Mark then put Mark value in Min *) if?ar3sMiN ?in then ?in49 ?ar3sMiN;
Write/0,tudent number 0) i) 0 mar3 is 4 0) ?ar3sMiN2; if?ar3sMiN 9 C:then *riteln/0 Pass02 else
*riteln/0 ail02; end;
We can also disable part of our code temporarily by commenting it:
*riteln/0?a> mar3 is4 0) ?a>2;// Writeln(Min mark is! " Min)# *riteln/0Press enter 3ey to close02; eadln;
In the above code, we have disabled the procedure for writing the minimum student mark.
Note:
We can declare an array as having azerobased index the same as in the C language:
?ar3s4 arrayM:.. EN ofInteger;
This can hold 10 elements too, but the first item can be accessed using the index 0:
umbersM:N49 6:;
Second item:
umbersM1N49 615;
Last item:
umbersMEN49 1:;
or umbersMHig(/umbers2N49 1:;
8/13/2019 Start Prog Using Pascal
47/152
3ecords
While arrayscan hold many variables of the same type, recordscan hold variables of different types,
and these variables are called 'Fields'.
This group of variables/fields can be treated as a single unit or variable. We can use records to store
information that belong to the same object, for example, car information:
1. Car type: string variable
2. Engine size: real number
3. Production year: integer value
We can collect these different types in one recordwhich represents a Car as in the following example:
program&ars;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses { you can add units after this };
type '&ar9 record ?odelame4 string; "ngine4 ,ingle; ?odelAear4 Integer; end;
var &ar4 '&ar;begin Write/0Input car ?odel ame4 02; eadln/&ar.?odelame2; Write/0Input car "ngine size4 02; eadln/&ar."ngine2; Write/0Input car ?odel year4 02; eadln/&ar.?odelAear2;
*riteln; *riteln/0&ar information4 02; *riteln/0?odel ame 4 0) &ar.?odelame2; *riteln/0"ngine size 4 0) &ar."ngine2; *riteln/0?odel Aear 4 0) &ar.?odelAear2;
Write/0Press enter 3ey to close..02; eadln;end.
8/13/2019 Start Prog Using Pascal
48/152
In this example ,we have defined a new type (Record) using the 'type'keyword:
type Car9 record ?odelame4 string; "ngine4 ,ingle; ?odelAear4 Integer;
end;
We have added the letter (T) to Carto indicate that this is a type and not a variable. Variable names
could be like: Car, Hour, UserName, but type names should be like: TCar, THouse, and TUserName.
This is a standard in the Pascal language.
When we need to use this new type, then we should declare a variable of that type, for example:
var &ar4 Car;
If we need to store a value in one of its variables/fields, we should access it like this:
&ar.?odelame
Records will be used in theRandom access filessection of this book.
8/13/2019 Start Prog Using Pascal
49/152
*iles
Files are important elements of operating systems and applications. Operating system components are
represented as files, and information and data are represented in files too, like photos, books,
applications, and simple text files.
Operating systems control files management like: reading, writing, editing and deleting files.
Files are divided into many types according to many perspectives. We can group files into two types:
executablefiles, and datafiles. For example compiled binary Lazarus applications are executable files,
while Pascal source code (.pas) are data files. Also PDF books, JPEG pictures, are data files.
We can divide data files into two types according to the representation of their contents:
1. Text files: which are simple text files that can be written, or read using any simple tool including
operating system command lines like cat, vicommands in Linux and type, copy con commands
in Windows.
2. Binary data files: These are more complex and need special applications to open them. For
example, picture files can not be opened using simple command line tools, instead they should
be opened using applications like GIMP, Kolour Paint,MS Paint,etc. If we open picture, or
voice files, we will get unrecognizable characters which mean nothing to the user. Examples of
binary data files are database files, which should be opened using the proper application.
There is another way to categorize files according to access type:
1. Sequential access files: An example of a sequential file is a text file, which has no fixed size
record. Each line has its own length, so we can't know the position (in characters) for the start of
the third line for example. For that reason, we could open the file for read only, or writing only,
and we can also append text only to the end of file. If we need to insert text in the middle of a
file, then we should read file contents into memory, do the modifications, erase the entire file
from disk, then overwrite it the file with the modified text.
2. Random access files: This type of file has a fixed size record. A record is the smallest unit that
we can read and write at one time, and it could beByte,Integer, string, or a user defined record.
We can read and write at the same time, for example, we could read the record number 3 and
copy it to the record number 10. In this case, we can know exactly the position of each record inthe file. Modifying records is simple. In random access files, we can replace/overwrite any
record without affecting the rest of the file.
8/13/2019 Start Prog Using Pascal
50/152
"et +iles
Text files are the simplest files, but we should write to them in only one direction (only forward). We
can not go back while writing to a text file. We should also define the operation mode before opening
the file:Read, WriteorAppend(writing at the end).
In this example, we will display the contents of a text file selected by a user. For example, a user may
have a text file name like c:\test\first.pasin Windows or/home/user/first.pas in Linux:
Reading text file programReading text file program
programeadile;
{$mode objfpc}{$H+}uses
{$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) sys#tils { you can add units after this };
var ileame4 string; 4 'e>tile; ine4 string;begin Write/0Input a te>t file name4 02; eadln/ileame2; ifile">ists/ileame2 then begin // $ink file varia%le (&) 'ith physical file (&ileame) Jssignile/) ileame2;
eset/2; // ut file mode for read" file should exist
// 'hile file has more lines that does not read yet do the loop whilenot"of/2 do
begin eadln/) ine2; // ead a line from text file *riteln/ine2; // +isplay this line in user screen end; &loseile/2; // elease & and &ileame connection end else// else if &ile,xists-- *riteln/0ile does not e>ist02; Write/0Press enter 3ey to close..02; eadln;end.
In Linux we can enter these file names:
8/13/2019 Start Prog Using Pascal
51/152
FetcFresolB.confor
FprocFmeminfoFprocFcpuinfo
We have used new types, functions and procedures to manipulate text files which are:
1. "4 ext"ile;
TextFileis a type that is used to declare a text file variable. This variable can be linked to a text file for
later usage.
2. if "ile#xists/"ile$ame2 t(en
FileExistsis a function contained in the SysUtilsunit. It checks for a file's existence. It returns Trueifthe file exists in the storage media.
3. %ssign"ile/) ileame2;
After we have checked for the file's existence, we can use the AssignFileprocedure to link the file
variable (F) with the physical file. Any further usage of Fvariable will represent the physical file.
4. Reset&"'( // Put file mode for read, file should exist
TheResetprocedure opens text files for reading only, and puts the reading pointer at the first character
of the file.
If there is no read permission for that file for the current user, an error message will appear, like access
denied.
5. Readln/) ine2; // ead a line from text file
The procedureReadlnis used to read a complete line from the file and put it in the variableLine.
Before reading a line from text file, we should make sure that the file has not reached the end. We cando that with the next function,Eof.
6.
8/13/2019 Start Prog Using Pascal
52/152
7. Close"ile/2; // elease & and &ileame connection
After finishing reading from or writing to a file, we should close it to release the file, because the Reset
procedure reserves the file in the operating system and prevents writing and deletion by another
application while the file is open.
We should use CloseFileonly when theResetprocedure succeeds in opening the file. IfResetfails (for
example, if the file does not exist, or is being used by another application) in that case we should not
close the file.
In the next example we will create a new text file and put some text in it:
Creating and writing into text fileCreating and writing into text file
var ileame4 string; 4 'e>tile; ine4 string; eady'o&reate4 Goolean; Jns4 &(ar; i4 Integer;begin Write/0Input a ne< file name4 02; eadln/ileame2;
// Check if file exists" 'arn user if it is already exist ifile">ists/ileame2 then begin
Write/0ile already e>ist) did you
8/13/2019 Start Prog Using Pascal
53/152
i49 1; repeat Write/0ine V 0) i) 0402; Inc/i2; eadln/ine2; ifine 0L0then *riteln/) ine2; // Write line into text file untiline 9 0L0;
&loseile/2; // elease & and &ileame connection" flush %uffer end else// file already exist and user does not 'ant to over'rite it *riteln/0!oing not(ing02; Write/0Press enter 3ey to close..02; eadln;end.
In this example, we have used many important things:
1.Booleantype:
eady'o&reate4 Goolean;
This type can hold only one of two values: either Trueor False. These values can be used directly in if
condition, whileloop or repeatloop.
In the previous example, we have used the if condition like this:
if ?ar3sMiN ?a>t(en
Which eventually turns to Trueor False.
2. UpCasefunction:
ifupcase/Jns2 9 0A0then
This statement is executed when the file exists. The program will warn the user about overwriting an
existing file. If he/she wants to continue, then he/she should enter a lowercaseyor capital Y. The
UpCasefunction will convert the character into a capital letter if it is lowercase.
3.Rewriteprocedure:
Rewrite/2; // Create ne' file for 'riting
The Rewrite procedure is used to create a new empty file. If the file already exists, it will be erased and
overwritten. It also opens the file for writing only in case of text files.
8/13/2019 Start Prog Using Pascal
54/152
4. Writeln(F, ..) procedure:
Writeln/) ine2; // Write line into text file
This procedure is used to write string or variables in text file, and appends them with end of line
characters, which are a carriage return/line feed combination (CR/LF), represented as the characters for
the numbers 13 and 10 respectively.
These characters can not be displayed in a console window, but it will move the screen display cursor to
a new line.
5.Incprocedure:
Inc/i2;
This procedure increases an integer variable by one. It is equivalent to the statement:
i49 i + 1;
6. CloseFileprocedure:
Close"ile/2; // elease & and &ileame connection" flush %uffer
As we mentioned earlier, the CloseFileprocedure releases a file in the operating system. In addition, it
has an additional job when writing to a text file, which is flushing the writing buffer.
Buffering of text files is a feature that makes dealing with text files faster. Instead of writing a single
line or character directly to disk or any other storage media (which is very slow compared with writing
into memory), the application will write these entries into a memory buffer. When the buffer reaches
its full size, it will be flushed (forced to be written) into permanent storage media like a hard disk. This
operation makes writing faster, but it will add the risk of losing some data (in the buffer) if the power is
suddenly lost. To minimize data loss, we should close the file immediately after finishing writing to it,
or calling the Flushprocedure to flush the buffer explicitly.
8/13/2019 Start Prog Using Pascal
55/152
A))endin' to a tet +ile
In this example, we want to open an existing text file for writing at the end of it, without removing its
original contents using the procedureAppend.
Add to text file programAdd to text file program
var ileame4 string; 4 'e>tile; ine4 string; i4 Integer;begin Write/0Input an e>isted file name4 02; eadln/ileame2; ifile">ists/ileame2 then begin // $ink file varia%le (&) 'ith physical file (&ileame) Jssignile/) ileame2;
%ppend/2; // .pen file for appending
*riteln/0Please input file contents line by line0)0
8/13/2019 Start Prog Using Pascal
56/152
3andom access +iles
As we mentioned earlier, the second type of file according to an access type perspective isRandom
access , or direct access. This type of file has a fixed size record, so that we can jump to any record for
reading or writing at any time.
There are two types of random access files: typed files and untyped files.
"y)ed +iles
Typed filesare used for files that contain the same type of data that has the same size of records, for
example, if a file contains records ofBytetype, that means the record size = 1 byte. If the file contains
real numbers (Single), that means all record sizes are 4 bytes, etc.
In the next example, we will show how to use file of Byte:
Marks programMarks program
var 4 fileofGyte; ?ar34 Gyte;begin Jssignile/) 0mar3s.dat02; e
8/13/2019 Start Prog Using Pascal
57/152
Also we have used the function Writeinstead of Writelnto write records in the typed file:
Write/) ?ar32;
Writelnis not suitable for typed files, because it appends CR/LF characters on each line of written text,
but Writestores the record as it is without any additions. In this case, if we have entered 10 records (ofByte), file size will be 10 bytes on disk.
In the next example, we will show how to display the previous file's contents:
Reading student marksReading student marks
programead?ar3s;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var 4 fileofGyte; ?ar34 Gyte;begin
Jssignile/) 0mar3s.dat02; ifile">ists/0mar3s.dat02 then begin eset/2; // .pen file whilenot"of/2 do begin Read/) ?ar32; *riteln/0?ar34 0) ?ar32; end; &loseile/2; end else *riteln/0ile /mar3s.dat2 not found02;
Write/0Press enter 3ey to close..02; eadln;end.
In the next example, we will show how to append new records without deleting the existing data:
8/13/2019 Start Prog Using Pascal
58/152
Appending student marks programAppending student marks program
programJppend?ar3s;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var 4 fileofGyte; ?ar34 Gyte;begin Jssignile/) 0mar3s.dat02; ifile">ists/0mar3s.dat02 then begin ile?ode49 7; // .pen file for read/'rite eset/2; // open file ,ee3/) ile,ize/22; // 0o to %eyond last record *riteln/0Please input students mar3s) it02;
repeat Write/0Input a mar34 02; eadln/?ar32; if?ar3 :then // +ont 'rite value in disk Write/) ?ar32; until?ar3 9 :; &loseile/2;
end else *riteln/0ile mar3s.dat not found02;
Write/0Press enter 3ey to close..02; eadln;end.
After running this program and entering new records, we can run it again to see the appended data.
Note that we have usedResetfor opening the file for writing instead of theRewriteprocedure.Rewrite
erases all data for existing files, and creates an empty file if the file does not exist, whileResetcan only
open an existing file without erasing its contents.
Also we have assigned 2 to the FileModevariable to indicate that we need to open the file for
read/write access mode. 0in FileModemeans read only, 1means write only, 2(Default) means
read/write.
ile?ode49 7; // .pen file for read/'rite eset/2; // open file
8/13/2019 Start Prog Using Pascal
59/152
Resetputs the read/write pointer to the first record, and for that reason if we start to write records
immediately, we will overwrite the old records, so we have used the Seekprocedure to move the
read/write pointer to the end of file. Seekcan be used only with random access files.
If we try to access a record position that does not exist with the Seekprocedure (for example, record
number 100, while we have only 50 records), we will get an error.
We have also used the FileSizefunction, which returns the current record count in the file. It is used in
combination with the Seekprocedure to jump to the end of the file:
,ee3/) ile,ize/22; // 0o to after last record
Note that this example can be used if the Student marks file already exists; if not, then we should run
the first program (Storing Student Marks) because it usesRewritewhich can create new files.
We can combine both methods (ResetandRewrite) according to whether the file exists, as we havedone in the next example:
Create and append student marks programCreate and append student marks program
programead*rite?ar3s;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var 4 fileofGyte; ?ar34 Gyte;begin Jssignile/) 0mar3s.dat02; ifile">ists/0mar3s.dat02 then
begin ile?ode49 7; // .pen file for read/'rite Reset/2; // open file *riteln/0ile already e>ist) opened for append02; // +isplay file records whilenot"of/2 do begin Read/) ?ar32; *riteln/0?ar34 0) ?ar32; end end
8/13/2019 Start Prog Using Pascal
60/152
else// &ile not found" create it begin Rewrite/2; *riteln/0ile does not e>ist)) not it is created02; end;
*riteln/0Please input students mar3s) it02; *riteln/0ile pointer position at record V 0) ilePos/f22; repeat Write/0Input a mar34 02; eadln/?ar32; if?ar3 :then // +ont 'rite value Write/) ?ar32; until?ar3 9 :; &loseile/2;
Write/0Press enter 3ey to close..02; eadln;end.
Note that in this example, we didn't use the Seekprocedure, instead we read all file contents first. Thisoperation (Read all file) moves the pointer to the end of file.
In the next example, we will use a file of records to store Cars information.
Cars database programCars database program
program&arecords;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
type '&ar 9 record
?odelame4 stringM7:N; "ngine4 ,ingle; ?odelAear4 Integer; end;
var 4 fileof'&ar; &ar4 '&ar;begin Jssignile/) 0cars.dat02;
8/13/2019 Start Prog Using Pascal
61/152
ifile">ists/0cars.dat02 then begin ile?ode49 7; // .pen file for read/'rite eset/2; // open file *riteln/0ile already e>ist) opened for append02; // +isplay file records whilenot"of/2 do begin Read/) &ar2; *riteln; *riteln/0&ar V 0) ilePos/2) 0 --------------------------02; *riteln/0?odel 4 0) &ar.?odelame2; *riteln/0Aear 4 0) &ar.?odelAear2; *riteln/0"ngine4 0) &ar."ngine2; end end else// &ile not found" create it begin eist) created02; end;
*riteln/0Please input car informaion) 0)0 in model name to e>it02;
*riteln/0ile pointer position at record V 0) ilePos/f22;
repeat *riteln/0--------------------------02; Write/0Input car ?odel ame 4 02; eadln/car.?odelame2; if&ar.?odelame 0>0then begin Write/0Input car ?odel Aear 4 02; eadln/car.?odelAear2;
Write/0Input car "ngine size4 02; eadln/car."ngine2; Write/) &ar2; end; until&ar.?odelame 9 0>0; &loseile/2;
Write/0Press enter 3ey to close..02; eadln;end.
In the previous example, we declared TCartype to define car information. The first field (ModelName)
is a string variable, but we limited its maximum length [20]:
?odelame4 stringM7:N;
We should use this declaration for string variables before we use them in files, because the default
ANSI Stringvariables has a different and unlimited storage type in memory, but for typed files, every
data type width should be defined.
8/13/2019 Start Prog Using Pascal
62/152
*ile co)yin'
All file types, like text files, binary files, are based on byte units, which are the smallest representation
of data in computer memory and on disk. Every file should contain one byte, two bytes, etc, or no bytes
at all. Every byte could hold an integer or a character code from 0 to 255. We can open all file types
using the File of Byteor File of Chardeclaration.
We can copy any file to another one using File of Bytefiles, and the result will be a new file that is
identical to the source file's contents.
Copy files using file of byteCopy files using file of byte
programiles&opy;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var ,ourceame) !estame4 string;
,ource) !est4 fileofGyte; Gloc34 Gyte;begin *riteln/0iles copy02; Write/0Input source file name4 02; eadln/,ourceame2;
Write/0Input destination file name4 02; eadln/!estame2; ifile">ists/,ourceame2 then begin Jssignile/,ource) ,ourceame2; Jssignile/!est) !estame2;
ile?ode49 :; // open for read only eset/,ource2; // open source file e
8/13/2019 Start Prog Using Pascal
63/152
// destination fileend;
&loseile/,ource2; &loseile/!est2;
end else// 1ource &ile not found *riteln/0,ource ile does not e>ist02;
Write/0&opy file is finis(ed) press enter 3ey to close..02; eadln;end.
After running the previous example, we should enter an existing source file and a new destination file.
In Linux we could enter file names like this:
Input source file name4 F(omeFmotazFRuranFmis(ariF67.mp6Input destination file name4 F(omeFmotazFJlsajda.mp6
In Windows we could enter something like this:
Input source file name4 c4Wp(otosWmypp(oto.jpgInput destination file name4 c4WtempWcopy.jpg
If the source file exists in the same directory as the FileCopyprogram, we could enter only the file
name like this:
Input source file name4 test.pasInput destination file name4 testcopy.pas
If we use this method to copy large files, it will take a very long time compared with operating systemcopy procedures. That means the operating system uses a different technique to copy files. If we want to
copy a 1 megabyte file, that means the while loop will repeat about 1 million times, that means a
million read and a million write operations. If we replace the file of Bytedeclaration withfile of Word,
that means it will take about 500,000 cycles for read and write, but this will work only for the files
whose size is even not odd. It will succeed if a file contains 1,420 bytes, but it will fail with a file of
1,423 bytes.
To copy a file of any kind using a faster method, we should use untyped files.
8/13/2019 Start Prog Using Pascal
64/152
/nty)ed +iles
Untyped filesare random access files,that have a fixed record length, but are not linked to any data
type. Instead, they treat data (records) as an array of bytes or characters.
Copy files using untyped files programCopy files using untyped files program
programiles&opy7;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var ,ourceame) !estame4 string; ,ource) !est4 file; Gloc34 arrayM:.. 1:76N ofGyte; umead4 Integer;begin *riteln/0iles copy02; Write/0Input source file name4 02; eadln/,ourceame2;
Write/0Input destination file name4 02; eadln/!estame2;
ifile">ists/,ourceame2 then begin Jssignile/,ource) ,ourceame2; Jssignile/!est) !estame2;
ile?ode49 :; // open for read only eset/,ource) 12; // open source file e
8/13/2019 Start Prog Using Pascal
65/152
end else// 1ource &ile not found *riteln/0,ource ile does not e>ist02;
Write/0&opy file is finis(ed) press enter 3ey to close..02; eadln;end.
New things in the previous example are:
1. Declaration type of files:
,ource) !est4 file;
2. Read/write variable (Buffer)
Gloc34 arrayM:.. 1:76N ofGyte;
We have used an array of bytes (1 Kilo bytes, and it can be modified) to read and copy files blocks.
3. Opening an untyped file requires an additional parameter:
eset/,ource) 12; // open source file e
8/13/2019 Start Prog Using Pascal
66/152
BlockReadcould read only 100 bytes. Reading fewer records than desired happens also at the
last block of the file. If the file contains 1034 bytes for example, that means in the first loop, we
will get 1024, but in next loop we will get only 10 bytes left, and Eoffunction will return True.
We need theNumReadvalue to use with theBlockWriteprocedure.
5. Writing to untyped files:
*loc+Write/!est) Gloc3) umead2;
This is the write procedure, and it is similar to the BlockReadprocedure, but it has some differences: 1.
Instead of using the SizeOfprocedure, we have usedNumRead, becauseNumReadcontains the actual
read Block size. 2. The fourth parameterNumWritten(which is not used in this example) is not
important, because we always get records written as we desire, unless the disk is full.
After we run this application, notice the speed of copying large files. If the file contains 1 Megabytes,
that means we need only about one thousand reading/writing cycles to copy the entire file.
In the next example, we will use untyped files to read any file and display it as it is stored in memory or
on disk. As we know, files are list of bytes.
Display file contents programDisplay file contents program
programead&ontents;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
var ileame4 string; 4 file; Gloc34 arrayM:.. 1:76N ofGyte; i) umead4 Integer;begin Write/0Input source file name4 02; eadln/ileame2;
ifile">ists/ileame2 then begin Jssignile/) ileame2;
ile?ode49 :; // open for read only
8/13/2019 Start Prog Using Pascal
67/152
eset/) 12;
whilenot"of/2 do begin Gloc3ead/) Gloc3) ,izef/Gloc32) umead2; // display contents in screen fori49 :toumead - 1do *riteln/Gloc3MiN) 040) &(r/Gloc3MiN22; end; &loseile/2;
end else// &ile does not exist *riteln/0,ource ile does not e>ist02;
Write/0press enter 3ey to close..02; eadln;end.
After running this example and entering a text file name for example, we will see for the first time
CR/LF values (13/10), because we display each character code (ASCII). In Linux we will find only linefeed (LF) which has a value of 10 in decimal. This is a line delimiter in text files.
We can display other types of files, like pictures, executables, to see how they look from the inside.
We have used the Chrfunction in this example to get the numerical value of characters, for example the
letter ais stored in memory in a byte as 97, and capitalAis stored as 65.
8/13/2019 Start Prog Using Pascal
68/152
(ate and "ime
Date and time are two of the most important issues in programming. It is important for the applications
that store transaction or any operation information, like purchasing, bills payment, etc, they need to
store the date and time of that transaction. Later they could determine the transactions and operations
that happened during the last month or current month, for example.
An applications log is one operation that relies on date/time recording. We need to know when some
application starts, stops, generates an error, or crashes.
TDateTimeis the type in Object Pascal that we can use to store date/time information. It is a double
precision floating point number that occupies 8 bytes in memory. The fractional part of this type
represents time, and the integral part represents the number of days that have passed since
30/Dec/1899.
In the next example, we will show how to display the current date/time value using theNowfunction.
program!ate'ime;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses ) ,ys#tils { you can add units after this };
begin *riteln/0&urrent date and time4 0) !ate'ime'o,tr/o
8/13/2019 Start Prog Using Pascal
69/152
TheDatefunction returns only the date part of today, and the Timefunction returns the current time
only:
*riteln/0&urrent date is 0) !ate'o,tr/Date22; *riteln/0&urrent time is 0) 'ime'o,tr/ime22;
These two functions put zeroes in the other part, for example, theDatefunction returns the current day
and puts zero in the time part (Zero in time means 12:00 am). The Timefunction returns the current
system time, and puts zero in the date part (Zero in date means 30/12/1899).
We can check this by usingDateTimeToStrfunction:
*riteln/0&urrent date is 0) !ate'ime'o,tr/Date22; *riteln/0&urrent time is 0) !ate'ime'o,tr/ime22;
TheDateTimeToStrdisplays date/time according to the computer's date/time configuration. Its result
may vary between two computer systems, but the FormatDateTimefunction will display date and time
in the format written by the programmer regardless of computer configuration:
*riteln/0&urrent date is 0)"ormatDateime/0yyyy-mm-dd ((4nn4ss0) Date22;
*riteln/0&urrent time is 0)"ormatDateime/0yyyy-mm-dd ((4nn4ss0) ime22;
In the next example, we will treat date/time as a real number, and we will add and subtract values from
it:
begin *riteln/0&urrent date and time is 0) ormat!ate'ime/0yyyy-mm-dd ((4nn4ss0) o
8/13/2019 Start Prog Using Pascal
70/152
var J!ate4 '!ate'ime;begin J!ate49 "ncode!ate/1E5) 11) 1D2; *riteln/0?y date of birt( is4 0) ormat!ate'ime/0yyyy-mm-dd0) J!ate22; Write/0Press enter 3ey to close02; eadln;end.
TheEncodeDatefunction acceptsyear, monthand daysas inputs, and returns year/month/day values in
one variable of type TDateTime.
TheEncodeTimefunction accepts hour, minute, secondandMillisecondand returns time values as one
TDateTimevalue:
var J'ime4 '!ate'ime;begin J'ime49 "ncode'ime/1E) 77) 5:) :2; *riteln/0Jlmug(rib prayer time is4 0) ormat!ate'ime/0((4nn4ss0) J'ime22; Write/0Press enter 3ey to close02; eadln;end.
(ate4time com)arison
You can compare two date/time variables the same as comparing real numbers. For example in real
numbers: 9.3 is greater than 5.1, the same happens for TDateTimevalues. Now + 1, which represents
tomorrow, is greater than today (Now), and Now + 1/24 which means an hour after now is greater than
Now 2/24 which means two hours before now.
In the next example, we will put the date 1/Jan/2012in a variable and compare it with current date and
check if this date is passed or not yet.
var Aear7:174 '!ate'ime;begin Aear7:1749 "ncode!ate/7:17) 1) 12;
ifo< Aear7:17 then *riteln/0Aear 7:17 is not coming yet02 else *riteln/0Aear 7:17 is already passed02; Write/0Press enter 3ey to close02;
8/13/2019 Start Prog Using Pascal
71/152
eadln;end.
We can add new functions to this example, which displays the remaining days or passed days to/from
that date:
var Aear7:174 '!ate'ime; !iff4 !ouble;begin Aear7:1749 "ncode!ate/7:17) 1) 12; !iff49 Jbs/o< - Aear7:172;
ifo< Aear7:17 then *riteln/0Aear 7:17 is not coming yet) t(ere are 0)
ormat/0L:.7f0) M!iffN2) 0 days emaining 02 else *riteln/0irst day of Qanuary 7:17 is passed by 0) ormat/0L:.7f0) M!iffN2) 0 !ays02; Write/0Press enter 3ey to close02; eadln;end.
Diffis a real number variable that will hold the difference between current date and the 2012 date. We
also used theAbsfunction, which returns the absolute value of a number (the number without the
negative sign).
News recorder programNews recorder program
In this example, we will use text files to store News titles, and in addition, we will store date and time
too.
After closing and opening the application again, it will display the previously entered news titles with
their date/time:
programne
8/13/2019 Start Prog Using Pascal
72/152
{ you can add units after this };
var 'itle4 string; 4 'e>tile;begin Jssignile/) 0net02; ifile">ists/0net02 then begin // +isplay old ne's eset/2; whilenot"of/2 do begin eadln/) 'itle2; *riteln/'itle2; end; &loseile/2; // reading is finished from old ne's Jppend/2; // open file again for appending end else e
8/13/2019 Start Prog Using Pascal
73/152
onstants
Constants are similar to variables. They have names and can hold values, but differ from variables in
modifying that value. Constant values can not be modified while running the application, and their
values should be determined before compiling the application.
We have used constants in a different way before, without naming them, just as an Integer value or
string as in this example:
*riteln/52; *riteln/0Hello02;
The value 5 will never change after running the application. 'Hello' is also a string constant.
We can define constants using the Constkeyword after the application's uses clause as in the following
example:
Fuel Consumption programFuel Consumption program
programuel&onsumption;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads)
{$"!I}{$"!I} &lasses) ,ys#tils { you can add units after this };
const,allonPrice9 D.5;
var Payment4 Integer; &onsumption4 Integer; Oilos4 ,ingle;begin Write/0Ho< muc( did you pay for your car00s fuel4 02;
eadln/Payment2; Write/0*(at is t(e consumption of your carK /Oilos per Sallon24 02; eadln/&onsumption2;
Oilos49 /Payment F SallonPrice2 8 &onsumption;
*riteln/0'(is fuel
8/13/2019 Start Prog Using Pascal
74/152
In the previous example, we will calculate the kilometers that the car could run with its current fuel
according to these facts:
1. Car fuel consumption: we have used the Consumptionvariable to store kilometers per gallon for
the current car2. Fuel: we have used the Paymentvariable to store how much money we paid for the current fuel
3. Gallon Price: we have used the GallonPriceconstant to store the price for a gallon of fuel for
the current country. This value shouldn't be entered by the user; instead, it should be defined by
the programmer.
Constants are recommended when using the same value many times in the application. If we need to
change this value, we can do it once at the header of code.
8/13/2019 Start Prog Using Pascal
75/152
$rdinal ty)es
Ordinal types are integer values that use literal indications instead of numbers. For example, if we need
to define language variables (Arabic/English/French) we could use the value 1 for Arabic, 2 for
English, and 3 for French. Other programmers wouldn't know the values for 1, 2 and 3 unless they find
comments with these values. It will be more readable if we do it with ordinal types as in the below
example:
programrdinal'ypes;
{$mode objfpc}{$H+}
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I}
&lasses { you can add units after this };
type Languageype- <%rabic. lt#nglish'(
var ang4 'anguage'ype; Jame4 string; ,election4 Gyte;begin Write/0Please select anguage4 1 /Jrabic2) 7 /"nglis(202; eadln/,election2;
if,election 9 1then ang49 ltJrabic else ifselection 9 7then ang49 lt"nglis( else *riteln/0*rong entry02;
ifang 9 ltJrabic then Write/0XYZ[ \]^_4 02 else ifang 9 lt"nglis( then
Write/0*(at is your name4 02; eadln/Jame2;
ifang 9 ltJrabic then begin *riteln/0X` ^_ 0) Jame2; Write/0_^[ hk ^ ^q_ vwx[ ^[02; end else ifang 9 lt"nglis( then
8/13/2019 Start Prog Using Pascal
76/152
begin *riteln/0Hello 0) Jame2; Write/0Please press enter 3ey to close02; end; eadln;
end.
Integer, characterand booleantypes are ordinal types, while real numbers and strings are not.
8/13/2019 Start Prog Using Pascal
77/152
ets
Set types can hold multiple properties or characteristics in one variable. Sets are used only with ordinal
values.
For example, if we need to define the operating system's support for applications, we can do it as in the
following:
1. Define ordinal type that represents operating systems: TApplicationEnv:
%pplication#nv9 /aeinu>) ae?ac) ae*indo4 setof'Jpplication"nB;
3. Put operating system values in the application set variable:
ireo>49 Maeinu>) ae*indo
8/13/2019 Start Prog Using Pascal
78/152
else *riteln/0'(ere is no Bersion of ,uper'u> under linu>02;
ifae?ac in,uper'u> then *riteln/0'(ere is a Bersion for ,uper'u> under ?ac02 else *riteln/0'(ere is no Bersion of ,uper'u> under ?ac02;
eadln;end.
Also we can use set syntax for other ordinal types, like Integers:
if?ont( inM1) 6) 5) ) @) 1:) 17N then *riteln/0'(is mont( contains 61 days02;
Or character:
if&(arinM0a0) 0J0N then *riteln/0'(is letter is J02;
8/13/2019 Start Prog Using Pascal
79/152
Ece)tion #andlin'
There are two types of errors: compilation errors like using a variable without defining it in the Var
section, or writing statements with incorrect syntax. These types of errors prevent the application from
compiling, and the compiler displays a proper message and points to the line containing the error.
The second type is the runtime error. This type of error occurs while the application is running, for
example, division by zero, In a line like this:
>49 y F z;
This is valid syntax, but at run time a user could enter 0 in theZvariable, and then the application will
crash and display a division by zeroerror message.
Trying to open a nonexistent file will generate a runtime error also (File not found), or trying to create a
file in a read only directory.
The compiler cannot catch such errors, which only occur after running the application.
To build a reliable application that will not crash from runtime errors, we should use exception
handling.
There are different methods of exception handling in Object Pascal:
"ry ece)t statement
Syntax:
try // 1tart of protected code &allProc1; &allProc7; // ,nd of protected code
exceptone4 e>ception do// ,xception handlingbegin
*riteln/0"rror4 0+ e.message2;end;end;
Example for division:
program">ceptionHandling;
{$mode objfpc}{$H+}
8/13/2019 Start Prog Using Pascal
80/152
uses {$I!" #I%}{$I!" #se&'(reads} ct(reads) {$"!I}{$"!I} &lasses) sysutils { you can add units after this };
var >) y4 Integer; es4 !ouble;begin try Write/0Input >4 02;