Pascal Programming for CSEC

Welcome to Pascal Programming for CSEC- a website which is particularly developed to help you learn the Pascal Programming language step-by-step! Enjoy surfing this website and get yourself reading the lessons built purposely for those who would like to get themselves familiar and capable of writing structured Pascal programs. This site is geared towards preparing students for  CSEC Information Technology. Included in this site provides videos and other multimedia tools to teach some of the most challenging topics in CSEC IT.
This site is a rich collection of information gathered from some of the CSEC online learning sites such as Notesmasters, wizznotes and other online resources. Some of the text from which information has been taken include Log on to IT for CSEC (by Roland Birbal and Michele Taylor) and information Technology (by Kevin Skeete and Kyle Skeete).



Introduction to Pascal Programming

Learning Plan





Previous Knowledge:


Pascal Programming Introduction

Pascal is a very easy language, and helps beginners to introduce them to other languages, before they can start to learn C or C++ or any other advanced language (such as JAVA) - it is the doorstep to other high level programming languages (and talking from experience I have first learnt Pascal which made it very easy for me to migrate to other programming languages).

Pascal is a high-level procedural programming language widely used as a as a language to learn general programming concepts. Sometimes Pascal is preferred to other languages, and could be useful to solve technical problems. It is not necessary to learn any other easier language to start learning Pascal, or any of that sort. It is a very easy programming language and helps you understand the basics of the world of programming. 

A General Overview of Low-Level & High-Level Languages

There are two main categories of programming levels; these are low-level and high-level languages. The terms 'low' and 'high' does not mean that a group of 'low-level' languages are inferior to the 'high' ones. A low-level language consists of machine-oriented programming. For example, machine code is the only language with which the CPU understands. The other most-common low-level language, is the Assembly language. The Assembly language has a structure of machine-oriented programming. The Assembly Language, in other words, has a major control of the computer hardware. The Assembly Language makes use of mnemonics and has a better relationship with the memory and the CPU unit far more than that of other programming languages. The Assembly language is sometimes used as part of the source code written in Pascal. A high-level language consists of all those languages which are problem-oriented. A low-level language is not user-friendly, that is, makes it hard for the user to understand the structure of the program. Pascal, C/C++, BASIC, COBOL, Fortran, etc.. are examples of high-level programming languages. High-level languages represent their source code in such a way that it is more understandable to the programmer.

Interpreters and Compilers

The compiler translates the entire program before it is run.

The interpreters translate a line at a time while the program is being run.

Every high-level language has its own source which needs to be translated into the CPU's language - machine code. These translators are referred to as interpreters and compilers. A high-level language package contains either an interpreter, or a compiler, with which a high-level language uses to translate the source code into object code. An interpreter is more slower than a compiler, the fact that it has to be loaded into memory till the end of the translation of the program. It is less practical than the compiler. However, the interpreter can be helpful for correcting out errors in programs i.e. it is ideal for debugging. A compiler is faster due to its single, complete translation of the program into object code. A compiler, compiles the source code (with no syntax errors) and makes a copy of it. This copy is called the 'object code'. After it has been compiled, it does not need a recompilation (unless the source code is changed and a recompilation is required to affect the change). The object code used by the OS in order to execute the compiled program.


Where can I get a Pascal Source Code Editor & Compiler?

Back in the old days, Borland Turbo Pascal, was the one-stop shop Pascal compiler out there. However times change and so do our computers. This compiler has since been outdated and nowadays there are different compilers for Pascal one can use.

It is of fundamental importance that any learner who starts learning Pascal uses a compiler to compile his code and execute it while practicing Pascal coding. At the time of writing, the best source code editor for Pascal programs and compiler is Ezy Pascal.

One can download the compiler by :

clicking here .

For extra notes on problem solving and problem design click here.

Question 1

Programming languages are categorized into two groups, namely   and  

Question 2

  • Pascal
  • C++
  • Cobol
  • Java

What is the name of the programming language we are using?

End of Lesson

Lesson 1-The First Few Steps in Pascal Programming



Videos on the Basic Structure of Pascal Program

The following video tutorial is based on the basic structure of a pascal program and the uses of write and writeln statements

The following video tutorial is based on the basic structure of a pascal program and the uses of read and readln statements

When you are finish looking at the tutorial there is extra notes on the next page, please read them and after that you may proceed to answer the necessary questions to test how much you have learnt from the lesson.

The First Few Steps in Pascal Programming

In a program, you must always obey the rules of the language, in our case, the Pascal language. A natural language has its own grammar rules, spelling and sentence construction. The Pascal programming language is a high level language that has its own syntax rules and grammar rules. As you go along with the lessons, you must note what you can do and what you cannot do in writing a Pascal program. A very simple program is shown below:

Program Lesson1_Program1;


Write('Hello World. Prepare to learn PASCAL!!');



The program is written only to display the message : 'Hello World. Prepare to learn PASCAL!!' - an introductory message that is displayed to you whenever you are going to learn a new programming language. This is simply shown on the screen. So, to display any message on the screen, you should use 'write' (or 'writeln'). The 'readln' statement, here is used as to 'stop' the program and wait until the user presses enter. If the 'readln' statement is missing in this program, then the message is displayed on the screen without giving any chance for the user to read it and exits!

Try running this program with and without the 'readln' statement and notice the difference.

Now, look at this:

Program Lesson1_Program2;


Write('Hello World. Prepare to learn PASCAL!!');



This program also runs perfectly as the previous one. The only difference is: neatness and friendliness.  This first program is, what is commonly referred to in programming, as 'indented'. Indentation is a must in writing programs as it makes it easier to read ie. neater. Indentation also helps with debugging and code presentation. You will note how I indent programs. A program in Pascal always starts by the reserved word 'Program' following the title of the program. There are various restrictions on how to write this statement. Below is a simple example of a small program. (Remember: you can copy and paste the program in a text file, save the text file as filename.pas and open it with your compiler (such as Free Pascal). The .pas extension is required.) In the following program, the computer must prompt the user to enter a number, then the latter is added to the second number input by the user.

Program Lesson1_Program3;

Var Num1, Num2, Sum : Integer;

Begin {no semicolon}

Write('Input number 1:');


Writeln('Input number 2:');


Sum := Num1 + Num2; {addition}




Now we must take a look at the program. A program in Pascal starts with the reserved word 'Program' (although it is not explicitly required) and ends with 'End', following a full stop (this is required though). A full-stop is never used within the program, except when dealing with records (later topics) and at the end of the program as seen in the example above.

The 'Var' statement, is used to introduce any suitable variables which will be used later in the program. These variables are non-constant terms so that they are used in the program for storing values. The terms 'Num1', 'Num2' and 'Sum' in the program are the variables which store any numbers, except those which are real (in fact, during the execution of the program, a runtime error may occur if a decimal number is input). As you can see in the example above, these variables are assigned to as integers. The term 'integer' means any whole number, i.e. a number which is not a decimal number but a positive or negative number. The integer type ranges from -32768 to 32767. So values which are not within the specified range cannot be stored by an integer type. There are other types which are wider in range, but for now the integer type is enough to hold up our values. The variables 'Num1', 'Num2' and 'Sum' are terms which are not reserved words, but can be used as variables in the program to store data in them. They could be changed more than once. Moreover, I could have used 'number1', 'number2' and 'totalsum' (note that there must be no spaces within the variables), instead of 'Num1', 'Num2' and 'Sum', respectively. As you can see, it is much better to shorten the variables than writing long words, such as 'variable_number1'.

After declaring all the variables which are required to be used later in the program, the main program always starts with the reserved word 'Begin'. Without this word, the compiler will display a diagnostic (error message). In the program above, both of the two types of 'write' are used. These are 'write' and 'writeln'. Both has the same function, except that the 'write' function, does not proceed to the following line when writing a statement. If you run this program, you will notice the difference between them. When using these two terms, any message that will be typed in between the brackets and the inverted commas '(' ')', is displayed on the screen. However, if a variable is used instead of a message, withoutusing the inverted commas, the CPU will display the stored variable in the memory, on the screen. In line 9, the CPU will not display 'Sum' on the screen, but the stored number in the memory. Another important thing which must be noticed is the semi-colon (;). The semicolon is used after each statement in the program, except those that you will learn later. However, in the example above, there isn't a semicolon after a 'begin' statement. This is because the flow of the program has just started and must not be stopped by a ';'.

The text in between the braces ({ }) are called comments or in-line documentation. I guess you consider the comments to be 'unnecessary': This is wrong! Comments are very useful in describing complicated tasks and functions. In my experiences, I have encountered many problems, like for instance when having a break from writing a program for a long time, and then resuming again after a long period! Practically, I've spent a long time trying to understand what I have done previously (understand my own code, let alone other programmers try to understand my code). Comments within the braces are not read or compiled by the compiler/interpreter. I will also be using lots of comments along the lessons to explain my code to you!

The 'readln' statement is another reserved word for input purposes, which enables the user to input a number or text only i.e.: using the keyboard. But in our case the 'readln' statement is used to input numbers only (letters are accepted but will cause a run-time error because it is not the input we want) and store them in the variables 'Num1' and 'Num2'. This is because both variables are assigned to as integers, and integer variables do not store strings. A run-time error is detected by the OS (Operating System; ex. Windows or Linux) if something goes wrong with the input. Later in the course, you will also learn how to control input and output exceptions - unexpected runtime errors. One last thing on errors is this: there are 2 major error types which are - Runtime Errors and Compilation Errors. Runtime errors are those which occur unexpectedly during the execution of the program, whereas a Compilation error is one which is detected during the compilation process. Note that a decimal number is also considered as a wrong input; a decimal number must not be input, since it is a real number (more on this later).

After the prompts and inputs by the user, follows the addition. i.e. 

Sum := Num1 + Num2;

The result of the above statement is the addition of the values stored in variables 'Num1' and 'Num2'. The important thing that you should know is that one cannot make the same statement as follows:

Num1 + Num2 := Sum;

This is another syntax error. It is the fact that transfer of information is from left to right and not from right to left. So, mind not to make this error. The ':=' is called the assignment statement, and should be discussed later on.

For extra notes on program implementation click here.

Question 1

Arrange the following code into a well structured pascal program
  • 1st
    Program Name;
  • 2nd
    Var first_score:integer;
  • 3rd
    Const pi:integer:=3.14;
  • 4th
  • 5th
    Writeln("hello world");
  • 6th

Question 2

Char Stores what data?

Real Stores what data?

String Stores what data?

Integer stores what data?

Question 3

  • Start & Stop
  • Program & End.
  • Begin & End.
  • Go & Stop
A program in Pascal starts with the reserved word "..................." and ends with "...................".

Question 4

  • Read and Readln are used to input information into the program
  • Write and Writeln are used to input information into a new line in the program
  • Writeln is used to output information in a new line
  • Readln is used to output information in the same line
Select true or false for the following.

End of Lesson

Lesson 2-Variables, Constants & the Assignment Statement

Video on Variables and Constants


Lesson 2-Variables





Real Numbers and Integers



Variables, Constants & the Assignment Statement


String Variables

Soon, you should learn how to input text by the user using 'string variables'. The following program is written showing an example of a string variable, prompting the user to input his name:

Program Lesson2_Program1;


name, surname: String;

Begin write('Enter your name:');


write('Enter your surname:');


writeln;{new line}

writeln;{new line}

writeln('Your full name is: ',name,' ',surname);



If we take a look at this program, we notice a new variable type : 'String'. Both the name and surname variables are of type string. When the program is run and prompts the user to input his name, the name which is keyed in by the user goes directly to its place in the memory called 'name'. Same occurs to surname. *I'd like to remind you that the variables 'name'and 'surname' are not reserved words, but are used by the programmer as his variables. I could have used 'n' instead of'name' and similarly 'sname' instead of 'surname'. The two 'empty' writeln's in lines 9 and 10 are used to move on to a new line. In this case, 2 lines are cleared. The next message displays the full name of the user using the above format. If a string variable is required to be displayed on screen, it should be put in between inverted commas and commas if it is concatenated with another message.

It could be in the form of: (please note where you should and where you should not put the inverted commas following the commas)

Writeln('Your name is: ',name);


Writeln('Your name is:',name,'. Your surname is ',surname,'.');

Note that you can even make it this way:

Writeln('Your name is: ',name,'');

BUT you should put the inverted commas properly (underlined) to close the string in the last writeln function.



Constants and the Assignment Statement

Apart from variables, there are also items in the program which are referred to as 'constants'. Unlike variables, constants keep their value or string unchanged for the whole program. Here I have made a program, not so much different from the previous one:

Program Lesson2_Program2;

Var surname: String;

Const {the reserved word 'const' is used to initialize constants} name = 'Victor';


Write('Enter your surname:');




Writeln('Your full name is: ',name,' ',surname);



In the above program, the constant 'name' is assigned to as 'Victor' and is of type string. However, in other cases, you might have used integer constants (whole numbers), i.e.:

Const age = 15;

The constant 'age' is a value that could be used whever it is required in a program.


age2 := 15; age2 := age + 15;

The above example shows an addition of the value of the variable 'age' with the value 15. The value of the constant 'age' remains 15, but the value of the variable 'age2' becomes 30. The assignment statement is not only used for additions, but is also used to assign a variable: text if it is a string variable or a numeric value if it is an integer variable. Try examine this yourself:

name := 'victor'; age := 15; {also: "age:='15';" BUT in this case, 'age' is an integer variable} writeln('Name:',name,'. Age:',age,'.');


I conclude lesson 2 with another simple program for you to read and think about:

Program lesson2_Program3;


PD, Dname, Cmodel : String;

TotalKM, CostPD, TCostPD, Distance : Real; {real is a decimal (described later)}

Begin TCostPD := 0; {note that this is called an 'initialisation'. It is important to initialise variables to 0 so that it is 'refreshed' from the previous 'rubbish' value in the memory.}

Writeln('This program prompts you to ' + + 'input the cost per litre of');

Writeln('the petrol/diesel you spend ' + + 'in and the average distance you travel');

Writeln('with your car every week. Then ' + + 'the computer calculates the total cost');

Writeln('you spend in fuel every week.'); Readln; Write('Diesel or Petrol?: ');


Write('Name Of Driver: ');


Write('Car Model: ');


Write('Cost of Diesel/Petrol: (£) ');


Writeln('Average distance you travel ' + + 'with your car every week: (kilometres) ');




Writeln('Name of Driver:',Dname);

Writeln('Car Model:',Cmodel);


Writeln('Average distance covered '+ +'every week: ',Distance:1:2,'Km');

Writeln('Cost of ',PD,' per liter: £',CostPD:1:2,'/litre');


Writeln; TCostPD := Distance * CostPD;

Writeln('Total cost of ',PD,' per week:' + + '£',TCostPD:1:2); {note this,} TCostPD := 0;

Writeln('Total cost of ',PD,' per week:'+ + '£',(Distance * CostPD):1:2); {this}

Writeln('Total cost of ',PD,' per week:'+ + '£',Distance * CostPD); {and this - without ':1:2'}



Question 1

Match the examples to their Data Types
  • -1,1,2,3
  • 12.3, 1.4, 2.34
  • 'A', 'B', '*'
  • 'John', 'hello', 'Mary

Question 2

Match the definition with the words
  • Variable
    a container that can change throughout the program
  • Constant
    a container that remains the same throughout the program

Question 3

  • Writeln("Hello World");
  • Readln("Hello World");
How do you output to the user "Hello World" in pascal programming?

End of Lesson

Lesson 3-Special Functions of the CRT Unit: ClrScr(), GotoXy(), etc...

Functions of the CRT Unit: ClrScr(), GotoXy(), etc.

Description of the CRT Functions

Below is a table of the new words:

Reserved Word

Crt: Yes/No


Clrscr Yes Clears screen
Gotoxy(int,int) Yes Takes the cursor to the pre-defined position
Textbackground(word/int) Yes Background colour
Textcolor(word/int) Yes Colour of text
Readkey Yes Reads a key; Could be assigned to a variable
Delay(int) Yes Waits for the included time(milliseconds)
Halt(parameter) No Program terminates

int - integer (-32768 to 32767), word - 0 to 65535.


• Clrscr: (clear screen)

Writeln('When you press enter, the screen would be cleared!');



• Gotoxy(int,int): (Go to position x and y);


Writeln('The position is 10 pixels from the left of the screen, and ten pixels');

Writeln('from the top of the screen.');


• Textbackground(word/int): (Background colour);

Textbackground(red); {word - red}

Writeln('Note the difference');

Textbackground(5); {integer - 5}


Writeln('Note the difference');


• Textcolor(word/int): (Text colour);

Textcolor(red); {word - red}

Writeln('Text colour');

Textcolor(5); {integer - 5}

Writeln('Text colour');


• Readkey: (Reads a key-press);

Example 1:

Writeln('Press ANY key!!!');


Example 2:

Writeln('Press ANY key');

Keypress := Readkey; {keypress is a DECLARED string variable(can be an integer variable)} Writeln(Keypress);

• Delay(int): (Holds for some time in milliseconds);


Delay(1000); {1000 milliseconds}





• Halt(int): (Program terminates with an exit code);

Writeln('Press enter and the program terminates!); Readln; Halt(0);

Note that instructions following 'halt' are not executed since the program terminates when halt is encountered.

Untitled multiple choice question

  • Put your answer option here
  • Put your answer option here

Untitled text matching question

  • Define your key...
    Define your answer...
  • Define your key...
    Define your answer...

Untitled statement question

  • Type your statement here...
  • Type your statement here...

End of Lesson

Lesson 4- Program Flow Control (If Statement, Repeat-Until & For Loop)

Videos on If Statements and Loop (While,Repeat and For)

IF Statements

While Loops
Repeat loops


Repeat Loops


For Loops





Program Flow Control (If Statement, Repeat-Until & For Loop)

The IF Statement

The 'if statement' executes a the proceeding statement(s) conditionally. This means that if an action comes to be true, then the statement(s) proceeding the if statement are executed, else these statements are skipped. It works like this:

If some <condition> happensthen do this (reaction, if condition is true).


If some <condition> happens, then 

do this (reaction, if condition is true)

else do this (reaction, if condition is false).

In Pascal, the 'if statement' should be written using the following syntax:

If conditional expression then

code ... ;{if one action}


If <conditional expression> then

Begin <instructions> ... 

End; {if more than one instruction is required}

Note that you should not use an assignment statement in the 'if' construct, otherwise the compiler will raise a syntax error. I.e.:


If x := 20 then x := x + 1; {the underlined character must be excluded}


If x = 20 then x := x + 1; {only an equal sign is used for comparison}

A program is shown below as an example of how the 'if statement' works:

Program lesson4_Program1;

Uses Crt;

Label 1; {this is used with a goto statement}


Sel: String;

N1,N2, Total : Real;

YN : Char; {this is a character variable type, which holds single characters ONLY}



Total := 0; {always initialise integer/real variables}








Write('Select: ');

Sel := Readkey;

If Sel = '1' {action} Then

Begin {more than one statement}


Write('Input No.1:');


Write('Input No.2:');


Total := N1 + N2;

Writeln('Addition: ',N1:2:3,' + ',N2:2:3,' = ',Total:2:3);

Write('Press any key to continue...');

Readkey; Goto 1;{this leads back to the beginning of the program, otherwise the program terminates} End; {Closing the if statement(begin)}

If Sel = '2' Then {note that the assignment statement is not used within an if statement}



Write('Input No.1:');


Write('Input No.2:');


Total := N1 - N2;

Write('Subtraction: ');

Write(N1:2:3,' - ',N2:2:3,' = ',Total:2:3);

Write('Press any key to continue...');


Goto 1;

End; {Closing the if statement}

If Sel = '3' Then



Write('Are you sure?(Y/N)');

YN := Readkey;

If YN = 'y' Then

Halt; {1 action, so no need of Begin..End}

If YN = 'n' Then

Goto 1; {the goto statement is not recommended for excessive use}



In the above program, the 'goto' statement is used. So far, it has been a real damage to programs and it has produced unwanted confusions. I strongly suggest you not to use it repeatedly (or better yet not at all).



If ..Then .. Else

Normally, the instructions following the if statement cannot be executed if the condition is not true. But in an if..then..else statement, there is at least one set of statements to be executed. Let's take a look at the example below:

Writeln('Who has discovered the land of America?');


If (ans = 'Christopher Colombus') Then

score := score + 1 { if this does not execute, }


Writeln('sorry, you''ve got it wrong!'); { then this executes }

Note that if the 'else' term is included with an if statement, then there should be no semi-colon before the 'else' term; just as seen in the above example.



Nested If Statements

The previous program have already shown an example of nested if statements. I.e.:

If Sel = '3' then



Write('Are you sure?(Y/N)');

YN := Readkey;

If YN = 'y' Then

HALT; {Nested if statement}

If YN = 'n' Then

Goto 1; {Another Nested if statement}


A nested if statement, is in the form:

If (this happens) then    {if 1}
If (this happens) then    {if 2}
(do this) etc...
Else (do this)            {if 2}
Else (do this) etc...   {if 1}

A nested if statement is an if statement within another if statement, as shown above.



The Repeat-Until Loop

This loop is used to repeat the execution of a set of instructions for at least one time. It is repeated until the conditional expression is obeyed. The following example, shows the model of the 'repeat-until' loop:


Until <some conditional statement is true>;

Here's an example:

Uses Crt; Var YN : String; Begin Writeln('Y(YES) or N(NO)?'); Repeat {repeat the code for at least one time} YN := Readkey; If YN = 'y' Then Halt; {Halt - exit} If YN = 'n' Then Writeln('Why not? Exiting...'); Delay(1800); { wait a second plus 800 milliseconds } Until (YN = 'y') OR (YN = 'n'); End.

See? It's very simple! In the above program, there is a Boolean expression in the 10th line (or). This will be described later on.



The For Loop

The for loop is a sort of repeat-until loop. The for loop, repeats a set of instructions for a number of times. The for loop is in the form:

- If used for only one action:

for {counter (variable)}* := {initial value} to/downto {final value} do

{code...(for one instruction)}

- If used for more than one instruction:

for {counter (variable)}* := {initial value} to/downto {final value} do Begin




*Generally, this variable is called the 'loop counter'.

Now, an example of the for loop is shown below, but firstly, you should appreciate the usefulness of the for loop. Consider the following example:

Without for loop:

Program lesson4_Program2a; Uses Crt; Begin Writeln('for loop'); {somewhat boring writing all this!!!} Writeln('for loop'); Writeln('for loop'); Writeln('for loop'); Writeln('for loop'); Writeln('for loop'); Writeln('for loop'); Readln; End.

With for loop:

Program lesson4_Program2b; Uses Crt; Var Counter : Integer; {loop counter declared as integer} Begin For Counter := 1 to 7 do {it's easy and fast!} Writeln('for loop'); Readln; End.

Note that the two programs above perform the same function, but which programming style is more useful?

Suppose we have to make a program which designs a small box with some of the characters of the ASCII, obviously the characters which are most likely to make up a simple box. 

Without the for loop:

Program Program3a_lesson4; Uses Crt; Begin Gotoxy(25,5); Writeln('+'); Gotoxy(25,6); Writeln('I'); GotoXy(25,7); Writeln('I'); GotoXy(25,8); Writeln('I'); GotoXy(25,9); Writeln('I'); GotoXy(25,10); Writeln('I'); GotoXy(25,11); Writeln('+'); GotoXy(26,11); Writeln('-'); GotoXy(27,11); Writeln('-'); GotoXy(28,11); Writeln('-'); GotoXy(29,11); Writeln('-'); GotoXy(30,11); Writeln('-'); GotoXy(31,11); Writeln('-'); GotoXy(32,5); Writeln('+'); Gotoxy(32,6); Writeln('I'); GotoXy(32,7); Writeln('I'); GotoXy(32,8); Writeln('I'); GotoXy(32,9); Writeln('I'); GotoXy(32,10); Writeln('I'); GotoXy(32,5); Writeln('+'); GotoXy(26,5); Writeln('-'); GotoXy(27,5); Writeln('-'); GotoXy(28,5); Writeln('-'); GotoXy(29,5); Writeln('-'); GotoXy(30,5); Writeln('-'); GotoXy(31,5); Writeln('-'); {oh my God!!! Phew!} Readln; { wait for user to read } End.

With for loop:

Program Program3b_lesson4; Uses Crt; Var Counter : Integer; {loop counter} Begin For Counter := 1 to 5 do Begin gotoxy(25, 5 + Counter); Writeln('I'); End; For Counter := 5 Downto 1 do Begin {an example of 'downto' instead of 'to', note the 'gotoxy(_,_)'} gotoxy(32, 11 - Counter); Writeln('I'); End; For Counter := 1 to 6 do Begin gotoxy(25 + Counter, 11); Writeln('-'); End; For Counter := 6 Downto 1 do Begin gotoxy(32 - Counter, 5); Writeln('-'); End; {--------------The Corners(+)---------------} Gotoxy(25,5); Writeln('+'); GotoXy(25,11); Writeln('+'); GotoXy(32,5); Writeln('+'); GotoXy(32,11); Writeln('+'); GotoXy(45,7); Writeln('Just as simple as the for loop!!!'); Readln; End.

Again, the two programs above perform the same function.



Nested for loops

A nested for loop is similar to that of the nested if statements. A nested for loop is in the form:

for {loop counter} := {original value} to {final value} do {Begin-if required}

        {code if any..begin should be included (i.e more than one action)}

  for {loop counter} := {original value} to {final value} do {Begin-if required}

        {code..if more than one action, include begin in the second for loop}

  {End; - if begin is included in the second for loop)}

        {code if any..begin should be included in the first for loop} 

{End; - if begin is included in the first for loop)}

The nested for loop is rarely used and it may cause problems.



While-Do Loop

This type of loop is executed while the condition is true. It is different from the 'Repeat-Until' loop since the loop might not be executed for at least one time. The code works like this:

While <condition is true> do the following:

instruction 1;

instruction 2;

instruction 3;


End; {If while-do loop starts with a begin statement}

Example Program on the While-Do loop:

Program Lesson4_Program4; Uses Crt; Var Ch : Char; Begin Writeln('Press ''q'' to exit...'); Ch := Readkey; While Ch <> 'q' do Begin Writeln('I told you press ''q'' to exit!!'); Ch := Readkey; End; End.

Untitled drag and drop text question

Untitled multiple choice question

  • Put your answer option here
  • Put your answer option here

Untitled fill in the blanks question

Untitled statement question

  • Type your statement here...
  • Type your statement here...

End of Lesson

Lesson 5-The CASE-OF Statement

The CASE-OF Statement

The Syntax of the CASE-OF Statement

So far, you have learned how to use an 'if statement'. But in some cases the 'case statement' is preferred to the if statement because it reduces some unnecessary code but the same meaning is retained. The case statement is very similar to the if statement, except in that the it does not accept literal conditional expressions (i.e.: strings) but surprisingly enough, it allows single character conditional expressions. Here is how it works:

Case {variable of type: integer or character ONLYof

         {input statement- within inverted commas if of type char} : {code..}

         {input statement- within inverted commas if of type char} : {code..}


End;   {End Case}

Now you should note the difference and the intelligent use of the case statement over the if statement. The Program is written using the if statement:

Program Program1a_Lesson5; Uses Crt; Label Return; {used respectively with the goto statement; beware of it} Var SEL : Integer; YN : Char; Begin Return: Clrscr; Writeln('[1].PLAY GAME'); WRITELN('[2].LOAD GAME'); WRITELN('[3].MULTIPLAYER'); WRITELN('[4].EXIT GAME'); Writeln('note: Do not press anything except'); Writeln('numbers; otherwise an error occurs!'); Readln(SEL); If SEL = 1 Then Begin Writeln('You will soon be able to create'); Writeln('games using Pascal Programming :-)'); Delay(2000); Goto Return; End; If SEL = 2 Then Begin Writeln('Ahhh... no saved games'); Delay(2000); Goto Return; End; If SEL = 3 Then Begin Writeln('networking or 2 players?'); Delay(2000); Goto Return; End; If SEL = 4 Then Begin Writeln('Are you sure you want to Exit?'); YN := Readkey; If YN = 'y' Then Begin Writeln('Good Bye...'); Delay(1000); Halt; {EXIT PROGRAM} End; If YN = 'n' Then Goto Return; End; End.

Now, the folowing program is written using the case-of statement instead of the if statements and the output 
is exactly the same.

Program Program1b_Lesson5; Uses Crt; Label Return; {use of the goto statement is not recommended..avoid it} Var SEL : Integer; YN : Char; Begin Return:Clrscr; Writeln('[1].PLAY GAME'); WRITELN('[2].LOAD GAME'); WRITELN('[3].MULTIPLAYER'); WRITELN('[4].EXIT GAME'); Writeln('note: Do not press anything except'); Writeln('numbers; otherwise an error occurs!'); Readln(SEL); Case SEL of 1 : Begin Writeln('You will soon be able to create'); Writeln('games using Pascal Programming :-)'); Delay(2000); Goto Return; End; 2 : Begin Writeln('Ahhh... no saved games'); Delay(2000); Goto Return; End; 3 : Begin Writeln('networking or 2 players?'); Delay(2000); Goto Return; End; 4 : Begin Writeln('Exit?'); YN := Readkey; Case YN of {a sort of a nested case statement} 'y' : Begin Writeln('Good Bye...'); Delay(1000); Halt; End; 'n' : Goto Return; End; {End Case 2} End; {Close Conditional Expression 4} End; {End Case 1} End.


The CASE-OF-ELSE Statement

Again this is similar to the if..then..else statement. Study the program below to learn how to use the 'else' term following the 'case statement':

Program Program2_Lesson5; Uses Crt; Label Return; { avoid it } Var YN : Char; Begin Return: ClrScr; Writeln('Exiting?'); YN := Readkey; Case YN of 'y' : Halt; 'n' : Begin Writeln('What are you going to do here, anyway?'); Delay(2000); Halt; End; Else Begin Writeln('Press either ''y'' for yes'); Writeln('or ''n'' for no.. please try again..'); Delay(3500); ClrScr; Goto Return; End; End; {CASE} End. {PROGRAM}

Basically, what the code does above is that if the input is none of 'y' or 'n', then program flow falls to the 'else' of the case statement - its like an 'if all else fails'. It works like the last 'else' of the if statement.

Lesson 6-Logical Operators and Boolean Expressions

Logical Operators and Boolean Expressions

What are Logical Operators?

Logical operators are used in conditional expressions which return true or false called a Boolean result. A Boolean expression is one which contains these logical operators. They are also used in assignments (an example of this would be shown later). Such operators consist of simple logical operators, such as 'Not' or 'And'. They should be used in between conditional expressions.

For example:

If (x = 0) AND (a = 2) Then ...



The Logical Operators

There are three types of logical operators, each of which are concerned with conditional expressions. These are:

  • AND
  • OR
  • NOT

These logical operators have a different effect on the conditional expressions. Let's see how each of the logical operator behaves on the following conditional expressions...



The 'AND' Logical Operator

If (admin = 'admin') AND (password = 'pass') Then Writeln('Login accepted. Welcome Administrator!');

Expression 1 Expression 2 AND (result)
true true true
false true false
true false false
false false false


You can see very clearly from this table that if expression 1 and expression 2 are both true (i.e. the user inputs 'admin' and 'pass' into variables 'admin' and 'password' respectively), the message will be displayed. Above is a table showing the possible combinations. So, from the above table, one can conclude that for a logical operation such as AND, to give out a true result, both conditional expressions should be true.



The 'OR' Logical Operator

If (month = 'July') OR (month = 'August') Then Writeln('Month is either July or August.');

Expression 1 Expression 2 OR (result)
true true true
false true true
true false true
false false false


Either expression 1 or expression 2 should be true to display the message. If for example expression 1 is true and any other conditional expressions are false, the result is true! Above is the truth table showing all the possible combinations. So, from the above table, one can conclude that for a logical operation such as OR, to give out a true result, only one of the conditional expressions should be true.



The 'NOT' Logical Operator

Not is different from the two logical operators. It only accepts one input and is known as the 'inverter'. If for example the result of two conditional expressions is true, the 'not' operator will invert the result to false! So, the purpose of the logical operator, 'not', is to invert the input. The simple truth table for the not operator is as follows:

Input NOT (result)
true true
false true
true true
false false




Example of the 'AND' Operator

Program Lesson6_Program1; Uses Crt; Var n1, n2 : string; Begin Writeln('Enter two numbers: (''0'' & ''0'' to exit)'); Repeat Write('No.1: '); Readln(n1); Write('No.2: '); Readln(n2); If (n1 = '0') AND (n2 = '0') Then Halt(0); Until (n1 = '0') AND (n2 = '0'); End.




Example of the 'OR' Operator

Program Lesson6_Program2; Uses Crt; Var n1, n2 : String; Begin Writeln('Enter two numbers: (''1'' & ''2'' to exit)'); Repeat Write('No.1: '); Readln(n1); Write('No.2: '); Readln(n2); If (n1 = '1') OR (n2 = '2') Then Halt; Until (n1 = '1') OR (n2 = '2'); End.




Example of the 'NOT' Operator

Program Lesson6_Program3; Uses Crt; Var n1 : String; Begin Writeln('Enter two numbers: (any number except 0 to exit)'); Repeat Write('No.1: '); Readln(n1); If not(n1 = '0') Then Halt; Until not(n1 = '0'); End.




Boolean Expressions

Boolean expressions are expressions which evaluate to either 'true' or 'false'. The data type of a boolean variable is called a Boolean and stores either true or false.

Var bool : Boolean; bool := True;

Example use of a boolean variable:

Program Lesson6_Program4; Var quit : Boolean; a : String; Begin quit := False; Repeat Writeln('Type ''exit'' to quit:'); Readln(a); If a = 'exit' Then quit := True; Until quit = True; End.

Lesson 7-Procedures and Functions

Procedures and Functions


Procedures are just like small programs. Sometimes they are called sub--programs. They help the programmer to avoid repetitions. A procedure start off with a begin and ends up with an end;. It can also have its own variables, which cannot be used with the main-program. To have an exact definition of a procedure, you should compare a program which includes a repeated section with another program avoiding the repeated sections by using a procedure, which is called several times:

Program Lesson7_Program1a; Uses Crt; Var Counter : Integer; Begin textcolor(green); GotoXy(10,5); For Counter := 1 to 10 do Begin Write(chr(196)); End; GotoXy(10,6); For Counter := 1 to 10 do Begin Write(chr(196)); End; GotoXy(10,7); For Counter := 1 to 10 do Begin Write(chr(196)); End; GotoXy(10,10); For Counter := 1 to 10 do Begin Write(chr(196)); End; Readkey; End.

Now have a look at the next program which uses a procedure:

Program Lesson7_Program1; Uses Crt; Procedure DrawLine; {This procedure helps me to avoid the rewriting the for loops} Var Counter : Integer; Begin textcolor(green); For Counter := 1 to 10 do Begin Write(chr(196)); End; End; Begin GotoXy(10,5); DrawLine; GotoXy(10,6); DrawLine; GotoXy(10,7); DrawLine; GotoXy(10,10); DrawLine; Readkey; End.

There are some differences between these two programs which are very important to note. These are :

  • Size of the program

    It is very important for a program to be small in size. The first program, say, its size is 1900 bytes, but the second one holds about 1350 bytes!

  • Neatness

    Adopting a neat style of writing for a program helps the programmer (and other future debuggers) to cater with future bugs. I think that the first program is cumbersome, whilst the other is not! What do you think??!

  • Repetitions

    Repetitions in a program can cause a hard time for a programmer. So procedures are an essential way to avoid repitions in a program. They also enlarge the size of a program!

  • Debugging Efficiency

    When you are required to debug the program, bugs could be much more easier to find out as the program is sliced into smaller chunks. You may run the program and notice a mistake at a certain point and which is located in a particular procedure/function. It would be much more difficult to find a mistake in a program if it would be one whole piece of code. Do slice your program into smaller chunks, and this needs the planning and design of the whole problem in hand prior starting to code. Coding (or writing up your program) is just one section of the whole software developement process. The whole Software Developement Lifecycle is a critical software engineering process which is divided into different stages facilitating the development of highly complicated software.


Using Procedures with Parameters

Returning back to program Lesson7_Program1b, note the gotoxy statement before the DrawLine; this could effectively be eliminated so that we can avoid the repeating the use of the gotoxy! An effort should always be made to eliminate the duplication of code. Thus we introduce the use of parameters in our procedure so that we can change the position of the characters within the procedure accordingly.. The new program is as follows:

Program Lesson7_Program2; Uses Crt; Procedure DrawLine(X : Integer; Y : Integer); {the declaration of the variables in brackets are called parameters} Var Counter : Integer; {normally this is called a local variable} Begin GotoXy(X,Y); {here I use the arguments of X and Y} textcolor(green); For Counter := 1 to 10 do Begin Write(chr(196)); End; End; Begin DrawLine(10,5); DrawLine(10,6); DrawLine(10,7); DrawLine(10,10); Readkey; End.

Now, this program includes a procedure which uses parameters. Every time it is called, the parameters can be variable, so that the position of the line could be changed. This time, we have also eliminated the gotoxy statement before everyDrawLine statement. The numbers in the brackets of the DrawLine are the parameters which state the position of the line. When arguments are passed to a procedure, variables are declared within the brackets of the procedure, and must be separated by a semi-colon ";". The variables (known as the parameters) should be used by the procedure only. I have written another program which prompts the user to enter his/her favourite text colour and background colour to be used to write text (in his/her favourite colours) further on in the program.

Program Lesson7_Program3; Uses Crt; Var UName, USurn, UCoun, UMail : String[50]; {These var's are global because they are used by more than one procedure} TxtB, TxtC, i : Integer; InfoCor : Boolean; Procedure EnterUserInfo(TxtCol : SmallInt; TxtBck : SmallInt); Begin textcolor(TxtCol); textbackground(TxtBck); ClrScr; Write('Your Name: '); Readln(UName); Write('Your Surname : '); Readln(USurn); Write('Country : '); Readln(UCoun); Write('E-Mail Address: '); Readln(UMail); Write(' Thank you for entering your personal information!!'); Readkey; End; Procedure ConfirmationField(TxtCol : SmallInt; TxtBck : SmallInt); Var YN : Char; { a local variable } Begin textcolor(TxtCol); textbackground(TxtBck); ClrScr; Writeln('Your Name: ',UName); Writeln('Your Surname : ',USurn); Writeln('Country : ',UCoun); Writeln('E-Mail Address: ',UMail); Writeln; Writeln; Writeln('This is a confirmation field. Please verify that'); Writeln('your information is correct!'); Writeln; Write('Is your personal information all correct? [Y/N] '); Repeat YN := Readkey; Case YN Of 'N' : InfoCor := False; 'Y' : InfoCor := True; End; Until (YN = 'N') OR (YN = 'Y'); End; Begin { main program } InfoCor := True; ClrScr; TextBackground(cyan); TextColor(green); Write('A list of colours is being displayed...'); For i := 1 to 16 do Begin Case i Of 16 : Begin TextBackGround(white); End; End; textcolor(i); Writeln(i,': This is Colour No.',i); End; TextBackGround(black); TextColor(white); Write('Please, put into your mind your favourite colour. '); Write('When you are ready press any key...'); Readkey; ClrScr; Write('Enter your favourite text colour: (only numbers) '); Readln(TxtC); Write('Enter your favourite background colour : __'); Readln(TxtB); Writeln; Writeln; Write('Now, you must enter your personal information. '); Write('Hit any key to continue...'); ClrScr; EnterUserInfo(TxtC,TxtB); ConfirmationField(TxtC,TxtB); If InfoCor = False Then Repeat Writeln; Writeln('You verified that your information is, for some reason, incorrect.'); Writeln('You are now going to re-enter your correct information. Hit any key..'); Readkey; EnterUserInfo(TxtC,TxtB); ClrScr; ConfirmationField(TxtC,TxtB); Until InfoCor = True; End.



The Variable Parameter

Parameters of procedures can be reference variables. In this case, data may flow through the variable in both ways. What I am trying to say is that you can pass data and get data through the procedure using a variable parameter. Here is a declaration of a variable parameter:

Procedure <PROCEDURE_NAME(Var Variable_Name Type);>

Here is an example of how to use a variable parameter and its purpose:

Program VAR_PARAM_EXAMPLE; Procedure Square(Index : Integer; Var Result : Integer); Begin Result := Index * Index; End; Var Res : Integer; Begin Writeln('The square of 5 is: '); Square(5, Res); Writeln(Res); End.

In the example above, the 'Result' variable parameter is used to store the result of the square of the 'Index' parameter. After the procedure Square' has been executed, the 'Res' global variable will have the result of 25 since the procedure stores it back in the variable parameter. This way, it can be used in main program to output the result.




The second type of sub-program is called a function. The only difference from the procedure is that the function return a value at the end. Note that a procedure cannot return a value. A function start and end in a similar way to that of a procedure. If more than one value is required to be returned by a module, you should make use of the variable parameter. A function can have parameters too. If you change the sub-program from procedure to a function, of the previous program, there will be no difference in the output of the program. Just make sure which one is best when you can use to implement a module. For example, if you don't need to return any values, a procedure can be preferred. However if a value should be returned after the module is executed, a function should be used instead.

Example of a program using a function is seen below:

Program Lesson7_Program4; Uses Crt; Var SizeA, sizeB : Real; YN : Char; unitS : String[2]; Function PythagorasFunc(A: Real; B: Real) : Real; {The pythagoras theorem} Begin PythagorasFunc := SQRT(A*A + B*B); {Output: Assign the procedure name to the value. If you forget to assign the function to the value, you will get a trash value from the memory} End; Begin Repeat Writeln; Write('Enter the size of side A : '); Readln(sizeA); Write('Enter the size of side B : '); Readln(sizeB); Repeat Write('metres or centimetres? Enter : [m or cm] '); Readln(unitS); Until (unitS = 'm') OR (unitS = 'cm'); Writeln(PythagorasFunc(sizeA,sizeB),' ',unitS); Writeln; Write('Repeat? '); YN := Readkey; Until (YN IN ['N','n']); End.

In the pythagoras function above, the result is returned to the function by assigning the value to the function name. This way we can use the function in the main program to store the result of the function in a variable (in this case it has been outputted directly).

Lesson 8-File Handling

File Handling


A file contains data which is saved in the hard disk. You can only view a file from the hard disk by using an operating system. A can contain text data which is used by word processors. Many text files are saved in the hard disk with the extensions: *.txt and *.doc. The file with extension of *.txt, means that it is created by the Microsoft Notepad. Whenever you use the Microsoft Notepad and save a text file, this saved file is created and written on to the hard disk. However, some programs have various formats on how to maintain the text - such as justification, font, font colour. So many files contain more data other than text data! The program itself uses various techniques to create a file in such a way that, when it is being read again it can read (using programming skills, etc..) if it is justified, its font style etc..

Before you go on with files, please make sure that you have enough hard disk space for our experiments, since I am going to demonstrate to save a file to the hard disk!! :) Only a few bytes, however..




Read from a File (file input)

Reading a file in pascal is very easy. Note that there are no reserved words in Pascal that are used to to read or write to a file. We used the 'usual words': readln() and writeln(); Here's the technique of how to read a text file (only):

Program Lesson8_Program1; Var UserFile : Text; FileName, TFile : String; Begin Writeln('Enter the file name (with its full path) of the text file:'); Readln(FileName); {A .txt file will be assigned to a text variable} Assign(UserFile, FileName + '.txt'); Reset(UserFile); {'Reset(x)' - means open the file x} Repeat Readln(UserFile,TFile); Writeln(TFile); Until Eof(UserFile); Close(UserFile); Readln; End.

It is worth to take a look at various important lines of the program. A new variable of type: 'Text' is new to you, and this should be used whenever you are going to edit a text file! The variable 'FileName' is required to link to the file indicated by the user. The 'assign' statement is used to declare 'FileName' + '.txt' to a text file, so that the file could be opened, using - 'Reset()'. To read from the first line to the very last line of the file, you should use the repeat-until loop, ending the loop with : 'Until Eof(textfile);', which means: 'Until the End Of File [eof]'.



Create and Write to a File (file output)

The following program is an example of how to create-and-write or overwrite a file:

Program Lesson8_Program2; Var FName, Txt : String[10]; UserFile : Text; Begin FName := 'Textfile'; Assign(UserFile, 'C:\'+FName+'.txt'); {assign a text file} Rewrite(UserFile); {open the file 'fname' for writing} Writeln(UserFile, 'PASCAL PROGRAMMING'); Writeln(UserFile, 'if you did not understand something,'); Writeln(UserFile, 'please send me an email to:'); Writeln(UserFile, ''); Writeln('Write some text to the file:'); Readln(Txt); Writeln(UserFile, ''); Writeln(UserFile, 'The user entered this text:'); Writeln(UserFile, Txt); Close(UserFile); End.

In the above program, I am using the 'writeln()' statement so that I write to the file I have previously assigned to. Note that, even though I am using writeln(), there is no output to the screen, it goes to the file I initialised referred to by 'UserFile'.

To check exactly what has just been written to this file, go to C:\, and see if there is a file named:

Textfile.txt. Open it and see what does it contain!! :-). If you encountered any difficulties in locating the file, then in the start menu go to:

start -> find -> files or folders => look in drive C: and enter 'textfile.txt' in the text box; double click on it.



Append text to an existing File

Writing to an existing file, means, open a file and add extra data, but not overwrite the contents file. Some beginner programmers do not actually understand how to not overwrite a file with data they would like to input. This is the common problem:

Var UFile : Text; Begin Assign(UFile, 'C:\ADDTEXT.TXT'); ReWrite(UFile); Writeln(UFile, 'How many sentences ' + + 'are present in this file?'); Close(UFile); End.

Copy the program above in your Pascal compiler. Run this program for two times or more. After you run this program several times, find the file named 'addtext.txt'. Is there more than one sentence?

A new function which works with files, can solve our problem. This function is called 'append(f)', where f is a variable of type text. This can be done by simply changing the 'Rewrite(UFile)' to 'Append(UFile)', and the file contents are not overwritten, but appended!

The above program can be changed to the following:

Var UFile : Text; Begin Assign(UFile, 'C:\ADDTEXT.TXT'); Append(UFile); Writeln(UFile, 'How many sentences, '+ +'are present in this file?'); Close(UFile); End.

Run the program two times or more to see the change...



Delete Files

In Pascal, the reserved word used to delete files from the hard this is the 'Erase(f)' where f is a variable of any data type. This means that 'f' could be both file and text variable type. Note, that the file you are about to delete is not taken in the recycle bin, but it is directly kicked off the hard disk!!

Unlike any other file functions, the Erase() function does not open the file to delete it, so you don't need to call Close(...) after Erase().

Example Program:

Var UFile : Text; { or it could be of 'file' type} Begin Assign(UFile, 'C:\ADDTEXT.TXT'); Erase (UFile); End.



The '{$I-},{$I+}' compiler directives

Compiler directives are used to adjust the compiler settings during the compilation process, so that programmers can control their program in their preferrable way. Compiler directives are declared using the symbols '{', '$' and '}'. Note that the braces are used for comments, but still, '{$something}' is taken to be a directive. Instead of 'something' the programmer should replace it by a known directive (a letter). Now, the '{$I}' is used to tell the compiler not to take into consideration I/O errors including file operations. Say, for example, if a file is trying to be opened, but it does not exist, the program does not stop from executing and halts with a runtime error, saying: 'File not found' or whatever annoying error! Make sense? So, if you apply this compiler directive before you open the file, either for writing or reading, I/O errors will not cause the program to raise a runtime error forced halt.

Now, I must teach you how to use this compiler directive by letting you know where to put it and how to cater with the error that might occur. It must be placed where you are going to open or delete a file. ie.:

{$I-} actions on file... {$I+} { enable the I/O error check again }

It is important to enable again the i/o error check, after you have disabled it, so that any unknown future errors would be automatically encountered. However, if you think that it would be better to disable i/o error checking for the entire program, you can! Just apply the directive at the beginning and that's it but it is not recommended since during the runtime of your program you will not be notfied of IO errors that might occur!! After you control a file action, you must check whether an error has occured or not by using the system function 'IOResult', which returns IO error information. This is a typical traditional exception handling. You should test for errors using the statement:

If (IOResult <> 0) Then ...

The IOResult function should be explicitly used after an IO error check so that it will automatically clear the error flag of the system otherwise, the IO error cause a 'mutation' to other IO processes resulting into a runtime error. You are not required to grasp each word perfectly from what I said. The most important thing is that you include that statement if the IO directives are to be used and everything would be fine. Now I should show you how to use it by an example:

Program Lesson8_Program3; Uses Crt; Var t : Text; s : String; Begin Assign(t, 'C:\ABC.DEF'); {$I-} { disable i/o error checking } Reset(t); {$I+} { enable again i/o error checking - important } If (IOResult <> 0) Then Begin Writeln('The file required to be opened is not found!'); Readln; End Else Begin Readln(t,s); Writeln('The first line of the file reads: ',s); Close(t); End; End.

If the required file is found the IOResult returns a 0 value, meaning no errors; ELSE if not found (IOResult returns a non-0 value) display an error message!

IMPORTANT: if the file is successfuly found, the file is opened and you should close it as shown in the program above. However, if it is not found, the common sense says that it couldn't be opened because it is not found!?! So, you should not include a 'close(..)' after it is not opened and this is done conditionally as shown in the example. Study carefully my program and run it several times with good paths and non-good ones to see well the difference and how does the compiler directive works!!

Hopefully, the compiler directive could be applied to different functions, similarly as in the program above. You can use it with 'Rewrite()', 'Append()', 'Erase()', and also 'FSearch()'. You can try as many programs as you wish and hopefully practicing the IO directive. I know, that this directive is somewhat complex and hard to be understood but undoubtedly useful! I am there waiting for your e-mails, if you think that your program does not work properly when using this directive.




Create and Remove Sub-Directories

In Pascal, there are functions with which you can either create or remove a directory from the hard disk. To create a directoy, we use the function 'CreateDir(c)' where 'c' is of type PChar. Ohh, that's sound kinky... What the heck does PChar means? Hehe, PChar is a pointer variable which holds the address of a dynamic variable of a specified type. It is sort of a pointer for characters. Before you create the directory, however, you have to check if the directory exists, else a runtime error shows up fiddling in front of your monitor!! :-) The directory is created as follows:

NewDir := FSearch('C:\Pascal Programming', GetEnv('')); If NewDir = '' Then CreateDir('C:\Pascal Programming');

From only three lines of code, we have been able to create a dir. But, before you go experimenting on your own, you should strictly read the following documented example: (I will explain in detail the 'FSearch()' function)

Program Lesson8_Program4; Uses WinDos, Dos; { note the inclusion of the 'windos.tpu' library } Var NewDir : PathStr; { for searching the dir and create a new one, if it does not exist } F : Text; Begin { search for the dir } NewDir := FSearch('C:\Pascal Programming', GetEnv('')); { create a new one, if it does not exist } If NewDir = '' Then CreateDir('C:\Pascal Programming'); Assign(F,'C:\Pascal Programming\pprogramming.txt'); {$I+} ReWrite(F); {$I-} { disable and enable back again i/o error checking } { write to text file } Writeln(F,''); {$I+} Close(F); {$I-} End.

The variable type, 'PathStr', is new to you, and this is a variable defined in the 'dos.tpu' library. So, you have to include the 'dos' library at the beginning of your program. The 'FSearch()' function is implemented also in the windos library to search in a dir list. So, it was useful in our program and any other program to search if the dir exists or not. It's not important to know exactly what does 'GetEnv()' mean, which is found in the second parameter of FSearch(). The Borland Turbo Pascal reference says that its function is to return the value of the specified function. Note that 'FSearch()' is implemented in the 'dos.tpu' library, while CreateDir()' is implemented in the 'windos.tpu' library.

To remove a directory, it is quite simple. Just add 'remove()' at the end of your program! :-) Your operating system will automatically erase the dir if it exists. It doesn't matter if you 'remove' a dir which does not exist. Hopefully, no runtime errors, will show up! The 'remove(Pch)' function is also implemented in the windos library, where 'Pch' is a variable of type PChar, again.



FileSize() - Return the value of a file in bytes

Now, for the fun stuff!! To return the size of a file, simply declare a variable of 'longint' type, and assign it to the filesize of the file. A file variable of type byte, should be assigned to the file which you would like to return its size, using 'Assign()'.

Program Lesson8_Program4; Var f : File of Byte; { file var of type byte } sz : LongInt; { var for the size } Begin Assign(f,'C:\anyfile.txt'); {$I-} Reset(f); {$I+} If (IOResult <> 0) Then Begin { file found? } Writeln('File not found.. exiting'); Readln; End Else Begin { Return the file size in Kilobytes } sz := Round(FileSize(f)/1024); Writeln('Size of the file in Kilobytes: ',sz,' Kb'); Readln; Close(f); End; End.

Lesson 9- Arrays


What are Arrays?

An array is a highly useful data structure that stores variable data having the samedata type. It is just like a small fixed number of boxes linked together one after the other storing things that are related to each other. An array is said to be astatic data structure because, once declared, its original size that is specified by the programmer will remain the same throughout the whole program and cannot be changed.

Up until now, we have used single variables only as a tool to store data. Now we will be using the array data structure and here is how it is declared:


<arrayName> : Array[n..m] of <Data Type>;

myArray : Array[1..20] of Integer;

An array data structure defines the size of the array and the data type that it will use for storing data. In the above example, the array stores up to 20 integers however I may have used 30 integers or more. This size depends on your program requirements.

Arrays are used just like ordinary variables. They are used to store typed data just like the ordinary variables. You will now learn how to assign data to arrays and read data from arrays.

In the example above, I have declared 20 integers and I should be able to access each and one of them and here is how I do it.

To assign values to a particular integer of an array, we do it like this:

myArray[5] := 10; myArray[1] := 25;

<arrayName>[index] := <relevant data>

You just take the array in subject, specify the index of the variable of the array and assign it a value relevant to the data type of the array itself.

Reading a value from an array is done as follows:

Var myVar : Integer; myArray : Array[1..5] of Integer; Begin myArray[2] := 25; myVar := myArray[2]; End.

Just like ordinary variables, arrays should be initialised, otherwise scrap data will remain stored in them. If we want to intialise 2 whole 20-sized integer and boolean arrays to 0 and false respectively, we do it like this:

Var i : Integer; myIntArray : Array[1..20] of Integer; myBoolArray : Array[1..20] of Boolean; Begin For i := 1 to 20 do Begin myIntArray[i] := 0; myBoolArray[i] := False; End; End.



Introducing User-Defined Data Types

Now that we have used various built-in data types, we have arrived at a point were we want to use our defined data types. Built-in data types are the ones we used lately, such as IntegerBoolean and String. Now we will learn how to specify our own customised data types and this is just how it is done:


<myDataType> = <particularDataType>;

The "Type" keyword is a reserved Pascal word used to define our own data types. So you start defining your own data types by using this keyword. After defining your own data types, you may start using them just like the other built-in data types as follows:


<myVar> : <myDataType>;

Now lets define a new simple data type and note how it will be used in the program below:

Type nameType = String[50]; ageType = 0..150; { age range: from 0 to 150 } Var name : nameType; age : ageType; Begin Write('Enter your name: '); Readln(name); Write('Enter your age: '); Readln(age); Writeln; Writeln('Your name:', name); Writeln('Your age :', age); Readln; End.

In the above example we defined a String[50] and a 0..150 data type. The nameType only stores strings up to 50 characters long and the ageType stores numbers only from 0 to 150.

We can define more complex user-defined data types. Here is an example of more complex user-defined data types:

Type i = 1..5; myArrayDataType = Array[1..5] of Byte; byteFile = File of Byte; { binary file } Var myArrayVar : myArrayDataType; myFile : byteFile; Begin Writeln('Please enter 5 number from (0..255): '); For i := 1 to 5 do Readln(myArrayVar[i]); Writeln('You have entered the following numbers: '); For i := 1 to 5 do Writeln('Number ',i,': ',myArrayVar[i]); Writeln('Now writing them to file...'); {store the numbers in a file} Assign(myFile, 'example.dat'); ReWrite(byteFile); Write(myFile, myArrayVar[i]); Close(myFile); Writeln('Done, you may exit..'); Readln; End.

In the above example I showed you how to incorporate arrays as user-defined data types. Note that you may use user-defined data types more than once.



2 Dimensional and Multi-Dimensional Arrays

2 Dimensional arrays and multi-dimensional are arrays which store variables in a second or nth dimension having n*m storage locations. Mutli dimensional arrays including the 2 dimensional array, are declared by using multiple square brackets placed near each other or using commas with one sqaure brackets as an alternative. Here is how multi-dimensional are declared:

my2DArray : Array[i..j][k..l] of <DataType>; myMultiDimArray : Array[m..n][o..p][q..r][s..t]... of <DataType>;

Let us have the 2 dimensional array defined first. Think of a grid where each box is located by using horizontal and vertical coordinates just in the example below:

1 2 3 4 5
3     3,4  
5   5,3    


Let us declare an array having 3 by 5 dimensions, assign a value to a particular variable in the array and illustrate this on a grid just like the one above:


Var my2DArray : Array[1..3][1..5] of Byte; Begin my2DArray[2][4] := 10; End.

Having the vertical axis as the 1st dimension and the horizontal one as the 2nd dimension, the above example is illustrated as follows:

1 2 3 4 5



Multi-dimensional arrays are rare and are not important. The single and 2D dimensional arrays are the 2 most frequent dimensions.

The following example is a bit more complex example than the previous examples and it also uses a 2 dimensional array to illustrate their use.

Uses Crt; Type myRange = 1..5; arrayIntType = Array[myRange] of Integer; myFileType = File of arrayIntType; Var i : myRange; myFile : myFileType; { the next array is 2 dimensional } arrayInt : Array[1..2] of arrayIntType; Begin Clrscr; Randomize; For i := 1 to 5 do Begin arrayInt[1][i] := Random(1000); Writeln('rand num: ',arrayInt[1][i]); End; Assign(myFile, 'test.dat'); ReWrite(myFile); Write(myFile, arrayInt[1]); Close(myFile); ReSet(myFile); Read(myFile, arrayInt[2]); Close(myFile); For i := 1 to 5 do Writeln(i,': ', arrayInt[2][i]); Readln; End.

This concludes the arrays lesson. In the next lesson we will learn about Record data structures, their uses and we will also learn how to use binary files used record data structures.

Lesson 10-Strings & String Manipulation

Strings & String Manipulation

Introduction to Strings

Maybe you already know what is a Stringvariable from previous program examples that you have tried, but you don't know what operations and what functions one can apply to them and how can they be manipulated in order to obtain another form of string.

In this lesson we will cover some important functions that the Pascal programming language has got to offer in order to cater for string operations far more easier to use than you think.

Let's jump into the strings staff straight away. In order to understand strings, one has to keep in mind that a string is made up of an array of characters. The string data type is an in-built data type that is an array of 256 characters (Type String = Packed Array[0..255] of Char). When stored in memory, the processor should know where the string starts and where it finishes. In order to know where the string finishes, in Pascal, the 0th element of a string is defined as the length of the string. So, if you try to access character 0 of a string, the number of characters stored in that array is returned, thus letting the processor to know where the string finishes.

The following example shows some simple string operations.

Var myString : String; Begin myString := 'Hey! How are you?'; Writeln('The length of the string is ', byte(myString[0])); Write(myString[byte(myString[0])]); Write(' is the last character.'); End.

Note that in the previous program I have used an automatic data-type conversion, normally referred to as data type-casting. When type-casting from one data type to another, all that is happening is simply a conversion from one data type to another based on the data type in subject and the wrapping data type to which the old data type is being converted. In our case, the array variable myString has a special 0th element storing the number of characters in that array in string format. This value is an ascii value, so trying to display it without converting it into a number, the alternative ascii character is displayed. So you have to change the character value to an ordinary number by wrapping the variable by another data type, in our case a byte data type (why use integer? - its all waste of memory and memory consumption).

Note that myString[myString[0]] without having data-type casting around myString[0] will lead to a compiler error because myString[0] is a character and not an integer.

Note that to retrieve the length of a string (ie. the number of characters in a string) there is no need to use the method I showed to you because its too complicated and unfriendly. Instead, there is the simpler function, length() which will return the number of characters of the string in subject. Eg. numOfChars := length(myString);



Useful String Functions

There are some basic Pascal functions that has to do with string operations and so there is no need to write them yourself, and they are of course quite useful. I will explain all the string functions by describing what they do and a simple example of each.

Function Pos(SubString : String; S : String) : Byte;


This function will search for the string SubString within the string S. If the sub-string is not found, then the function would return 0. If on the other hand the sub-string is found, then the index integer value of the first character of the main string that matches the character of the sub-string is returned.

Var S : String; Begin S := 'Hey there! How are you?'; Write('The word "How" is found at char index '); Writeln(Pos('How', S)); If Pos('Why', S) <= 0 Then Writeln('"Why" is not found.'); End.


Function Copy(S : String; Index : Integer; Count : Integer) : String;


This function will copy some characters from string S starting from character index Index and copies as much as Count. The copied string is then returned.

Var S : String; Begin S := 'Hey there! How are you?'; S := Copy(S, 5, 6); { 'there!' } Write(S); End.


Procedure Delete(var S : String; Index : Integer; Count : Integer );


Deletes a specified number of characters from the string S. The starting position of deletion is from character index IndexThe number of characters that will be deleted is specified through Count. The new string is passed back through the variable parameter S.

Var S : String; Begin S := 'Hey Max! How are you?'; Delete(S, 4, 4); { 'Hey! How are you?' } Write(S); End.


Procedure Insert(Source : Stringvar S : String; Index : Integer);


This function will insert a string of any length into a source string starting from an index character. The string S will be inserted into string Source starting from the index character Index. No characters will be deleted from the front except if the resulting string is longer than 255 characters. In this case, the front characters will be truncated as to fit a 255-character string.

Var S : String; Begin S := 'Hey! How are you?'; Insert(S, ' Max', 4); Write(S); { 'Hey Max! How are you?' } End.


Function Concat(s1 [, s2,] : String) : String;


Concatenates 2 or more strings depending how long is the argument expression. Try to make sure not to exceed the limit of 255 characters when concatening strings as it will result in truncation. This function can also be obtained by using the plus (+) operator between strings that need to be concatenated.

Var S1, S2 : String; Begin S1 := 'Hey!' S2 := ' How are you?'; Write(Concat(S1, S2)); { 'Hey! How are you?' } End.

is the same

Var S1, S2 : String; Begin S1 := 'Hey!' S2 := ' How are you?'; Write(S1 + S2); { 'Hey! How are you?' } End.


Function UpCase(C : Char) : Char;


Converts the character C to uppercase and returned. If the character is already in uppercase form or the character is not within the range of the lower case alphabet, then it is left as is.

Var S : String; i : Integer; Begin S := 'Hey! How are you?'; For i := 1 to length(S) do S[i] := UpCase(S[i]); Write(S); { 'HEY! HOW ARE YOU?' } End.


Procedure Str(Val : Integer / LongInt / Realvar S : String);


Converts an integer or a decimal value to a string. The value parameter Val is converted into a string and passed through the variable paramter S.

Var S : String; i : Real; Begin i := -0.563; Str(i, S); Write(S); End.


Procedure Val(S : Stringvar Val; Code : Integer);


Converts a string to its corresponding numeric value. The string paramater S is converted into a numeric value and passed back through the variable paramter Val. If the string to be converted is not a correct numeric value, an error occurs and is returned via Code. If the conversion is correct then Code is 0.

Var S : String; error : Integer; R : Real; Begin S := '-0.563'; Val(S, R, error); If error > 0 Then Write('Error in conversion.') Else Write(R); End.