Pascal Notes
Pascal Notes
Turbo Pascal is a compiled language. This means you write your program code in
an editor, then you compile and run the program.
If there are mistakes in your code, these will usually be picked up by the compiler
which wont compile the program until you fix them.
Start Turbo Pascal, and in the editor (called the IDE - Integrated
Development Environment) type the following code.
program FirstProgram;
begin
clrscr; {clears the screen}
writeln('A ');
writeln('fine ');
writeln( program.');
write ('A fine program ');
writeln ('with no hitches.');
writeln;
writeln;
write ('A fine program,');
writeln ('my friend, this is!');
write('A');
write('fine');
write('jumble!');
readln; { you must press Enter to finish the program and return to the IDE.}
end.
You should see some messages appear on the screen, press Enter to return to the
IDE.
forgetting the ; semi-colon that must be at the end of most lines (but not
all!!)
the full stop after the end at the end of the program.
Page: 1 of 15
TURBO PASCAL NOTES
This program shows how to use the procedures writeln and write to place text
on the screen.
What do you think is the difference between these two procedures?
Notice that the words that are being written to the screen must be inside
parenthesis ( ) and have around them.
Exercise 1.
Try adding some lines of your own to this program so that it prints messages over
most of the screen.
Save the program on your data disk by clicking File | Save As ... , select
correct drive and a suitable name.
(e.g. red = 4)
Here is some code to draw a series of windows on the screen using the Crt unit.
Notice how you can get shadow effects using a box on top of another.
Page: 2 of 15
TURBO PASCAL NOTES
program ScreenBoxes;
uses crt
begin
TextBackground(Green);
ClrScr;
Window(3,2,78,24);
TextBackGround(Red);
ClrScr;
Window(6,4,75,22);
TextBackGround(Black);
ClrScr;
Window(8,5,74,23);
TextBackGround(Blue);
ClrScr
end.
Try this program listing: (* Try out some of the operators and functions *)
program OperatorsAndStdFunctions;
uses crt; {Just to make it look a bit fancy, colour courtesy of the crt unit}
var {this is where variables you use in a program must be declared.}
integer1, integer2, AnswerA: integer; {declare 3 integer variables}
number1, number2, AnswerB : real; {declare 3 real variables}
begin
TextBackGround(Blue);
ClrScr;
TextColor(White);
Writeln('Kindly type in an integer of your choice, friend.');
Writeln( Please remember that an integer is a whole number.');
readln(Integer1); {store their first integer in Integer1}
Writeln('Kindly type in another integer of your choice, friend.');
readln(Integer2);
AnswerA:= Integer1 + Integer2; {we use the + operator}
Writeln;
Writeln('The sum of your integers is ',AnswerA);
Writeln; {create some space on the screen.....}
Writeln; {by writing empty lines.}
Writeln('Kindly type in a real number of your choice, friend.');
Writeln( A real number may have decimals, example 3.412.');
readln(Number1);
Writeln('Kindly type in another real number of your choice, friend.');
readln(Number2);
AnswerB:= Number1 + Number2;
Writeln;
write('The sum of your numbers is ')
Writeln(AnswerB);
Writeln;
write('However this looks much better as: ');
Writeln(AnswerB:3);
Writeln;
write('And better still as: ');
Writeln(AnswerB:3:4);
readln
end.
Page: 3 of 15
TURBO PASCAL NOTES
Notice the use of the := sign to assign a value to a variable. In Basic the = sign is
used, in most Logo versions a procedure called MAKE or NAME is used.
In Pascal programming, you must declare in your code the type of variables you
plan to use. This tends to slow you down at first, as you must be familiar with the
different data types available.
integer - the positive and negative counting numbers (...-3, -2, -1, 0, 1,
2....)
char - any letters, punctuation marks, digit characters from the keyboard
Boolean - have only two values, either true or false
real - positive and negative numbers that include decimals.
Another very useful type is the set type. The set type can represent a group of
ordinal types - these are values that are defined in a particular order. A sequence
of integers numbers (1...1000), the letters A .. Z are examples, or you can
define your own ordinal type.
var ValidKeys = [ 1 , 2 , 3 , 0 ];
The elements that belong to the set you define are enclosed in square brackets.
It is important that if you declare a variable of a particular type, that the value it
gets is of the same type, else you get a type mismatch, which will cause a
problem.
In the program listing on the previous page, see what happens when you give a
real number (say 3.456) when the program asks for an integer. {Crash!!!!} This
is called a type clash.
* the use of write and writeln - can you see the difference in their effect?
* how real numbers are dealt with by the compiler in floating point notation,
which may be a bit foreign to most people (e.g. 4.35E+03), but you can change
this by putting numbers such as (AnswerB:3:4) which prints the variable in
decimal form, to 4 decimal places in this case.
Can you work out what the effect of the 3 in (AnswerB:3:4)?
Operators
Notice that division, /, is not an operator with integers. This is because if you
divide an integer into another integer the result is not an integer (5 / 2 = ?).
Exercise 3.1
Write a program that takes two numbers from a user, then computes their sum,
difference(-), product (*), and quotient and displays the results in a readable,
user friendly form.
Page: 4 of 15
TURBO PASCAL NOTES
The following Arithmetic functions will allow you to perform many more
operations on numbers the user of your program supplies.
Try them out:
Exercise 3.2
Try some of these functions in a program, so that user can calculate some weird
and wonderful results.
So now that you have- Turbo Pascal, Operators and some Arithmetic functions,
you should be able to work out any sum you need!!!!
Computer programs can get quite long. In fact, they soon get very difficult for a
human to read and understand, though a computer won't usually complain if the
program is bug free. To overcome this, most programming languages use
subprograms in the main program so that a human can more easily follow what is
going on. In Pascal, two sorts of subprograms are Procedures and Functions.
Here is an example of a procedure in Pascal. (don t type it in yet, it must go in
the body of the larger program)
Page: 5 of 15
TURBO PASCAL NOTES
It looks similar to a program in the way it is set out - with a name, and the words
var, begin, and end appearing.
You give a procedure its name after the reserved word procedure and then in
parentheses you must give any "parameters" the procedure may use.
If you have done some Logo programming, a parameter for a procedure or
function is the same as an "input" for a Logo procedure.
Unlike Logo parameters, in Pascal you also have to declare what type of
parameter is being used,- in the example, the parameter is called UserName
and its type is string. The string type refers to strings of characters such as
lkjljkjkl or William etc.
The variables BackColour and ColourText are local - they only have meaning
and effect inside this procedure. The rest of the program doesn t know anything
about them.
The following program listing shows how procedures and functions are used.
program SomeProcedures;
uses crt ; {the crt unit provides colours for text and backgrounds }
var
Name : string {string variables used for names etc.}
FirstInt, SecondInt, Result: integer;
Page: 6 of 15
TURBO PASCAL NOTES
The counter variable is used to count how many times the for loop will repeat.
program Animate;
uses Crt, Graph;
{Crt unit has the Delay procedure, Graph unit for graphics }
(* This procedure will draw a box shape, wait a set time, then
draw over and hide the shape using XORPut. It has 3 parameters (of type
integer), the x and y coordinates of the top left side, and the time delay before
the shape is hidden.*)
Page: 7 of 15
TURBO PASCAL NOTES
end;{DrawTheShape procedure}
var
Counter , Driver, Mode: integer; {Counter is used by for loop, Driver and
Mode to initialize the graphics }
begin
Driver:= Detect; {detect the Graphics hardware}
InitGraph (Driver, Mode, ' '); {Initialize the graphics - path to driver is default
you made need to specify a path between the ' '}
SetBkColor(LightBlue); {set screen background}
SetColor(Red); {set pen colour}
ClearDevice; {clear the screen}
NOTE; this code used the graphics driver and assumes that that it is in the
default directory. See your Turbo Pascal manuals if uncertain about this.
If you want to put more that one statement in your for loop, you must make a
compound statement. This must have a begin and end on either side of it.
readln
end.
Now the for loop repeats the 3 lines in the compound statement a total of 500
times!
Page: 8 of 15
TURBO PASCAL NOTES
You can change where the box moves on the screen by altering the start and end
values assigned to the Counter variable.
Try these:
DrawTheShape(X, 0, 5);
DrawTheShape(X, X, 5);
Notice the use of the word var in the parameter declaration. This is how you
specify that parameters are variable rather than value.
Page: 9 of 15
TURBO PASCAL NOTES
You should type in the code of the program below, debug and run it, and study it
carefully. Experiment by altering values of the numbers in the code and watch the
effect on the screen.
What you should see is that value parameters can be altered in a procedure, but
this has no effect outside that procedure.
A variable parameter must be a variable, whereas you could simply supply two
numbers to the procedure ValueParams.
(****** This program attempts to show the difference between value and
variable parameters.**)
(**** O. Parnaby 15 Oct. 1996 ************)
program ValueAndVarParams;
uses crt;
var Number1, Number2 : integer;
Page: 10 of 15
TURBO PASCAL NOTES
Use this procedure in a program that gets the series length and the numbers
from a user, then prints the result of the calculation.
begin
.....
end; }
The if statement lets a program choose between taking two alernative actions.
Its general form is :
if (boolean expression, ie an expression that is true or false)
then (some action)
else (some alternative action)
The else portion of the statement can be left out if it is not required.
Page: 11 of 15
TURBO PASCAL NOTES
This code assumes that two variables Number1 and Number2 have been
declared first.
exercise If Number1 = 435 and Number2 = 546, what would be the output of
this code?
If the actions to follow the if and else have more than one statement, then this
compound statement must be enclosed by a begin and end.
example:
if Number1 > Number2 { > is the "greater than" symbol}
then
begin
writeln ( Bill wins );
BillsScore := BillsScore + 1;
end {then }
else
begin
writeln ( Joan wins );
JoansScore:= JoansScore + 1;
end; {else}
You may wish to test a character a user has press using an if statement.
A menu type example might look like this:
uses crt; {crt unit has the Readkey procedure}
var TheChar : char
...{lines of code, headings etc.}
TheChar := Readkey; {The Readkey waits for a key to be pressed, we assign the
value of the key pressed to TheChar}
if TheChar = 1 then
begin
DoMenuOption1; {user defined procedure}
DrawTheMenu; {user defined procedure - redraw the menu again }
end;{if}
else
FlashErrorMessage; {user defined procedure}
.....
7 < 4 (false)
4 = 4 (true)
SecondLetter >= FirstLetter (?) depends on what values the variables have
Y <> chr(45) (false) <> means not equals
chr(45) is ascii character number 45
Page: 12 of 15
TURBO PASCAL NOTES
The case statement is a good way to get a program to choose between a number
of alternatives. The same effect could be achieved using numerous if...then
statements, but the case statement is often a simpler and clearer way of doing
this.
case expression of
value1 : statement1;
value2 : statement2;
..... etc
else {if an else is to be
used}
statement;
end; {case}
Suppose you are writing a Menu procedure, and you want the procedure to do
different things depending on which key the user presses.
Here is a snippet of some sample code:
end {case}
Page: 13 of 15
TURBO PASCAL NOTES
(****************************************************************
**)
(* The while loop, and read/write to console *)
(* O.Parnaby 19/11/96 *)
(* This short program demonstrates a use of the while-do loop *)
(* Notice how characters are read into a variable, then *)
(* "echoed" (written) onto the screen. *)
(* Notice also how if a Carriage return (pressing Enter) is read
then a writeln is used to write characters on the next line *)
(****************************************************************
***)
program WhileLoop;
uses
Crt;
Const {define these constants to make handling characters easier}
EscKey = #27; {char 27 is the Esc key}
{The SET type - handy to use with IN, to screen characters}
ValidKeys : SET OF Char = ['0'..'9','A'..'z', #13, #32];
{Here we have declared a constant, and defined it at the same time}
var
TheChar : Char; {we will read characters into this variable}
begin
clrscr;
Writeln('Type characters and see them echoed to the screen');
Writeln ('Press Esc key when finished.');
Textcolor(green);
TheChar := Readkey; {Read the key pressed into TheChar variable}
While TheChar <> EscKey do {while the key pressed is not Esc}
begin
if TheChar IN ValidKeys then
begin
{if the key is Enter - carriage return}
if TheChar = #13 then Writeln(TheChar)
{display the char on screen, note: no ; before an else}
else Write(TheChar); {write key to the screen}
end;{IF TheChar }
TheChar := Readkey; {read the next character}
end; {while}
writeln;
Writeln('Press any key to finish');
readln;
end.
example:
program TwoDimensionalArraysPart1;
uses
crt; {for clrscr}
type
Table = array['A'..'F','a'..'f'] of string[2]; {first define the array type}
{now follow procedures to initialise the values, and to print them to screen}
{these procedures will be handed a variable parameter of type Table
Page: 14 of 15
TURBO PASCAL NOTES
var
TheTable: Table; {This is the variable that the procedures will use}
Page: 15 of 15