0% found this document useful (0 votes)
147 views

PASCAL Tutorial

Syntax refers to the structure and rules for constructing statements in a programming language. In this context, the syntax shown provides the proper form or format for using the "read" function in Pascal to read input from the user. It indicates that "read" is a function that takes a single variable as a parameter inside parentheses.

Uploaded by

mickaylia green
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

PASCAL Tutorial

Syntax refers to the structure and rules for constructing statements in a programming language. In this context, the syntax shown provides the proper form or format for using the "read" function in Pascal to read input from the user. It indicates that "read" is a function that takes a single variable as a parameter inside parentheses.

Uploaded by

mickaylia green
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 46

PASCAL

A Tutorial
You are visitor number
[an error occurred while processing this directive]

This page is dedicated to teaching you to program with Borland Turbo Pascal, easily and
quickly. We assume no prior programming experience but at least a basic knowledge of
algebra. We provide you with all the software you will need, so if you want to learn how
to program then you have come to the right place.

Why Learn Pascal?

We thought long and hard about this question. Pascal is a basic and easy to learn
language. Using it teaches you important programming principles which can be applied
to most other programming languages. It will also teach you skills to think through tasks
and also other skills which can be applied to many areas, including some outside
computing, such as task management etc. But the most important reason to learn Pascal is
because it's fun and interesting. (We hope)

What would I use Pascal for?

You would use Pascal for the same things you would use any programming language.
This is things such as: making games or the like, making databases, or performing
repetitive calculations.

Downloading Pascal 6

To begin with you will need to download Pascal. This is Pascal 6 which is Freeware.
(Pascal 7 is not however, and so we cannot give it to you). Once you have downloaded it
you will need to unzip it to the appropriate directory. You can now run TURBO.EXE

 Download Turbo Pascal 6 (1.2 MB)

You will also need to know how to use the Pascal programming environment:
 How to Use Pascal

Bob the Sausage


You may have noticed Bob at the top of the screen. He will appear occasionally
throughout the tutorials, so watch out for him.

Right, with no further ado, let's get started:

 First Lesson: Program Structure

Other lessons are:


 Variables
 Basic IO
 Basic Maths
 Procedures
 Loops
 Flow Control
 Arrays
 Records
 Objects
 Text Management
 Files
 Exercises

Pascal Forum

Go to the message forum on our page and post your question. With luck, someone else
who visits the page may have the answer you looking for. If they don't then one of us will
gladly answer your question for you in our Message Forum

You could also try joining our mailing list below to share your knowledge of pascal with
everybody.

How to Use Pascal


Opening and Saving files in Pascal

Opening and closing your files in pascal follows the usual method of:
* File Menu
* Open (or Save)
* Select the File (or type in the file name)
* Click Open (or Save)

This is exactly the same as you would do in any word processing program.
Alternatively you can press F2 to save your program.
It is a good idea to save your work regularly.

Exiting Pascal

To exit Pascal:

* File Menu
* Exit

Alternatively you can press Alt-x to exit.

Compiling and Running Your Program

It is VERY important that you know how to do this so make sure you remember it.

COMPILING:

When you compile your program, Pascal checks it for errors. If there are any errors
Pascal tells you. If you don't understand what the error means then look up the error in
the help.

To compile your program press F9, or you can select Compile from the Compile menu.

RUNNING YOUR PROGRAM:

To run your program press Ctrl+F9, or select Run from the Compile menu. This
command compiles your program. Then if the compilation was successful your program
will be run.

Back to Main Page

Program Structure
The Pascal programming language has several important words in it. These are called
keywords. In example programs keywords will be displayed in bold. This lesson will
teach you some basic keywords and structure of your pascal programs.

It is optional to begin your program with the keyword 'Program', followed by your
program name. This keyword is useful only to you. It lets you identify what the program
does quickly and easily.
After this comes the keyword 'var'. This is followed by any variables you wish to use in
your program. If you are not using any variables then you do not need the 'var' keyword.
(More on variables in the next lesson.) Pascal will report an error if you try to use the 'var'
keyword without any variables.

After this comes the keyword 'begin'. This indicates the beginning of the main part of
your program. After this comes your program code. The end of the program is indicated
by the keyword 'end.'. Note the full stop after the word 'end'.

It is a good idea to comment your code so you can understand what it is doing if you
look at it later. It is also important so that other people can understand it also.

In pascal you can comment your code in two diffent ways. Either { to start the comment
and } to end the comment or (* to start the comment and *) to end the comment.

eg.
Program DoNothing;     {This line is optional}

var

begin

    (*Note that comments can carry over


   &nbspmultiple
   &nbsplines*)
end.

This program does absolutely and utterly nothing.

In fact this program will create an error on the begin command. It will say 'variable
identifier expected'. This is because the var keyword should only be included if you have
variables to declare.

There are also several other keywords, which are optional and must come before 'var'.
Some of these are 'type', 'const' and 'uses'.

'Type' declares any variable structures - explained later.

'Const' declares any constant values to use throughout your program. These are anything
which is always the same, such as the number of days in the week. Alternatively if you
use a set value throughout your program, it is a good idea to make this a constant value so
that it can easily be changed if you later decide to do so.

The 'Uses' keyword allows your program to use extra commands. These extra commands
are stored together in what is called a module or library. These modules have names such
as CRT, or GRAPH. Each module contains several extra commands. These commands
will be related in some way. Eg. GRAPH contains extra commands to do with graphics.
CRT contains many general commands. (Even though CRT stands for Cathode Ray Tube
- ie. the screen)

eg.

uses crt, graph;    {This means pascal allows you to uses the extra commands in the crt
and graph modules}

const
   &nbspInchesInFoot = 12;     {These are some constants you might use}
   &nbspDaysInWeek = 7;
   &nbspe = 2.1718281828;

type
    {Type definitions go here - don't worry about these yet}

var      (*variables are declared here*)

begin

end.

Basic Variables in
Pascal
A variable is an expression which represents a value. A variable is named such because it
can have any value - its value is variable.

There are many different types of variables. For the moment we will say that a variable
can store a word or a number.

eg. Number is a variable which stores a number.


Number is assigned a value of 23456.
Therefore later in the program saying:
5 * Number + 6 will be the same as saying:
5 * 23456 + 6, since Number is equal to 23456.
In Pascal, assigning variables is done by:
Number := 23456;
This will make the variable, 'Number', equal to 23456.

There are several different types of number variables:

*Integer  &nbsp-Any Integer (Whole number) from -2^15 to 2^15 - 1


*LongInt  &nbsp-Any Integer (Whole number) from -2^31 to 2^31 - 1
*Real     &nbsp-Any Real number (Number which can have decimal points)
            from 2.9 * 10^-39 to 1.7 * 10^38
            (It is accurate to 11 significant figures)

Plus there are a few others, (which we won't mention yet). It isn't necessary to know all
the details.

All you really need to know is that Integer variables store Integers. LongInt variable can
hold much larger Integers, and Real variables can hold any number.

There are two main types of variable which hold letters:

*Char     &nbsp-Any single character


*String    -A word or phrase up to a set length

A string is a series of characters. The default maximum length of a string in Pascal is 255
characters. However if you don't want your string to be that big you should set it smaller.
You do this by putting the length of the string in square brackets after the variable.

Pascal also has variable of type 'Boolean'. These can have the values of either true or
false.

In Pascal, variables are declared at the beginning of the program or procedure. They must
be declared after the keyword 'var'. Variables are declared in two parts. First is then name
of the variable - how it will be referred to in your program. This is followed by a colon.
Then is the type of variable, eg Integer, Byte. This is followed by a semicolon.

eg.
var

myInt : Integer;
aRealNumber : Real;
thisIsAString : String[30];
booleanVariable : Boolean;
This will create the folling variables:
myInt - This will be an Integer.
aRealNumber - This is a Real number.
thisIsAString - This is a sequence of letters with a maximum length of 30 characters.
booleanVariable - This contains a true or false value.

It is interesting to note that 'string' is a keyword. This is because it is different to other


variable types, as it contains a sequence or 'Array' of characters. We will study Arrays in
depth in a latter lesson.

Make sure you understand all of the above before proceeding further.

BASIC INPUT AND


OUTPUT

As you probably know, nearly all computer programs take input from the user.
If you don't know how to take input then you won't get very far in the programming
world.

Pascal has two major functions for taking input from the user. These are:-

read
Syntax:            What does syntax mean?
read (variable);
Explanation:
This reads all the characters typed, until the user presses enter, into the variable.
If the variable is of type integer, and the user types in string characters, then
an error will occur. If the variable is a string of defined length then read will only
take the first X characters from the line and put them into the string, where X is the size
of the string. Read does not move the cursor to the next line after input.

readln
Syntax:
readln (variable);

Explanation:
This is exactly the same as read except for the fact that it moves the cursor to the next
line after the user presses enter.

The output commands in pascal are very similar in syntax to the input commands.

write
Syntax:
write (variable);
write (variable:f)
write (real variable:f:d);
f=field width d=number of decimal places

Explanation:
The write command displays a string of characters on the screen. When a field width is
included, the writing
is right aligned within the field width e.g. write ('Hello':10); will produce the
following output...

00000Hello

(0=space)

Notice that 'Hello' is right-aligned within the field of ten characters , the remaining spaces
coming before 'Hello'

When writing real numbers, you must specify the field width and number of decimal
places displayed, otherwise pascal will write it to the screen in standard form (this is not
good). A field width of zero will just write the real as if you had not specified a field
width.

If you want to write a combination of things, separate these by a comma. e.g.


write ('Hello ' , name , ', you weigh ' , weight:0:2 , ' kg.');
The above will write something like this... Hello Joe Bob, you weigh 76.54 kg.

Note: The write command does not move the cursor to the next line after execution.

writeln
Syntax:
writeln (variable);
writeln (variable:f)
writeln (real variable:f:d);
f=field width d=number of decimal places

Explanation:
The writeln command is exactly the same as the write command except for the fact that it
moves the cursor
to the next line after execution.

NOTE: All of the above commands are also used when reading and writing to files.
This will be covered later.

EXAMPLE PROGRAM

Program example;
{This is an example program for input and output}

uses Crt;
var
name : string[30];
begin
clrscr;          {This clears the screen}
write ('What is your name? '); {Writes the question without moveing the cursor to
the next line}
readln (name); {take input from user}
writeln ('Hello ', name); {Output Hello joebob}
while not keypressed do; {waits for a key to be pressed}
end.

Mathematical
Operations
Pascal can do many mathematical operations. They are all relatively simple and easy to
remember.
The first thing to remember is that pascal uses := not = to assign a value to a variable.
e.g. int := 3;

Basic mathematical operators


Addition ...................... x := y + z;
Subtraction ................... x := y - z;
Multiplication ................ x := y * z;
Division ...................... x := y / z;
Integer division .............. x := y div z;
Modulo arithmetic ............. x := y mod z;

Integer Division: One integer is divided by another and the integer part of the result is
returned.

Modulo Arithmetic (Remainder Arithmetic): x := y mod z;


The above finds the remainder of y/z and puts it into x.

These mathematical operations are pretty self explanatory.

Mathematical functions
SQR

Syntax:

SQR(Real Variable)

Explanation:
SQR returns the square of the real variable that is passed to it, pretty simple really.

Example:
x := SQR(y);
This finds the square of y and puts the result in x.

SQRT

Syntax:

SQRT(Real Variable)
Explanation:
SQRT returns the square root of the real variable that is passed to it, pretty simple really.

Example:
x := SQRT(y);
This finds the square root of y and puts the result in x.

SIN

Syntax:

SIN(Real variable)

Explantation:
SIN returns the sin of the number that is passed to it. Unfortunately this is in
radians(stupid radians).
2*pi radians is equal to 360 degrees, so to convert from degrees to radians it is
degrees/180 * pi,
and from radians to degrees it is radians/pi * 180. It is a bit of a hassle but nevermind.

Example:
x := SIN(y);
This finds the sin of y(radians) and puts the value in x.
COS

Syntax:

COS(Real variable)

Explantation:
COS returns the cos of the number that is passed to it. This is also in radians. If you want
to know how to convert
radians into degrees and vice-versa then read the explanation of SIN.

Example:
x := COS(y);
This finds the cos of y(radians) and puts the value in x.

ARCTAN

Syntax:

ARCTAN(Real variable)

Explantation:
ARCTAN returns the inverse tanget of the number that is passed to it.
It returns the angle in radians (gasp).

Example:
x := ARCTAN(y);
This finds the inverse tangent, in radians, of y and puts the value in x.

Finding TANGENT

To find tanget just divide sin(Y) by cos(Y).


e.g x := sin(y)/cos(y); finds the tangent of y and puts it in x (remember radians).

Finding INVERSE SIN/COS

To find INVERSE SIN or INVERSE COS do the following...


INVERSE SIN = ARCTAN(y/sqrt(1-sqr(y)))
INVERSE COS = ARCTAN(sqrt(1-sqr(x))/x)
So x := arctan(y/sqrt(1-sqr(y))); finds the inverse sin of y and puts it in x.
So x := arctan(sqrt(1-sqr(x))/x); finds the inverse cos of y and puts it in x.

Procedures and
Functions
Sometimes when you are programming you might need to use the same piece of code
over and over again. &nbspIt would make your program messy if you did this, so code
that you want to use multiple times is put in a procedure or a function.

The difference between a function and a procedure is that a function returns a value
whereas a procedure does not. &nbspSo if your program has multiple Yes/No questions
then you might want to make a function which returns Yes or No to any question.

Procedures and Functions both take parameters. These are values that the procedure is
passed when it is called. &nbspAn example of this would be...

... drawBob (x,y); ...

This would call the procedure drawBob. It passes it the values x and y which the
procedure will use as Bob's coordinates. &nbspThe drawBob procedure would look
something like this...

procedure drawBob (x,y : integer); begin &ltCode here> end.

Somewhere in the code it would use x and y. &nbspNotice that x and y are declared like
variables except for the fact that they are in the procedure's header. &nbspIf you wanted
different types of parameters, eg. integers and strings, then you must separate them by
semi-colons like this...

procedure doSomething (x,y : integer; name : string);


var
&ltvariables used in the procedure>
begin
&ltCode here>
end.

There might be a situation where you want the procedure to modify the values passed to
it. Normally if you did this in the procedures it modifies the parameters but it does not
modify the variables that the parameter's values were given from. Anyway if you want to
do this you need to put var in front of the parameters. So if you wanted to do something
which changed x and y you would make a procedure like so...

procedure modifyXY (var x,y:integer);


begin
&ltModification of x and y>
end.

So by now you should know how to use a procedure. Next we will talk about Functions.

A function is like a procedure except it returns a value. &nbspYou could also think of a


function as a dynamic variable, ie it gives itself a value when you have a reference to it.
An example function is shown below which returns the day name from a number between
one and seven. The numbers represent the days in the week of course.

function dayName (dayNumber : integer): String;


begin

case dayNumber of
1 : dayName := 'Monday';
2 : dayName := 'Tuesday';
3 : dayName := 'Wednesday';
4 : dayName := 'Thursday';
5 : dayName := 'Friday';
6 : dayName := 'Saturday';
7 : dayName := 'Sunday';
end;
end.

Notice dayName assigns itself a value. The type of value that is to be assigned to it is
declared in the Function header after the parameters by going, ': &ltvariable type>' which
is in this case, string.

You should know enough about procedures and functions now so this is where this lesson
ends.

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

While loops take the form :


while &ltcondition> do
begin
  statement block
end;
These are useful for things like waiting until the user presses a key or waiting until a
number entered by the user is valid.

For instance you might say :


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

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

eg:  while not keypressed do;

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

The 'For' Loop


This loop takes the form:
for variable := value1 [to|downto] value2 do
begin
   statement block
end;
For loops are more useful for iterating through an array. For instance you might want to
add 1 to each integer in an array...
var
  &nbspi : Integer; {This will be the counter for the loop}
  &nbspmyArray : array[1..30] of Integer; {See arrays for this}
begin
   for i := 1 to 30 do
   &nbspmyArray[i] := myArray[i] + 1;
end.
This does goes through each item in the array 'MyArray' and adds one to the current
value in it.

Repeat

The repeat loop is very similar to the while loop except the condition is at the end, and if
you want to execute multiple lines, then you don't need to put begin .. end keywords
around the multiple lines. For instance, this loop using while...
i := 1;
while i <= 6 do
begin
writeln(i);
i := i + 1;
end;

Would be like this with a repeat loop...


i := 1;
repeat
begin
writeln(i);
i := i + 1;
until i > 6;

Notice how the condition has changed slightly. For the while loop, it would do the loop
while the condition is true, whereas the repeat loop does it until the condition is true. (Or
while the condition is false).
Flow Control
Flow control is basically changing what your program does depending on the
circumstances. In pascal there is the if statement which is used like so:

if &ltcondition> then
   statement block
else if &ltcondition> then
  &nbsp.
  &nbsp.
  &nbsp.
else
   statement block

The condition takes the form:

[boolean expression (AND|OR) [NOT] boolean expression ...]

and this can go on for a long time. For instance you could have a condition:

if (i = 1) and (j <= 3) or not (k <> 0) then


   statement block

Note : (not k <> 0) is the same as (k = 0).


Now here is an example program:

program security;

uses crt;
var
  &nbspinput : String;
begin
   clrscr;
  &nbspwriteln('Enter the password');
  &nbspreadln(input);
   if (input = 'Pascal') then
     &nbspwriteln('Pascal is easy!')
       {Note no semicolon for one line}
   else if (input = 'Basic') then
   begin
     &nbspwriteln('Basic is not');
     &nbspwriteln('very hard!');
   end
   else
     &nbspwriteln('Wrong password!');
end.
This first prompts the user to enter a password and then reads that into intput. First it
checks to see if input is 'Pascal'. Note that this is case sensitive. If it is 'Pascal' then it
writes 'Pascal is easy!' and goes to the end of the if statement (which happens to be the
end of the program) otherwise it checks the next condition. Is it 'Basic'? if it is then write
'Basic is not very hard!' (over two lines).If it is not then try the next condition. The next
condition is ELSE. The code in the ELSE part of the if statement is executed if none of
the other conditions in the if statement are met.

Another flow control command, which is actually considered bad practice to use, but is
quite useful in some situations is goto. To use this declare a label in the label section and
use it in your code. Then just say : goto label;

eg:

label label1;

begin
  &nbsp.
  &nbsp.
  &nbsp.
  &nbsplabel1:
   {Note the colon!}
  &nbsp.
  &nbsp.
  &nbsp.
   goto label1;
   {Note no colon}
  &nbsp.
  &nbsp.
  &nbsp.
end.

Easy!

You might have noticed that sometimes the if statement may get a little cumbersome to
use. ie:
if i = 0 then
...
else if i = 1 then
...
else if i = 2 then
And so on. This is really cumbersome and annoying (you have to type the same thing
over and over). So what you want to use is the case statement. The above example would
be done like so:
case i of
0:...
1:...
2:...
3:...
4:...
5:...
6:...
end;
Very handy. If you want to have multiple lines of code for one of the options, then you
must put the multiple lines between begin and end. If you try to use the case statement
with a String type (or any type that isn't a char or integer) then Pascal will give you an
error. You can only use ordinal types with the case statment.

Another useful set of commands are the 'EXIT' commands. These are:

Halt
This does the simple task of ending your program.

Exit
This command exits from the current procedure/function.

Break
This command exits from the current loop.

Arrays
Arrays are an important part of Pascal. You can think of them like a catalogue of
information. Arrays are declared under the type section. They are a collection of a
number of variables, arranged in the form of a table.

type

integerArray = array[1..30] of integer;


integerTable = array[1..25,1..25] of integer;
stringArray = array[1..100] of string[15];
.....

This is an example of declaring an array in the type block. The array called 'integerArray'
is like a list of integers, if seen on paper it might look like this...
1.______20
2.______145
3.______39
4.______2708
5.______25
6.______260
-
-
-
30._____300

The array called integerTable can be represented by a table. It is a two dimensional array.
You can have three,four or even five dimensions in an array if you want.

Accessing Arrays

To access an entry of an array during the program you must


go...arrayname[entrynumber]
or to access a multi-dimensional array you go...arrayname[x,y,z] (3d array)

OK HERE COMES AN EXAMPLE PROGRAM

Program classTest;
{An example program demostration arrays}
{Takes scores from a class test and tells people if they passed or not}

uses Crt;

type

testScores = array[1..10] of integer;

var

i : integer;
marks : testScores;
passOrFail : string[6];

begin

clrscr;
for i := 1 to 10 do
begin     write ('Please enter test score number ',i,': ');
    readln(marks[i]);
end;
for i := 1 to 10 do
begin
    if (marks[i] < 50) then
      passOrFail := 'Failed';
    else
      passOrFail := 'Passed';
    writeln ('Student no.',i,' ',passOrFail);
end;

while not keypressed do;

end.

Arrays can also be declared in the variables section without making a type. However it is
better to use a type if you plan to use the same type of array in multiple places. So this
code in the last program...

type

testScores = array[1..10] of integer;

var

marks : testScores;

Can also be written like this:

var

marks : array[1..10] of integer;

This would do exactly the same thing, but does not declare a type of 'testScores'.

Records
You may find that sometimes there are a lot of variables that are related to each other in
some way. For instance you might find that you have a door and know its height, width
etc. and want to keep them all together.

This sounds like a job for : records

Records are just a way of defining your own type. It is done like this:
type
  &nbspdoorType = record
     &nbspwidth : Integer;
     &nbspheight : Integer;
     &nbspcolor : String[10];
   end;
Now when you want to use doorType in your program you would do
this:
var
  &nbspaDoor : doorType;
begin
with aDoor do
begin
  &nbspwidth := 30;
  &nbspheight := 50;
  &nbspcolor := 'Blue';
end;
end.
It's that easy! You may notice I have used the with statement. What this means is that
you don't have to prefix each of the fields with the variable. So you can see that it can
save you quite a bit of work.

So here's my sample program for finding the area of a door.

program doorFind;
{Find the area of a door}

uses crt;

type
  &nbspdoorType = record
     &nbspwidth : Integer;
     &nbspheight : Integer;
   end;
var
  &nbspdoor : doorType;
begin
  &nbspclrscr;
  &nbspwriteln('Enter the door height');
  &nbspreadln(door.height);
  &nbspwriteln('Enter the door width');
  &nbspreadln(door.width);
  &nbspwriteln('The door area is ', door.width*door.height);
  &nbspreadln;
end.

Previous Lesson (Arrays)     Main Menu     Next Lesson (


Objects

C++, Java and JADE are all object oriented developement languages. This means that
everything is an object which has properties and 'Methods' which are actions which the
object performs.

"So what exactly is an object in Pascal?" you ask.


Well, an object in pascal is like a record with the addition of methods (procedures) which
belong to that object.

An object declaration would look something like this...

type

...
thing = Object
property : type;
...
procedure nameofproc;
function nameofFunc (parameters);
end;
...
NOTE: You do not need empty parameter brackets if your procedure has no parameters.

In the body of the program your procedures/functions etc. will be called


'thing.nameofproc'. Now within the procedure you can reference the object by going
'self'. Ok here is an example procedure of an object which adds one to the objects
number property.

...
procedure thing.incNumber;

begin
self.number := self.number + 1;
end;
...
WOW! what an amazing procedure! So all of the variables of type 'thing' will have that
method at their diposal. You call the method by going [variable name
here].incNumber or whatever the procedure happens to be called.

There are also special kinds of procedures called constructors and


destructors. Constructors are supposed to happen when the object is
created and destructors when it is deleted. But since pascal treats
objects like variables these must be called on like a normal procedure.
I don't see any particular need to use them, except that they may
increase readability of your code.

Text Effects and


Management
Sometimes people want to present their programs in a more entertaining way. There are
some things in the Crt unit that can spice up your program and make it neater.
Remember to use the Crt unit in your programs you put  uses Crt; at the start of your
program.

Colouring your text makes the program more attractive and pleasing to the eye. You will
also be able to put borders around your text, and make headings clearer.

TextColor
The way that that this works is shown below...
Textcolor (int);
Where int is an integer between 0 and 16. Pretty simple really. Here is a list of the
different colors represented by int.

0 - Black
1 - Dark Blue
2 - Dark Green
3 - Dark Cyan
4 - Dark Red
5 - Purple
6 - Brown
7 - Light Grey
8 - Dark Grey
9 - Light Blue
10 - Light Green
11 - Cyan
12 - Light Red
13 - Pink
14 - Yellow
15 - White

A text effect that you might want to have in your program might be highlighting behind
the text. This is done with a nifty little procedure called textBackground. Remember
though, that when you use this to change the text background colour and clear the screen,
it will clear it using that background colour. eg If you change it to blue and clear the
screen, the whole screen will be blue. So when you clear the screen be sure to change the
background color back to black (unless you want the screen to go blue)!

textBackground
textBackground (int)
int is a number between 0 and 7.

Another thing that you might want to do with your program is have a menu at the center
of the screen. This means that a procedure to move the cursor to a certain point on the
screen would be quite useful. Well fortunately there is such a procedure. This procedure
is known as gotoXY.

gotoXY
gotoXY (x,y);

A common text screen has width 80 and height 25, so make sure you don't place the
cursor off the screen. Doing this may yield unpredictable results. After you have moved
the cursor to a place the next write or writeln instruction will start from there. If you do a
writeln the cursor will move down a line but will not relocate itself to the same x co-
ordinate as the last gotoXY.

Files
How to declare a file
The first thing you need to know about files is how to declare them in pascal. A file is
declared similarly to any other variable like so...

var
    < file variable > : file of < type >
...
The type in the declaration will by any of the predefined types or one of your types that
you have defined in the type section. The most common type to use is a record which you
have declared. This means that the file will store records of that type. e.g. You could have
a file containing entries of type person which would have attributes like name, address,
phone etc..

Assign
This is where you give the file variable that you have declared an associated file name. It
works like so:--
assign (&ltfile variable>,&ltfile name>);.
Now your file variable points to a real file on the drive. This is where all the information
will be written to. Now you must open your file. Two ways of opening a file are
explained below.

Rewrite
If the file name you have assigned to your file variable does not actually exist on disk
then Rewrite will create it for you. What rewrite does, is clear the file so you can write to
it. NOTE: You are not able to read from the file when using rewrite. Rewrite is used like
this:--
rewrite (&ltfile variable>);
Easy! Now you can write to the file.

Reset
This is a mode where you can both read and write to the file. This is the main mode that
you should use in your programs. Sometimes a trick if you want to create a file and have
it open for reading and writing is to create the file with rewrite and then use reset on the
file. Reset works like so:--
reset (&ltfile variable>);

Close
The close command closes a file. (as if you hadn't guessed). You need to do this at the
end of your program because it saves the changes to the file. To close a file you write :--
close (&ltfile variable>);

Writing records to a file


Writing records to a file is VERY easy. For the examples coming up we will be using the
following record type.

type

personType = record
   name : string[30];
   address : string[60];
   phone : string[7];
end;
Now lets say that you have taken input from the user and have all of the values of a
person variable. Now you want to write it to the file right? To do this you use the write
statement. You should notice that this is the same command that is used for writing to the
screen. Well, writing to a file is not much different. All you need to do is the following...
write (&ltfile variable>,person);
You can write as many records to the file as you like now :)

Reading records from a file


To read records from a file you need to use the read statement. This is how you do it:--
read (&ltfile variable>,person);
This reads from the file into your record. When you next execute this statement you will
read the next record from the file into your record variable. This is because once you
have done a read statement the file pointer is moved along to the next record in the file
for your convenience.      :)

Seek
The seek command is to go to a certain record in the file. The file starts at 0 so to be at
the first record you need to go
seek (&ltfile variable>,0).
To be past the last record at a place where you can add records to the end of the file you
will need to go...
seek (&ltfile variable>,filesize(&ltfile variable>));
In the above example filesize returns the number of records in the file. But since the
records are number from zero up, the seek command goes to the next record after the last
record entered, ie the end of the file.

Truncate
The truncate command deletes all the records in the file that lie after the current file
position. So to delete the last record from the file you will have to go...
seek (&ltfile variable>,filesize(&ltfile variable>)-1);
truncate (&ltfile variable>);

Deleting a record from a file


The simplest way to do this is to go to the last record in the file, read that record into a
variable, then go to the record you want to delete and over-write this with the variable
that contains the last record's information. Once you have done this you go back to the
last record and use truncate to remove
it from the end. Now you have deleted
a file. The example program below
contains a delete procedure if you want
to see this in code.

program Example;

uses Crt;
type

personType = record
name : string[30];
address : string[60];
phone : string[7];
end;

var
personFile : file of person;

procedure Openfile;
begin

assign (personFile,'person.dat');
reset (personFile); {This assumes the file already exists}
end;

procedure writeToFile;
var     person : personType;
begin

with person do
begin
    write ('NAME: '); readln(name);
    write ('ADDRESS: '); readln(address);
    write ('PHONE: '); readln (phone);
end;

write (personFile,person);

end;

procedure readFromFile;
var
    person : personType;
begin

while not eof(personFile) do


begin
    clrscr;     read (personFile,person);
    with person do
    begin
        writeln ('NAME: ',name);
        writeln ('ADDRESS: ',address);
        writeln ('PHONE: ',phone);
    end;
    readKey;     {waits for a key to be pressed}
end;
end;

procedure deleteRecord;
var
    i : integer;
    person : personType;
begin

write ('What record number would you like to delete? ');


readln (i);
seek (personFile,i);
if eof(personFile) then exit;
{The above line checks if 'i' is bigger than or equal to the file size}
{After all, you can't delete a record that doesn't exist!}

seek (personFile,fileSize(personFile)-1);
read (personFile,person);
seek (personFile,i);
write (personFile,person);
seek (personFile,fileSize(personFile)-1);
truncate (personFile);

end;

begin
    &ltMain program code here>
    close(personFile);

end.

An Exercise
It's time for you to have a go at making your own program!

The program needs firstly to clear the screen. Then it will need to ask the user to enter an
Integer. Once the user has entered a number the program will need to tell the user which
number they have entered. Once the user presses enter again then the program will end.

Sounds hard? Try it!


Example Answer
Here is our example answer. Don't forget that if yours is not exactly the same it's not
necessarily wrong.

Program Input_Number;          {Don't forget that this line is not


needed}

Uses Crt;

var
  &nbspnum : Integer;
begin

  &nbspClrscr;;
  &nbspWriteln('Enter an Integer');
  &nbspReadln(num);
  &nbspWriteln('The Integer you entered was: ',num);
  &nbspReadln;;                      {Wait for the user to press enter}

end.

In programming the same thing can be done many different ways, so don't worry if your
program is different from ours as long as it works fine.

However if you found this task hard or didn't understand, you might want to reread some
of the previous lessons and try this task again later.

Another Exercise:
Change your program so that instead of asking the user for a number, it asks for their
name. Then get the program to say hello to the user.

Program Input_Name;
Our Answer
Uses Crt;

var
  &nbspname : String;
begin
  &nbspClrscr;;
  &nbspWriteln('Enter your name');
  &nbspReadln(name);
  &nbspWriteln('Hello ',name);
  &nbspReadln;;

end.

Don't forget that there are many ways a program can be done. Your one doesn't have to
be the same as ours.

Loop Exercise
Here is an exercise to practice loops:

Write a program which lets you enter the price of several articles. The user will enter a
price of zero to indicate that there are no more articles to be added. Once all the articles
have been entered, the program must display the total price of all the articles.

Example Answer
Program DisplayTotal;

uses crt;

var

price,total : Real;
begin
clrscr;
repeat
write('Please enter the price of the next article: $');
readln(price);
writeln;
total := total + price;
until Price = 0;

if total > 100 then total := total * 0.95;

Writeln('Then total price was: $', total : 0 :2);


readln;
end.

Triangle Analyser
Exercise
Here is the aim of this exercise...

You are to make a program which takes in the three side lengths of a triangle
and tell the user what type of triangle it is. e.g. right-angled , isoceles etc.
It should also tell the user whether the triangle is illegal.

You can download the answer here

program Triangle;

uses Crt;

var
i : integer;
side : array[1..3] of real;
begin
clrscr;

{TITLE}
writeln ('-----------------');
writeln ('Triangle Analyser');
writeln ('-----------------');
writeln;
writeln;
{INPUT}
for i := 1 to 3 do
begin
write ('Please enter side number ', i,' of the Triangle: ');
readln (side[i]);
end;
writeln;
writeln;
{PROCESSING AND OUTPUT}
if (side[1]+side[2]<=side[3]) or (side[2]+side[3]<=side[1])
or (side[1]+side[3]<=side[2]) then {These conditions are invalid
triangles}
writeln('That triangle is invalid')
else if (sqrt(sqr(side[1])+sqr(side[2])) = side[3])
or (sqrt(sqr(side[1])+sqr(side[3])) = side[2])
or (sqrt(sqr(side[2])+sqr(side[3])) = side[1]) then
writeln('That triangle is right-angled') {right angled <=>
a^2+b^2=c^2}
else if (side[1] = side[2]) and (side[2] = side[3]) then
writeln('That triangle is equilateral')
else if (side[1]=side[2]) or (side[2]=side[3]) or (side[1]=side[3])
then
writeln('That triangle is isoceles')
else writeln('That triangle is scalene'); {scalene = all sides
different}
writeln;
writeln;
writeln('Press any key to exit...');
while not keypressed do;

end.

Finding Pi
Using this following formula write a program which calculates pi:

pi = 2(2/1 * 2/3 * 4/3 * 4/5 * 6/5 * 6/7 * 8/7 * 8/9...)

For this program it will be best to use a type of variable called 'double'. This is like a 'real'
but can store more decimal places. It may also be useful to make the loop counter of type
'longInt'.

Here is our answer: Finding Pi

However: Although this is the simplist formula this takes a large number of loops to find
pi to many decimal places.

Other formulas are:

pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11...)


Note this formula is nearly as bad as the first one at taking a large number of loops.

pi = 16(1/5 - 1/3(1/5)^3 + 1/5(1/5)^5 - 1/7(1/5)^7 + ...) - 4(1/239 - 1/3(1/239)^3 +


1/5(1/239)^5 - 1/7(1/239)^7 + ...)
This formula (although more complex) gives pi much faster.

Try using these formulas to find pi.

The Fibonacci Sequence (1,1,2,3,4,8,13,21...) in which:


t(n) = t(n-1) + t(n-2)
can be used to find the golden ratio (1.618033989...):
Golden ratio = t(n)/t(n-1)

Find the golden ratio to as many decimal places as you can using this result.

Pizza Cost Finder


The challenge is for you to make a program which does the following...
*Takes the diameter of the pizza

*Takes the number of extra ingredients

*Works out the selling cost of the pizza from the above information

sellingcost = cost * 1.5


cost = fixedcost + (basecost*area) + (number of extra ingredients*extracost*area)
area = pi * r^2
basecost=cost of the base per metre squared
extracost=cost of an extra ingredient per metre squared
fixedcost=the fixed cost involved in making the pizza ie. labour

basecost, extracost and fixedcost are to be constants with the values 3.75,1.55 and 0.75
respectively.

Answer
program pizza;
{This works out the cost of a pizza}
{Ronald Begg}
uses Crt;
label extra;
const
fixedcost = 3.75;
basecost = 1.55;
extracost = 0.75;
var
diameter,area,cost,sellingCost : real;
ingred : integer;
begin
clrscr; {This block is my title}
writeln ('------------------');
writeln ('Pizza Cost Program');
writeln ('------------------');
writeln;

{input}
write ('Diameter of the Pizza(cm): ');
readln (diameter);
diameter := diameter /100; {convert to metres}

extra:
write ('Number of extra ingredients: ');
readln (ingred);

if (ingred > 3) or (ingred < 0) then


begin
writeln ('Invalid number of extra ingredients, please enter 0-
3');
goto extra;
end;

{processing}
area := pi*sqr(diameter)/4;
cost := fixedcost + (basecost*area) + (ingred*extracost*area);
sellingcost := cost * 1.5;

{output}
writeln;
writeln;
writeln ('The total cost of this Pizza is: $',sellingCost:0:2);
writeln;
writeln ('Press any key to exit...');
while not keypressed do; {Waits for a key to be pressed}
end.

School TV Statistics
The idea here is to design a program to take in an unknown number of students input.
Each student enters the hours of TV that he/she watched each day in the last week. From
the
information obtained this program should work out the following...
 The number of students interviewed
 The highest hours of TV watched in one day
 The highest average hours of TV watched each day in a week
 The overall average for the students.

HINT:&nbspYou might want to use a menu to do this. It is a nice way of doing it.

A model answer can be downloaded here

program TVProg;
{Figures out TV watching statistics}
{Ronald Begg}

uses Crt;
var
num : integer;
highestDayName,highestAvgName : string[30];
totalAvg,highestDay,highestAvg : real;

procedure pageBorder; {This procedure puts a border around the page}


var
i : integer;
begin
textColor(12);
for i := 1 to 79 do
begin
gotoXY(i,1); write('Û');
gotoXY(i,25);write('Û');
end;
for i := 1 to 25 do
begin
gotoXY(1,i); write('Û');
gotoXY(79,i);write('Û');
end;
end;

function day (number : integer): string;


{This function returns the day name from a number 1-7}
begin
case number of
1: day := 'Monday';
2: day := 'Tuesday';
3: day := 'Wednesday';
4: day := 'Thursday';
5: day := 'Friday';
6: day := 'Saturday';
7: day := 'Sunday';
end;
end;

procedure questions;
label query;
var
i,code : integer;
studentName : string[30];
stringHours : string;
studentAvg,hours : real;
begin
studentAvg := 0; {I put this in because pascal was giving huge}
clrscr; {numbers for the studentAvg if I didn't do
this}
textColor(15);
num := num + 1; {Add one for the extra student}
write ('Please enter your name: ');
readln (studentName); {Get the student name}
for i := 1 to 7 do {Get the hours of tv watched for each
day}
begin
query:
write ('Please enter the hours of TV you watched on ');
textColor(11); {Make the days appear blue}
write (day(i));
textColor(15);
write (' :');
readln (stringHours);
val(stringHours,hours,code);
if (hours = 0) and (stringHours[1] <> '0') then
begin {Check if a number was entered}
writeln ('Please enter a number as your input!');
while not keypressed do; {Wait for a key to be pressed}
readKey; {Clear the keyboard buffer}
goto query;
end
else if (hours > 24) or (hours < 0) then
begin {Check if number is valid}
writeln ('Please enter a value between 0 and 24!');
while not keypressed do;
readKey;
goto query;
end;
if hours > highestDay then
begin
highestDay := hours;
highestDayName := studentName;
end;
studentAvg := studentAvg + hours;{Add hours to the avg}
end;
studentAvg := studentAvg / 7; {Divide the total by seven to get
Avg}
totalAvg := (totalAvg * (num-1) + studentAvg)/num; {Get the new
total average}

if studentAvg > highestAvg then


begin
highestAvg := studentAvg;
highestAvgName := studentName;
end;
{Output for the student}
textColor(14);
writeln;
writeln;
writeln ('The average hours of TV watched a day for
',studentName);
writeln ('was ', studentAvg:0:1,' hours a day (1dp)');
while not keyPressed do; {Wait for key to be pressed}
readKey; {Clear the keyboard buffer}
end;

procedure overall;
begin
clrscr;
pageborder;
textColor(15);
gotoXY(5,8); {Show overall things like--number of students}
write('The total number of students interviewed was: ',num);
gotoXY(5,10); {--Highest hours in a day}
write('The highest recorded time for one day was :
',highestDay:0:1,' hrs');
gotoXY(5,11);
write('This time was achieved by: ',highestDayName);
gotoXY(5,13); {--Highest average hours}
write('The highest recorded average time was :
',highestAvg:0:1,' hrs a day');
gotoXY(5,14);
write('This average was achieved by: ',highestAvgName);
gotoXY(5,16);
write('The average amount of TV watched a day, overall, was: ',
totalAvg:0:1, ' hrs a day');
while not keypressed do; {Wait for a key to be pressed}
readKey; {Clear keyboard buffer}
end;

procedure clearStats; {As you can see, this clears all the overall
stats}
begin
num := 0;
totalAvg := 0;
highestDay := 0;
highestAvg := 0;
highestDayName := '';
highestAvgName := '';
clrscr;
pageborder;
textColor (14);
gotoXY(25,12);
write ('THE STATS HAVE BEEN CLEARED');
textColor(12);
gotoXY (1,25); {Hide the cursor in the page border}
while not keypressed do; {Wait for a key to be pressed}
readKey; {Clear the keyboard buffer}
end;

procedure showMainMenu(option : integer);


begin
{This shows the menu highlighting the selected option}
textColor (14);
textBackground (12);
gotoXY(20,9); write(' TV WATCHING STATS ');
textBackground (3);
if option = 1 then textBackground (5);
gotoXY(20,10); write(' Another Student ');
textBackground(3);
if option = 2 then textBackground (5);
gotoXY(20,11); write(' View Overall Stats ');
textBackground(3);
if option = 3 then textBackground (5);
gotoXY(20,12); write(' Clear Overall Stats ');
textBackground(3);
if option = 4 then textBackground (5);
gotoXY(20,13); write(' Exit ');
textBackground(0);
textColor(12); gotoXY(1,25); {hide the cursor in the page border}
end;
var
option : integer;
key : char;
begin
option := 1;
clrscr;
pageBorder;
while 1=1 do
begin
textBackground (0);
showMainMenu(option);

while not keypressed do;


key := readKey;

case key of
'H': begin {If the up arrow is pressed go up one}
option := option - 1;
if option < 1 then option := 1;
end;
'P': begin {If the down arrow is pressed go down
one}
option := option + 1;
if option > 4 then option := 4;
end;
chr(13),' ': begin {If enter is pressed then do the current option}
case option of
1: questions;
2: overall;
3: clearstats;
4: halt;
end;
clrscr;
pageborder;
end;
end;
end;
end.

Quiz
This is a quiz to see how much you have learnt about Pascal. You will be told your
results at the end, so just select the answer you think is best, click the corresponding
button, and move on to the next question. Good Luck!.

Rules
You start with a score of 20. A correct answer gives you four marks and an incorrect
answer takes one off your score. There are 20 questions so the lowest mark you can get is
zero and the highest mark is one-hundred.

Question 1
What is the var section for?

Declaring Constants
Declaring Variables
Your code goes here
Declaring types

Question 2
What does the Integer type hold?

Numbers between 0 and 65536


Letters and numbers
Anything
Numbers between -32768 and +32767

Question 3
How do you set the number of decimal places to be printed, with the writeln() statement?

Hit the computer that many times


Put it in brackets next to the variable
The value after the second colon
The value after the first colon

Question 4
What function is used to find the Sine of an angle?

cos()
sin()
arctan()
sqrt()

Question 5
How do you open a file for reading?

Using reset(f : File)


Using append(f : File)
Using open(f : File)
Using a crowbar
Question 6
What is an array?

A long string
A negative integer
A list of values
A while loop

Question 7
What command can you use instead of using if?

case
when
in situation
check condition

Question 8
How do you change the color of text?

textColor(integer)
foreColor(integer)
backColor(integer)
changeColor(integer)

Question 9
What type can't you use with the case statement?

char
integer
boolean
string

Question 10
What command is used to stop your program from running?

stop
halt
cease
pleaseStop!

Question 11
What unit is used in most pascal programs?
strings
Graph
Crt
Turbo

Question 12
How do objects differ from records?

They don't have properties


They take up less memory
They have procedures as well as properties
They are exactly the same

Question 13
Which one of these is not a loop in Pascal?

while..do
for..do
repeat..until
do..loop

Question 14
What command is used to locate the cursor at a set position on the screen?

locate (x,y)
gotoXY (x,y)
position (x,y)
cursorPos (x,y)

Question 15
Which one of these trigonometry functions is pascal missing?

tan
cos
sin
arctan

Question 16
What would X be equal to if, in pascal you had the code:-
X := 7*8-5 mod 3? (pascal has the same order of operations as a scientific calculator)

0
3
51
54

Question 17
What does the break command do?

Exit from the program


Exit from the current procedure
Exit from a loop
Breaks the computer

Question 18
How do you clear the screen in pascal?

clearScreen
cls
cs
clrscr

Question 19
Which one of these is a keyword?

integer
boolean
real
string

Question 20
Which one of these can only be declared in the type section?

objects
arrays
strings
booleans

Glossary
Boolean Constant Function
Keyword Ordinal Type Procedure
Reserved Word Syntax Variable
Boolean
Variable type named after George Boole who invented the representation of data with
either true or false (or 0s and 1s). A boolean can therefore take on the value of either true
or false. Conditional statements are boolean expressions. A boolean variable b may be
filled thus (among other ways):
b := (y = 2);
If y is 2 then b will become true, otherwise b will be false.

Back to top Back to where you were

Constant
A value which is set at design time, which cannot be changed during program execution.
It may be use for things such as the number of feet in a mile, to make your code more
readable.

Back to top Back to where you were

Function
A procedure that returns a value. A function to return the interest on a bank account
would be better practice than a procedure which put the value into a global variable.

Back to top Back to where you were

Keyword
A word, reserved by Pascal, for special use. Such as the program keyword which is
reserved for declaration of the program name. Keywords cannot be used for any other
purpose. They are also sometimes called reserved words.

Back to top Back to where you were

Ordinal Types
A type which contains a single value defining a place in an order. Hence, ordinal. In
pascal the only types that are not ordinal are string, array, record and object types.
See also : Boolean

Learn about : Variables

Back to top Back to where you were

Procedure
A block of instructions which can be called with a reference to the procedure name. A
procedure can take parameters. Normally used for code which is used a number of times
throughout the program. For instance you might make a procedure to calculate the
interest on a bank account, and each time, pass it the account balance and the interest
rate. It could check for being below the minimum to get any interest, etc.

See also : Functions

Back to top Back to where you were

Reserved Word
A word, reserved by Pascal, for special use. Such as the program reserved word which is
reserved for declaration of the program name. Reserved words cannot be used for any
other purpose. They are also sometimes called keywords.

Back to top Back to where you were

Syntax
The syntax of a command is how it is written.
e.g the readln command is written like so:--
readln (&ltstring value>);

Back to top Back to where you were

Variable
Reference to a memory address which can store information. What I mean is if you
declare i as an Integer, it has a variable value, such that it may change throughout your
program, or it may be set once, and that value checked.

See also : Constant


Back to top Back to where you were

You might also like