Sunteți pe pagina 1din 15

TURBO PASCAL NOTES

1. Writing a program in Turbo Pascal.

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;

{Demonstrates procedures write and writeln}

uses crt; {needed for the procedure clrscr - clear screen}

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.

Words inside curly brackets { } are not part of the


program code , but are called comments, and just
explain what is happening. I will put them in italics too.
It is a very good idea to put comments in all your
programs - all good programmers should do this so that
other people may understand what they intend to do.

To run this simple program, Click Run on the Menu bar,


or hold down Ctrl and press F9 -- (Ctrl + F9)

You should see some messages appear on the screen, press Enter to return to the
IDE.

You may get error messages.


The most common mistakes are :

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.

2. Adding colours to your text messages.


The crt unit enables you to use colours and windows on a text screen fairly
easily.
To have access to the procedures and function in the crt unit you must include
the line uses crt; immediately after your program heading.

Some of the procedures to try out (consult the manuals) are:

ClsScr clears the current window screen


TextColor(red) sets text colour

TextBackGround(5) sets text background colour.


Note that you can use colour numbers 0 to 15 or the defined constants

(e.g. red = 4)

program TextColours; {practice writing text on the screen in different colours}


uses crt; {the crt unit has the colour procedures}
begin
TextBackGround(Blue); {set background to blue}
clrscr; {clear the screen}
TextColor(Red); {text will be printed on screen in red}
writeln('Zippity doo da..');
TextColor(6); {numbers 0 to 16 are available, e.g. red = 4}
writeln('Zippity day');
readln;
end.

Window(X1,Y1,X2,Y2) places a window on the screen, at points (X1,Y1) top


left, and (X2,Y2) bottom right. Many other commands are now relative to this
window only.
GoToXY(X,Y) puts cursor at a point on the screen (relative to the current window)
ready for a write
e.g. GoToXY(10,10);
write('Well here we are on a Crt screen then!');

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.

3. Variables, some Pascal types, operators .

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.

Some of the simple types in Pascal are :

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.

You can define a set like this:

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.

Experiment with the program listed and study the following:

* 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

Experiment with the operators


integers ___+ , - , * (times)
real ______+ , - , * , / (division)

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

Some Standard Functions in Pascal.

The following Arithmetic functions will allow you to perform many more
operations on numbers the user of your program supplies.
Try them out:

FUNCTION NAME EXAMPLE RESULT

sqr square Writeln (sqr(7)); 49

sqrt square root Writeln(sqrt(1690)); 130

ln natural log Writeln(ln(4)) you tell me

abs absolute value Writeln(abs(-3)) 3

round rounds to Writeln(round(3.456) 3


nearest integer Writeln(round(-2.6) -3

trunc chops off real Writeln(trunc(3.9)) 3


no to whole Writeln(trunc(-4.85)) -4
part

sin sin of angle in Writeln(sin(3.142)) about 0


radians

cos as for sin but Writeln(cos(3.142)) about -1


cosine

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)

procedure GreetUser(UserName: string);


begin
TextBackground(2);
TextColor(4);
ClrScr;
GoToXY(5,5);
write('Well hello ',UserName);
GoToXY(5,7);
Writeln('And how are you now?')
end;{GreetUser}

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.

Here is an example of a Function in Pascal:

function AddEm(First, Second: integer):integer;


begin
AddEm:= First + Second;
end;
A function looks like a procedure, but notice that:
after its parameters, you must also give it a type (AddEm is an integer type)
the function calculates a value, so it will be used for this purpose in the program

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;

procedure GreetUser(UserName: string);


begin
TextBackground(2);
TextColor(4);
ClrScr;
GoToXY(5,5);
write('Well hello ',UserName);
GoToXY(5,7);
Writeln('And how are you now?')
end;{GreetUser}

function AddEm(First, Second: integer):integer;


begin
AddEm:= First + Second
end;{AddEm}

begin {main program}


TextBackGround (Black);
TextColor(White);
ClrScr;
GoToXY(2,2);
Write('Please type in your name and press <Enter>.');
GotoXY (2,4);

Page: 6 of 15
TURBO PASCAL NOTES

Readln(Name); {The users name is stored in the variable Name}


ClrScr;
GotoXY(5,5);
Write('We pause for a slightly dramatic effect!!!');
Delay(3000); {Delay waits 3000 milliseconds (approx.)}
GreetUser(Name); {The users name is given to the procedure GreetUser}
Writeln('Please type in a whole number.');
readln (First); {read the number into the variable First}
Writeln; {Write a blank line}
Writeln('Please type in another whole number.');
readln(Second); {read the number into the variable Second}
Result:= AddEm(FirstInt,SecondInt); {AddEm calculates the sum for Result}
Writeln('The sum of your numbers is ',Result);
GoToXY(5,15);
write('Press Enter to finish.');
readln {Nothing happens until Enter pressed}
end.{SomeProcedures} {Readln reads a CR (carriage return)}

The "for" statement .

The "for" statement is an example of a Pascal control structure, and it is an


iterator - something that repeats an action. This is also called a loop.
It allows us to repeat a statement a known number of times.

The structure of a "for" statement is:

for counter-variable := start-value to end-value do


some statement;

The counter variable is used to count how many times the for loop will repeat.

In the following example, we use it to create some animation.

(* This program demonstrates several things:


# the use of a procedure to draw a shape for us.
# using SetWriteMode to change the way the pen draws - we use XORPut
which has the effect of reversing the pen (like pen erase in Logo)
# using a for loop which is an iterator that allows you to repeat
an action a set number of times. *)

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.*)

procedure DrawTheShape (XPos, YPos, ShapeSpeed : integer);


begin
SetWriteMode(XORPut);
Rectangle(XPos, YPos, XPos + 20, YPos + 20); {Draw the box }
Delay(ShapeSpeed); {Wait a bit -number supplied for ShapeSpeed when called}
Rectangle(XPos, YPos, XPos + 20, YPos + 20); {Draw box again to erase it}

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}

for Counter := 0 to 500 do {the for starts here}


DrawTheShape(Counter, 200, 10); {Call procedure - Counter increased by 1 each
loop of for }
readln {the shape slides across. Press Enter to finish.}
end.

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.

Alter the Animate program by inserting the following:

Sound(550); {this will switch on sound at 550 Hz}

Delay(100); {this will allow the sound to play for a bit}

for Counter := 0 to 500 do {the for loop starts here}

begin {the start of the compound for statement}

Sound(1050) {switch the sound on at 1050 Hz}

DrawTheShape(Counter, 200, 5);


NoSound; {switch the sound off}

end; {the end of the compound for statement}

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

Experiment with this animation.


See how you can alter the speed at which the box moves by changing the third
parameter (value) in the DrawTheShape procedure.

DrawTheShape(X, 200, 200);

DrawTheShape(X, 200, 1);

You can change where the box moves on the screen by altering the start and end
values assigned to the Counter variable.

Try these:

for Counter := 100 to 200 do

for Counter := 10 to 600 do

Try these values for the parameters in DrawTheShape:

DrawTheShape(X, 0, 5);

DrawTheShape(X, X, 5);

Experiment with other values.

Write a new DrawTheShape that creates something more interesting than a


box to move across the screen.

Here is an example of a procedure with value parameters:

procedure ValueParams(Value1, Value2: integer);


begin
Value1:= 0;
Value2:= 0;
writeln('From inside the ValueParams procedure: ');
writeln ('Number1 is changed to ',Value1:3,' Number2 is changed to', Value2:3);
writeln('Press Enter to leave ValueParams procedure.');
readln;
end;

Here is an example of a procedure with 2 variable parameters:

Notice the use of the word var in the parameter declaration. This is how you
specify that parameters are variable rather than value.

procedure VariableParams(var Variable1, Variable2 : integer);


begin
Variable1 := 0;
Variable2 := 0;
writeln('From inside the VariableParams procedure: ');
writeln ('Number1 is changed to ',Variable1:3,' Number2 is changed to',
Variable2:3);

Page: 9 of 15
TURBO PASCAL NOTES

writeln('Press Enter to leave VariableParams procedure.');


readln;
end;

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.

If a variable parameter is given to a procedure and its value is changed by that


procedure, then this has effect outside the procedure.

A variable parameter must be a variable, whereas you could simply supply two
numbers to the procedure ValueParams.

This means, in the program you could have:

ValueParams(3 4) ; as an instruction, but you could not have


VariableParams( 3 4 ), as you must supply actual variables as the arguments
to this procedure.

Type in this code and run it.

(****** 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;

procedure ValueParams(Value1, Value2: integer);


begin
Value1:= 0;
Value2:= 0;
writeln('From inside the ValueParams procedure: ');
writeln ('Number1 is changed to ',Value1:3,' Number2 is changed to', Value2:3);
writeln('Press Enter to leave ValueParams procedure.');
readln;
end;

procedure VariableParams(var Variable1, Variable2 : integer);


begin
Variable1 := 0;
Variable2 := 0;
writeln('From inside the VariableParams procedure: ');
writeln ('Number1 is changed to ',Variable1:3,' Number2 is changed to',
Variable2:3);
writeln('Press Enter to leave VariableParams procedure.');
readln;
end;

Page: 10 of 15
TURBO PASCAL NOTES

begin {main program}


Number1:= 3;
Number2:= 4;
clrscr;
writeln('The starting values are Number1 = ',Number1, ' Number2 = ',
Number2);
writeln ('Press Enter, and these values will be passed to the ValueParams
procedure.');
readln;
ValueParams(Number1, Number2);
writeln('ValueParams has finished, and Number1 = ',Number1, ' Number2 =
',Number2);
writeln ('Press Enter, and these values will be passed to the VariableParams
procedure.');
readln;
VariableParams(Number1, Number2);
writeln('VariableParams has finished, and Number1 = ',Number1, ' Number2 =
',Number2);
writeln('Press Enter to finish program');
readln;
end.

Try these problems;

1. Write a procedure that averages a series of numbers.


The length of the series of numbers should be passed as a value parameter, and
the average value should be returned as a variable parameter.

Use this procedure in a program that gets the series length and the numbers
from a user, then prints the result of the calculation.

{hint : use for eg for n:= 1 to SeriesLength do

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.

Some pseudocode might look like this:


if the first number is greater than the second number

Page: 11 of 15
TURBO PASCAL NOTES

then print Bill wins


else print Joan wins

the equivalent Pascal code might be:


if Number1 > Number2
then writeln ( Bill wins )
else writeln ( Joan wins );

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}
.....

NOTE that an if..else statement must test a boolean expression. This is an


expression that will evaluate to either true or false.

examples of boolean expressions are:

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

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.

The form of a case statement is as follows:

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:

uses crt ; {has the Readkey function}


.........
procedure TheMenuLoop;
var TheKey : char;
begin
.....
TheKey := ReadKey; {ReadKey waits for a key press}
case TheKey of
'0' : QuitProgram; {a procedure to exit the program}
'1' : begin
Clrscr;
writeln('Your choice for option 1'); {More than one statement .. }
writeln('Press <Enter> to continue.'); {so begin...end must be used}
readln {This is called a compound statement}
end;
'2' : begin
Clrscr;
writeln('Your choice for option 2');
writeln('Press <Enter> to continue.');
readln
end;
'3' : begin
Clrscr;
writeln('Your choice for option 3');
writeln('Press <Enter> to continue.');
readln
end;

end {case}

The while-do loop.

Try out the following program.

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.

Two dimensional arrays

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

when they are called in the main program}

procedure InitTable(var ATable:Table);


var
i,j :Char;
begin{InitTable}
for i:= 'A' to 'F' do
for j:= 'a' to 'f' do
ATable[i,j]:= i+j;
end;{InitTable}

procedure ShowTableVals(var SameTable:Table);


var
i,j: Char;
begin
for i:= 'A' to 'F' do
for j:= 'a' to 'f' do
write(SameTable[i,j],' ');
{we can stick the chars with "+" to make a small string}
{strings can be written to screen}
end;{ShowTableVals}

var
TheTable: Table; {This is the variable that the procedures will use}

begin {main program}


InitTable(TheTable);
clrscr;
ShowTableVals(TheTable);
readln;
end.{main program}

When I first wrote this I defined the array thus:

Table = array['A'..'Z','a'..'z'] of string;

and got an error message.


Roughly how much memory would this take up?
There are 26x26 cells in the array, and each one would need 256 bytes.
Work out the total number of bytes required. Does it exceed 64K, which is the
maximum size allowed for static variables ?

Page: 15 of 15

S-ar putea să vă placă și