PASCAL Tutorial
PASCAL Tutorial
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.
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)
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
You will also need to know how to use the Pascal programming environment:
How to Use Pascal
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.
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
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.
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.
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
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'.
'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
 InchesInFoot = 12; {These are some constants you might use}
 DaysInWeek = 7;
 e = 2.1718281828;
type
{Type definitions go here - don't worry about these yet}
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.
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.
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.
Make sure you understand all of the above before proceeding further.
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.
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;
Integer Division: One integer is divided by another and the integer part of the result is
returned.
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
Procedures and
Functions
Sometimes when you are programming you might need to use the same piece of code
over and over again.  It 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.  So 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.  An example of this would be...
This would call the procedure drawBob. It passes it the values x and y which the
procedure will use as Bob's coordinates.  The drawBob procedure would look
something like this...
Somewhere in the code it would use x and y.  Notice that x and y are declared like
variables except for the fact that they are in the procedure's header.  If you wanted
different types of parameters, eg. integers and strings, then you must separate them by
semi-colons like this...
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...
So by now you should know how to use a procedure. Next we will talk about Functions.
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, ': <variable 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
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.
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.
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;
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 <condition> then
statement block
else if <condition> then
 .
 .
 .
else
statement block
and this can go on for a long time. For instance you could have a condition:
program security;
uses crt;
var
 input : String;
begin
clrscr;
 writeln('Enter the password');
 readln(input);
if (input = 'Pascal') then
 writeln('Pascal is easy!')
{Note no semicolon for one line}
else if (input = 'Basic') then
begin
 writeln('Basic is not');
 writeln('very hard!');
end
else
 writeln('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
 .
 .
 .
 label1:
{Note the colon!}
 .
 .
 .
goto label1;
{Note no colon}
 .
 .
 .
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
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
Program classTest;
{An example program demostration arrays}
{Takes scores from a class test and tells people if they passed or not}
uses Crt;
type
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;
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
var
marks : testScores;
var
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.
Records are just a way of defining your own type. It is done like this:
type
 doorType = record
 width : Integer;
 height : Integer;
 color : String[10];
end;
Now when you want to use doorType in your program you would do
this:
var
 aDoor : doorType;
begin
with aDoor do
begin
 width := 30;
 height := 50;
 color := '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.
program doorFind;
{Find the area of a door}
uses crt;
type
 doorType = record
 width : Integer;
 height : Integer;
end;
var
 door : doorType;
begin
 clrscr;
 writeln('Enter the door height');
 readln(door.height);
 writeln('Enter the door width');
 readln(door.width);
 writeln('The door area is ', door.width*door.height);
 readln;
end.
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.
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.
...
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.
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 (<file variable>,<file 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 (<file 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 (<file 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 (<file variable>);
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 (<file variable>,person);
You can write as many records to the file as you like now :)
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 (<file 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 (<file variable>,filesize(<file 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 (<file variable>,filesize(<file variable>)-1);
truncate (<file variable>);
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
procedure deleteRecord;
var
i : integer;
person : personType;
begin
seek (personFile,fileSize(personFile)-1);
read (personFile,person);
seek (personFile,i);
write (personFile,person);
seek (personFile,fileSize(personFile)-1);
truncate (personFile);
end;
begin
<Main 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.
Uses Crt;
var
 num : Integer;
begin
 Clrscr;;
 Writeln('Enter an Integer');
 Readln(num);
 Writeln('The Integer you entered was: ',num);
 Readln;; {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
 name : String;
begin
 Clrscr;;
 Writeln('Enter your name');
 Readln(name);
 Writeln('Hello ',name);
 Readln;;
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;
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.
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:
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'.
However: Although this is the simplist formula this takes a large number of loops to find
pi to many decimal places.
Find the golden ratio to as many decimal places as you can using this result.
*Works out the selling cost of the pizza from the above information
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);
{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: You might want to use a menu to do this. It is a nice way of doing it.
program TVProg;
{Figures out TV watching statistics}
{Ronald Begg}
uses Crt;
var
num : integer;
highestDayName,highestAvgName : string[30];
totalAvg,highestDay,highestAvg : real;
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}
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;
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?
Question 3
How do you set the number of decimal places to be printed, with the writeln() statement?
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?
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?
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?
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.
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.
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.
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.
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
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.
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.
Syntax
The syntax of a command is how it is written.
e.g the readln command is written like so:--
readln (<string value>);
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.