Real Pascal Programming Notes

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 38

Introducing Pascal programming

INTRODUCTION TO PROGRAMMING.
Definition
- Computer programming is the act of writing a program.
- A computer program is a sequence of instruction or statements into which a given problem is
reduced and that which is in a form the computer understands. The logic of the problem is actually
what is embedded in the computer executable statements.
- 4 basic operations performed by the computer are:-
1) Shifting operations
2) Comparing or testing operations
3) Calculating or computing
4) Jumping operations.
The logic to perform these operations are built into the hardware as logic circuits. Any problem must be
reduced into a form which makes use of these operations as building blocks.

Why Program?
The system is just an idiot, it operates on instructions given to it by the user and does not take initiatives
on its own.
Steps in programming
1) Problem definition: Complete and precise statement of the problem to be solved must be stated.
This is important because it serves as documentation since the program may have to be kept in a
library for others to use in your absence.
2) Analysis of the problem and modelling: this allows us to determine the complexity of the
problem and essential ingredients required to solve it; variables, constants etc, identify the input
and outputs, boundaries of the problem and a procedure for transforming the input to the output. A
model is an abstraction of the real problem and it defines the relationship between objects of the
problem space. They could be mathematical or logical.
3.1) Selecting or devising an algorithm: an algorithm is a procedure in that it is a finite set of
rules which give the sequence of operations for solving a specific type of problem. Its five
important features are:-
i) Finiteness: algorithm must terminate
ii) Definiteness: clear and unambiguous statements
iii) Input: specify what inputs are required
iv) Output: specify the number of outputs required#
v) Effectiveness: operations must be sufficiently basic and can be done in a finite and
reasonable length of time.

eg. Given a set of n numbers (x1,x2,x3,...,xn) device an algorithm for finding the mean of the set of numbers.

Solution: let S be the sum of the numbers, and i the index or counter.
- Start
- Step1: let S = 0.0 and i = 1 and store the values.
- Step2: read Xi
- Step3: Calculate S + Xi and store the value
- Step4: compare n and i, if n>i, add 1 to the current value of i and return to step2, otherwise go to
the next step.

1
Introducing Pascal programming
- Step 5: calculate the average Ave= S/n and store the value.
- Step6: print Ave as the value of the calculated mean.
- Stop.
Some notations used in Algorithm
1) Assignment Symbols
e.g Y X means assign the value of variable X to Y

2) Arithmetic symbols +, -, *, /,
X Y means XY
X 2 means X2
x * y means x times y

X/Y means

3) Logical symbols <, >, , , =

Y X means y is greater or equal to x.

4) Transfer Symbol GOTO


e.g Step1: X Y
Step2: X> 0? If YES GOTO step3 else GOTO step5.
Step3: Y Y–1
Step4: GOTO step1
Step5: Stop.
Now using these notations in our Average problem we have something like this:-
- Start
- Step1: let S 0.0 , i 1
- Step2: Read ( Xi)
- Step3: S S + Xi
- Step4: n > i, if YES , i i + 1 THEN GOTO step2 ELSE GOTO next step.
- Step 5: AVE S/n
- Step6: print (AVE)
- Stop.
3.2 Flowcharting

A flow chart is an effective pictorial representation which illustrates the logical and special steps in a
problem. It follows the steps in an algorithm to finish its task. The description of each step is shown by a
geometrical figure with instructions written inside, and the sequences in which the steps are to be
executed are indicated by arrow lines joining the appropriate figures.
Some common Flow Chart Symbols
Shape Name function
Oval shape To indicate Start and Stop
(terminals)
Diamond shape Decision symbol (is i > n ?)

2
Introducing Pascal programming
Data : input, output (Read or
Flow chart :Data symbol write)

Rectangle Processes or assignment


I 1, m s/n,

Small circle Flowchart connector.

Magnetic drum
Flowchart: magnetic disk

Magnetic disk Flowchart: Direct Access Storage

Flowchart: Storage Card

Flowchart: Manual Operations.

Using these symbols, let us draw a flowchart for the average problem.

START

S 0.0
I 1

Read Xi

S S + Xi

Is
N>i i i + 1
?

AVE S/n

3
Introducing Pascal programming

Print AVE

STOP

4 Coding the program: At this step, the half-English statements in the algorithm are transformed
into real computer codes.
5 Getting the program into the computer for a run:
This depends on the system in use.
- If it is card based, then the program is punched on cards and read into the computer.
- If it is key-to-disk, then we a keyboard is used to input the program.
At this stage, the computer takes over.
6 Documentation: since it is possible that others may want to use your program in your absence, it
is always necessary to properly document what you have been doing in the program. It starts from
the problem definition stage throughout all the stages discussed.

PROGRAMMING IN PASCAL

The Pascal programming language was developed in the early 1970s by Niklaus Wirth in Switzerland. It
is a general purpose high level language derived from ALGOL 60. It contains some unique features that
have been specifically designed that encourage structured designing, (an orderly discipline approach
towards programming that promotes clear and efficient error-free programs). Many educators and
professional programmers favour the use of Pascal over other general purpose languages.
The structure of a Pascal program:- Every Pascal program has a header and a block. This from the
main parts of a Pascal program. The header starts with Program () and is only one line long.
1) Header
2) Block
a. Declarations
-labels
-Constants
- Type
- Variable declaration
- Functions and Procedures
b. Statements
All components of the declaration part need not be present in any single Pascal program, but if present,
they must appear in the given order above.
Desirable program characteristics
1) Integrity: This refers to the accuracy of the calculations.
2) Clarity: refers to the overall readability of the program with particular emphasis on each
underlying logic. If a program is clearly written, it should be possible for other programmers to
follow the logic without undue efforts. One objective in the design of Pascal is the development of
clear readable program through a disciplined approach to programming.

4
Introducing Pascal programming
3) Simplicity: Clarity and accuracy are usually enhanced by keeping things as simple as possible. It
might be desirable to sacrifice a certain amount of computational efficiency in order to maintain a
relative simple straight forward program structure.
4) Efficiency: its concern with execution speed and effective memory utilisation.
5) Modularity: Most large programs cam be broken down to a series of identifiable subtask. Each of
these subtasks can be implemented as a separate program will do. This enhances the accuracy and
clarity of the program and it facilitates future program alterations.
6) Generality.
Planning a program It is essential that the overall program strategy be completely mapped out before
any of the details programming actually begins. In this way, the programmer can concentrate initially on
the general program logic without becoming logged down in the syntactical details of the individual
instructions. Such an approach an approach is referred to as TOP – DOWN programming
Another method is the BOTTOM – UP approach. This is useful for programmers that make use of
self contained program modules that would be accessed from other parts of the program. The bottom-up
approach is to first develop these program modules in details early in the overall planning process. Any
subsequent program development can then be based upon the known characteristics of these program
modules.
In practice, both approach are used (i.e bottom-up in developing module before the main program
block but top-down with respect to the development of each module. The main block will also be
developed using the top-down approach in most situations).

Pascal Data types


Data in Pascal are classified into different data types such that item belonging to the same data type can
be manipulated using the same operations and presented in similar ways both in Pascal programs and
inside the computer. The four standard data types in Pascal are: Integer, Real, Boolean and Char
(character).

Pascal Character set.


The characters consist of the alphabets, the numerals 0-9, the usual punctuation marks and a small
number of special symbols (characters).
The declaration
a: char; means that ‘a’ can be an alphabet, numeral or any special character.
A character constant consist of a character enclosed in single quote marks eg, ‘A’, ‘a’, ‘5’, ‘$’.
If a=’5’, and b=5, it does not imply that a=b. The quote marks are necessary so that Pascal will know for
instance that ‘+’ is a character constant rather than the addition sign or that ‘5’ is a character constant
rather than the integer 5.
String Constant: A series of characters such as a word or a sentence is known as a string. A string
constant is a series of characters enclosed in single quote mark, eg. ‘Examination Results’, ‘Mathias’.
Write and writeln statements
The statement write will cause the computer to print out information, eg write(1,2,3,4,5) will cause the
computer to print an output of the form 1 2 3 4 5, equally, the statements write(1,2); write(3); write(4,5)
and the statements
write(1,2)
Write(3)
Write(4,5)
Will all have the same output as the first statement.
5
Introducing Pascal programming
The writeln statement causes the printer to jump to the next line after the specified values have been
printed.
eg the statements, writeln(1,2); writeln(3); writeln(4,5) will have the following as output
12
3
45
Write statements can be formatted to specify the needed spacing. e.g write(1:5, 2:10), where 1:5 will
imply the digit 1 will occupy 5 spaces, equally 2:10 means digit 2 will occupy 10 spaces. Therefore if we
intend to print out the value of a=2.5, it will be written in Pascal as write (a:5:2) such that the output will
be 02.50. eg write(‘A’,’B’,’C’) will produce ABC as output, in case spaces are to be include, we write
(‘A’:4,’B’:4,’C’:4) the output here will appear as follows: A_ _ _B_ _ _C_ _ _

NB: In terms of characters, the computer prints them from left to right meanwhile in case of digits; it
prints them from right to left. Hence the statement write (1:5, 2:10) will have the following output. _ _ _ _
1_________2

Comment (* this is a comment*)


- Strings to be considered as comments are enclosed in * on some machines, others take comments
in single quotes as in (‘this is my first lesson’).
Example: Program First(Output);
 * this is our first program*
Begin
Writeln( ‘Good Day’);
Writeln( ‘This is our first program’);
Writeln(‘ We hope it will work’)
End.
Arithmetic Operators ( +, -, *, /, div, mod) ( div and mod are for integer arithmetic)
eg 11 div 3 = 3; 11 mod 3 = 2; 19 div 5 3; 19 mod 5 = 4;
That is we could have a div b; c mod d; where a, b, c, d are integer.
Declarations
Every Pascal program has a variable declaration part that lists each variable to be used in the program and
gives the data type of the values each variable can have.
Var x : real;
I : integer;
Where ever they appear in the program, the computer will consider x to be a real number and i to be an
integer. The following declarations are also allowed:-
Var i, j, k : integer; p: Boolean;
x, y, z : real; c :char;

The declaration section of the Pascal program is found between the HEADER and the STATEMENT
parts. That is
Program name(input, output);
Var x, y: real;
i,j: integer;
p: Boolean;

6
Introducing Pascal programming
c:char;
Begin
---
---
---
End.
Assignment: The assignment operator in Pascal is := and has the general form as
Variable := expression
eg X := 3.5;
y := 1.0;
z := false;
(In Pascal language, there is no restriction to variable name length; the only difference is that the first
eight characters must be different).
INPUT: The statements READ and READLN are used to input values from the standard input files.
eg a) READ(i,j,k) non formatted
b) READ(i:4,j:3,k:4) formatted
c) READ(i); READ(j); READ(k);
The statements (a) and (c) have the same effect.
READLN(i); READLN(j); READLN(k); will mean that the computer has to skip to the next line after
reading the value of i and so on.

CONSTANT DEFINITION: Pascal allows the use of an identifier to stand as a constant. At the constant
definition part, any number of identifiers can be defined to represent constant values during the running of
the program.

Eg Program name(input, Output)


CONST A = 5; C= ‘ FIRST PROGRAM’;
Var x, y: real;
I: integer;
Begin
---
---
---
End.
Example1: write a Pascal Program to compute the area A of a circle with radius R. The value for
should
be declared as a constant.
Solution:
Program Circle( Input, Output);
Const Pi = 3.14
Var radius, area: real;
Begin
Writeln(‘ Enter the radius of the circle’);
Readln(radius);
Area := PI * sqr(radius);
7
Introducing Pascal programming
Writeln(radius :10:3, area:10:3);
End.
Example2: write a Program in Pascal to compute the sales tax on a purchase and the total amount that
must be paid after the tax has been added to the purchase amount.
Solution:
Program tax (input, output)
Var amount, taxrate, decimalrate, salestax, totalpayment: real;
Begin
Writeln(‘Enter the purchase amount and the tax rate’);
Read (amount, taxrate);
Decimalrate := taxrate/100
Salestax := amount * decimalrate;
Totalpayment := amount + salestax;
Writeln(‘Amount of purchase:’ amount:8:2);
Writeln (Sales Tax rate:’ taxrate:4:1);
Writeln (‘Total to be paid:’ totalpayment:8:2);
End.
Some definitions:
1) Reserve Words: These are words with predefined meanings in Pascal programming
Language. Eg Begin, End, IF, Then etc.
2) Identifiers: these are names given to some program elements such as constants, variables,
procedures and programs. Eg Y12, Total, best etc.
3) Standard function: these are functions with predefined meanings in Pascal. Eg sqr, abs, etc etc.
4) Scope of identifier: This refers to the region within which an identifier is declared and hence can
be utilised.

Pascal Operator Priority.


For arithmetic expressions, the high priority operators are applied first followed by the low priority
operators. Operators with the same priority are operated from left to right order as they occur in the
expression.

High priority operators are : * , / , div , mod


Low priority operators are: + , -,

eg 1 9*5 + 7 div 3 ; ( multiplication and division)


45 + 2 ; addition
47
eg2 36/1.2 * 3.0 ; here we have to operate from left to right.
Note that the precedence rule may be altered by the use of parenthesis.

BOOLEAN EXPRESSION:
By a condition is meant a declaration statement that can be either TRUE or FALSE. A condition is
represented in Pascal Programming by a Boolean expression; that is an expression which yields the value
of either TRUE or FALSE.

8
Introducing Pascal programming
Relational operators are given a lower priority than any of the arithmetic operators. The general
classification is as follows: * , / , div , mod , + , - , = , < , > , <= , >= , <>.

Eg 3 + 5 < 4 * 2 – 1, multiplication is performed first.


3 + 5 < 8 - 1; addition and subtraction
8 < 7
FALSE.
Boolean operators NOT, OR, AND, take Boolean values as operands and yield values as results. The
priority of NOT is higher than that of any other operator. The priorities of AND and OR are the same as
that of arithmetic * and + respectively.

Priorities of arithmetic, Boolean and relational operators.


Operators Example: evaluate the expression (11 < 3 * 2 + 5) OR (6 * 2 = 4 * 3) AND NOT
(2 + 2 = 4)
NOT (11 < 3 * 2 + 5) OR (6 * 2 = 4 * 3) AND NOT (2 + 2 = 4)
* , / , DIV , MOD , (11 < 6 + 5) OR ( 12 = 12 ) AND NOT ( 4 = 4 )
AND ( 11 < 11) OR ( TRUE) AND NOT ( TRUE )
+ , - , OR (11 < 11) OR TRUE AND FALSE
= , < , > , <= , >= , FALSE OR TRUE AND FALSE
<>. FALSE OR FALSE
FALSE

Pascal Standard Functions:


These are functions that have already been programmed and the Pascal compiler already has a meaning
for them. Examples are:-
- Abs(x): stands for the absolute value of x
- Sqr(x): stands for the square of the value of x
- Sqrt(x): stands for the square root of the value of x.
- Sin(x): The sine value of x
- Cos(x): the Cosine value for x
- Arctan(x): this gives the inverse tangent value of x
- Exp(x): the exponential of x
- Ln(x): The natural logarithm of x ( that is logarithm to the base e of x)
- Odd(x): For an integer, the result is true if x is an odd number.
- Trunc(x): This will convert the real number x to integer by truncating the fractional part, eg trunc
(11.99) = 11.
- Round(x): This will convert a real number x to an integer by rounding the fractional part. Eg
round(1.7) = 2; round(5.45) = 5.
- Ord(x): The ordinal of number of x in the set of values defined by the type x.
- Chr(x): The character whose ordinal number is x.
- ALOG(x): log10 (x)

REPETITION STATEMENTS

9
Introducing Pascal programming
Pascal provides three statements to control repetition: The FOR statement, the WHILE statement and the
REPEAT until statement.

The FOR STATEMENT

This has the form:-


FOR i: = n1 to n2 do statement
FOR i: = n2 down to n1 do statement

eg FOR i := n1 down to n2 do eg3 FOR j := 1 to 5 do


eg FOR i := 1 to 5 do Begin Begin
Write (‘*’) S1; Read(j);
S2; Write(j:4);
The output will be ***** ......; End;
......;
.....;
Sn;
End;

Example: Write a program in Pascal that reads the length and width of an arbitrary number (N) of
fields and calculate their area and perimeter of each. The program should print the length,
width, area, perimeter of each field as well as the total area and total perimeter of all the
fields. Each variable should occupy ten spaces with three places of decimal.

Solution:
Program field (input, output)
(* Program to compute the area, perimeter, total area and total perimeter of an arbitrary
number of fields*)
Var
number, i : integer; length, width, area, perimeter, totalperimeter, totalarea: real;
Begin
Totalarea := 0.0; totalperimeter := 0.0;
Writeln(‘Lenght’:10, ‘Width’:10,’Area’:10,’Perimeter’:10);
Readln(number);
For i := 1 to number do
Begin
Read(length, width);
Area := length * width;
Perimeter := (length * width) * 2
Totalarea := total area + area;
Totalperimeter := totalperimeter + perimeter;
Writeln(lenght:10:2, width:10:2,area:10:2,perimeter:10:2);
End;
Writeln(totalarea:30:2, totalperimeter:10:2);
End.
THE WHILE STATEMENT:
10
Introducing Pascal programming
It is of the form:-

WHILE <Boolean expression> DO Statements; eg While <Boolean expression> Do


eg Program Segment Begin
--- S1;
--- S2;
I := 0 ---
WHILE i <= 20 Do ---
Begin Sn;
Write(i:4); i := i + 1; End.
end;
The output here will be of the form 0, 5, 10, 15, 20 but at this moment, the current value of i will be
25 such that if asked to write i, it will be 25.

The following predicates are particularly useful in connection with the “While” statement
ODD:- parameter is an integer; the value of odd(k) is true if K is odd.
EOF:- Parameter is a file such as input. eof(input) is true if no more data remains to be read.
EOLN:- Parameter is a line such as input. Value of eoln(f) is true if the end of the current line has been
reached.
eg
WHILE not eof(input) DO
Begin
Readln(Idnumber, Hours, Rate);
Wages := Hours * Rate;
Writeln( Idnumber:10, Wages:10:2);
end;
SENTINEL:-
A special value can also be given to the last data item. A data value used in this way is called a
SENTINEL. These are particularly useful when a file contains several sets of data to be processed, so that
the end of a set does not necessarily coincide with the end of the file.

NB: In a Pascal program, the sentinel appears under the Constant Definition section.

eg Program name;
Const
Sentinel = 999999
--------------
--------------
--------------
While idnumber <> sentinel do
Begin
---------
---------
End.

11
Introducing Pascal programming
The REPEAT statement
eg I := 0;
The general form is:- REPEAT
REPEAT Write(i:4)
Statements I := i + 1
UNTIL <condition> UNTIL i > 20;

Comparing the WHILE and the REPEAT statements

While <condition> DO statement REPEAT statement UNTIL <condition>

Statement

_ Condition

+ _ Condition

Statement
+

Example: Write a program in Pascal language that will read into the computer a series of values and
prints a warning message in case a value read is out of a predetermined range.

Solution. Program monitor (Input, Output);


Var low, high, value: real;
Begin
Readln(low, high);
While not eof(input) Do
Begin
Repeat
Read(value)
Until
Value > high or value < low
Writeln( value ‘is out of the predetermine range’);
End;
End.
Exercise:

12
Introducing Pascal programming
1) Write a program in Pascal programming language that will compute the sum of all the integers
from 1 through to 100.
2) Modify the program “FIELD” to use the predicate eof to determine when all the input data has
been read.
SELECTION STATEMENTS
a) ONE WAY SELECTION.
It is of the form:-
IF <condition> THEN statements.

eg IF i > 10 THEN S := S + 1;
# ------
While not oef(input) Do
Begin
Readln ( Idnumber, sales);
If sales > limit THEN
Writeln ( Idnumber:10, sale:10:2)
end;

b) TWO WAY SELECTIONS:


The general form is

IF <condition> THEN + _
Statement1 Condition? Statement2
Statement-1
ELSE
Statement-2

Consider writing a payroll program in Pascal Language that takes into consideration overtime hours
worked.
--- Program segment
(* Payroll program with overtime payment*)
While not eof (input) Do
Begin
READ(idnumber, hours, rate);
IF hours > 40.0 THEN
wages := 40 * rate + 1.5*rate*(hours – 40);
ELSE
wages := hours * rate;
WRITELN( IDnumber, hours, rate, wages);
end;

c) MULTIWAY SELECTION
It is of the form
IF <condition1> THEN statement1
13
Introducing Pascal programming
ELSE If <condition2 > THEN statement2
ELSE IF <condition3> THEN statement3
ELSE ------
------
ELSE IF <condition-n> THEN statement-n.

eg. If score >= 90 then grade: = ‘A’ Score grade that is:-
else if 80 <= score < 90 then grade :=’B’ 90 – 100 A
else if 70 <= score <80 then grade := ‘C’ 80 -89 B
else if 60 <= score < 70 then grade := ‘D’ 70 – 79 C
else grade := ‘F’ 60 – 69 D
0 - 59 F
- A program segment for this grading can be written as follows:-
:
:
While not eof (input) do
Begin
Readln( stnumber, score);
If score >= 90 then
Grade:= ‘A’;
else if score >= 80 then
Grade := ‘B’;
else if score >= 70 then
Grade := ‘C’;
else if score >= 60 then
Grade := ‘F’;
Writeln (stnumber: 10, score:10, grade);
End;

Assignment1:
Write a program in Pascal Language to read students scores and assign letter grades according to the
following scale:-
Scores 90 – 100 80 – 89 70 – 79 60 – 69 0 -59
Grade A B C D F

The program should keep track of the number of As, Bs, Cs, Ds and Fs. When all the grades have been
printed, the program should print a grade distribution giving the number of students who received each
grade.

THE CASE STATEMENT


The generalised selection statement is the CASE STATEMENT. The statement allows a program to select
on statement for execution out of a set of statements. It has the form
CASE e of
14
Introducing Pascal programming
L1: S1;
L2: S2;
: :
: :
Ln: Sn;
end;
Where e is the selector, S1, S2, ..., Sn are statements and L1, L2, ..., Ln are labels of the same type as
the selection expression e. If Si = Sj = ... = Sk, the notation Li, Lj, ..., Lk: S; is used.

eg. eg CASE grade of


CASE month of ‘A’: remark := ‘distinction’;
Jan, Mar, May, Jul, Aug, Oct, Dec: ending := 31; ‘B’: remark := ‘Credit’;
Apr, Jun, Sep, Nov: ending := 30; ‘C’: remark := ‘Merit’;
Feb: If year mod 4 := 0 Then ending :=29 else ‘D’: remark:= ‘Pass’;
ending:= 28; ‘ F’: remark := ‘Fail’
end; End;

example: Consider a real estate computation where the tax rate varies with the assessed value of the
property as follows:-
Assessed value < 5000000 5000000 - < 10000000 - < >= 15000000
10000000 15000000
Tax rate 3% 4% 5% 6%

Instead of the assessed value as the selector expression, we use a value computed from the assessed value.
We can map 1000000 assessed values into a single integer by dividing by 1000000. Then the CASE
statement will have the form category: = value DIV 1000000 and if category > 6 then category: =6.
Therefore the case statement will be of the form:-

CASE category of
0, 1, 2, 3, 4: rate := 0.03;
5, 6, 7, 8, 9: rate := 0.04;
10, 11, 12, 13, 14: rate := 0.05;
6: rate := 0.06:
end;
Assignment2:
Rewrite the score grading program using the CASE statement, further modify the program so that if the
score is outside the range 0 – 100, the computer should print the student’s id-number, the score and the
message ‘INVALID SCORE’.

FUNCTIONS AND PROCEDURES

Functions and Procedures allow programs to be constructed out of previously made parts. They perform
the same task as FORTRAN Functions and Procedures respectively.

A FUNCTION is defined using s function declaration which appears immediately after variable
declaration of the program. It has the form
15
Introducing Pascal programming

FUNCTION name (var1: type, var2: type,..., varn: type): type;

Following which is a sequence of statements that describe the operations to be performed on the input
data when the function is executed.

Its characteristics

1) A function is accessed by specifying its name within an expression as though it were an ordinary
variable followed by an optional list of parameters.
2) The function name can be followed by an optional list of parameters. These parameters are used only
to transfer information to the function from its reference point.
3) The function will return a single data item. This data item will be represented by the function name
itself.
4) A function must be of correct data type for the expression in which it is accessed.
5) A function must have a Begin and an End. The result is communicated back to the main/ calling
program by assigning a value to the function name itself. There is no FULL STOP at the end of a
function subprogram.

Program name (input, output);


Var v1, v2: type;
Function name( var1:type, ..., varn: type): type;
Begin
----
----
End;
Begin (* Main program*)
----
end;

Example: Suppose we want to write a program that uses a function subprogram to calculate the
volume of cuboids in Pascal language. Let the program be able to calculate the volume of n cuboids using
a function subprogram.

Solution:
Program Box(input, output)
Var i, n: integer; length, width, height: real;
Function vol(l, w, h: real): real;
Begin
Vol := l * w * h;
end;
Begin (* Main program*)
Readln (n);
For i := 1 to n do
16
Introducing Pascal programming
Begin
Readln( length, width, height);
Writeln(length:10:2, width:10:2, height:10:2, vol(length, width, height));
end;
end;

PROCEDURES
A procedure is a self contained program structure that is included within a Pascal program. A procedure
can be referenced by simply writing the procedure name followed by an optional list of parameters. The
parameters must be enclosed in parenthesis and if they are many, should be separated by commas. When
a procedure is referenced, the control is sent automatically to the beginning of the procedure and after its
action statements have been executed the control is returned immediately.

Each procedure has its own header and block and is declared as follows:-

Procedure name (var list: type, var1: type, var2: type,..., varn : type);

eg Procedure areas(l, w: real; var a, p: real);


It appears after variable declaration in the program. It has the following characteristics:-
1) A procedure is accessed by a simple statement consisting of the procedure name followed by an
optional list of parameters.
2) The parameter may represent information supplied to the procedure or under certain conditions,
information returned by the procedure.
3) Any number of data items can be transferred between a procedure and its reference point (i.e the
statement that accesses the procedure).
4) Procedures subprogram are used to perform a set of operations which might return several values
or take some other action such as printing a message to the user.

Example: Write a program in Pascal programming language which uses a procedure subprogram to
calculate the area and perimeter of a series of fields.
Solution: Program areas( input, output);
Var
Length, width, area, perimeter: real;
Procedure rectangle (l, w: real, var a, p: real);
Begin
a:= l * w; p:= ( l + w) * 2;
end;
Begin (* Main Program*)
While not eof(input) do
Read(length, width);
Rectangle(length, width, area, perimeter)
Writeln(length:10:2, width:10:2, area:10:2, perimeter:10:2);
end;
end.
TYPE CONCEPT IN PROGRAMMING

17
Introducing Pascal programming
In a high level programming language, the concept of type is of central importance. With each variable,
constant and expression having a unique type associated with it. In Pascal the association of a type with a
variable is made by its declaration. In FPRTRAN, it is deduced from the initial letter of the variable. In
the implementation of the language, the type information determines the representation of the values of
the variables and the amount of computer storage which must be allocated tom it. Type information also
determines the manner in which arithmetic operators are to be interpreted. The concept of type has the
following characteristic:-
1) A type determines the class of values which may be assumed by a variable or expression.
2) Every value belongs to one and only one type.
3) The type of a value denoted by any constant, variable or expression may be deduced from its form
or context without any knowledge of its value as computed at run time.
4) Each operator expects operands of some fixed type delivers results of some fixed type (usually the
same). While the same symbol is applied to several different types this symbol may be regarded as
ambiguous denoting several actual operators, such ambiguity can only be resolved at compile
time.
5) The properties of a value of a type and of a primitive operation defined over them are specified by
means of a set of axioms.
6) Type information is used in high level language both to predict and detect meaningless
constructions in a program and also to determine methods of presenting and manipulating data to
the computer.

DATA TYPES IN PASCAL


Date types are classified into simple, structured and pointer types.
The simple types are those whose values cannot be broken down into simpler components.
The structured types are those whose values can be broken down into simpler components.
The pointer types are those whose values are used to locate data items in the computer memory.
SIMPLE DATA TYPES
(i) Scalar Data Type:- they are the four standard data types i.e. Integer, Real, Boolean and Char.
(ii) Data type Definition:- Pascal allows the definition of a new type beyond the standard ones
whose definition are built into the language.
That is:-
TYPE
FIXED = integer;
FLOAT = real;
BIT = Boolean;
CHARACTER = char;
Var
I, j, k: FIXED; p, q: BIT;
X, Y, Z: LOAT; c: character;
(iii) User Defined Scalar Type: - Pascal allows a programmer to define new scalar types by listing
all possible values of each type. For example a programmer could define scalar types as
follows:-

TYPE
Day = (Sun, Mon, Tue, Wed, Thu, Fri, Sat);
Month = ( Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct Nov, Dec)
18
Introducing Pascal programming
Grade = (F, E, D, C, B, A);
Color = (Red, Blue, Yellow, Black);
Begin,
----
----
----
d := Wed;
-----
------
End.

The TYPE declaration comes before the var declaration.


e.g. TYPE
Day = (Sun, Mon, Tue, Wed, Thu, Fri, Sat);
Month = ( Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct Nov, Dec)
Grade = (F, E, D, C, B, A);
Colour = (Red, Blue, Yellow, Black);
Var
I: integer; d: day; score: grade; clr: colour

The order of various declaration and definitions in a Pascal program appear as follows:
- Program declaration
- Constant definition
- Type definition
- Variable declaration..
- Functions and Procedures
This is then followed by executable statements enclosed within a BEGIN and an END.

SILIENT CHARACTERISTICS OF PASCAL


(1) It is a block structure language
(2) It is a recursive structure language
(3) Array handling is free from storage implication
(4) It can handle strings and list
(5) Arrays can be built from second structures e.g Record.day :1..31
(6) No dynamic storage allocation
(7) There is an explicit introduction of sequential data structures called files
(8) It offers a new richness of the expression set
e.g day:=1—31;
week := 1 – 4;
month:= Jan – Dec;
set=(day, week, month);

BLOCK STRUCTURING
Some languages include means of delimiting the scope of names in a program. An important technique
for achieving this is known as block structure originally introduce with ALGOL 60
The essential syntactic features of block structures include a system of brackets for delimiting
regions or blocks of program text and the method of indicating the use of selected names within the

19
Introducing Pascal programming
blocks. Blocks are delimited by begin --- end, brackets in Pascal or Algol or by PROCEDURE---END or
BEGIN---END statements in PL/1. The use of names is denoted by declarations associated with each
block.
The rules for the scope of names in block structured language are:-
(1) The scope of names include the block in which it is declared but not any block surrounding it.
(2) The scope of a given name includes any block contained within its associated block, however if the
same name is used in a declaration within such block, a new meaning for the name is thereby
introduced. In addition to the syntactic importance of blocks, they also have considerable syntactic
implication since in programming, variables are associated with storage. An advantage of block
structure is that it leads to an efficient technique for storage handling .The fact that the variable is
known inside the block but not outside it means that storage for variables in a block need only to be
allocated when the block is entered, and may be released when the block is passed. The use of storage
has been extremely valuable in implementing program e.g language the technique is known as
dynamic storage allocation

Some more advantages of block include:


(1) The rules for name scope allow the composition of large programs from small fragments without
fear of name clashes.
(2) It is possible to design efficient run-time schemes for dynamic storage allocation based on the
scope of rules on block structure.

Some difficulties and disadvantages of block structure arise from those points where programming and
logic differs.
In programming, here is often the need to go outside of the framework of the hierarchy structure
implied by nested blocks. An example is the need to introduce a variable which will persist after the block
in which it is declared is terminated .It is not always possible to achieve this effect by declaring the
variable in a surrounding block.

STRENGH OF PASCAL
(1) Powerful data structuring facilities arrays, type, set, record etc
(2) Its compound statement portion or Pascal block enables the execution of statement sequentially from
top to bottom.
(3) Block structuring in Pascal allows big programs to be built and testing or debugging such big
AREAS OF STRONG APPLICABILITY
Pascal is widely used as a language reflecting the importance of data management, enabling the program
to deal more efficiently with processing and managing data. Because of its wide data structuring facility it
is used both in science and engineering. For the same reason it is used in data processing dept and most
often used as technique tool in universities and colleges.
N.B One big weakness of Pascal is that it has no separate compellability in procedures.

SCALAR AND SUBRANG TYPE


Scalar type: The basic data types in Pascal are the scalar type. Their definition indicates an ordered set of
values by enumerating the identifiers which denote the values.

The general form is: - type <identifier> = (<identifier>, <identifier>);

20
Introducing Pascal programming
e.g type colour =(white, red, blue, yellow, purple green, orange, black);
Note that for a type definition, in the type declaration part of a program, the type appears only once.
e.g type
Colours = (white ……………...black);
Sex = (male, female);
Day = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday)
Months= (January, February, march, April, May, June, July, August, September, October, November,
December );

It is ambiguous to declare things like; Work days= (Mon..Sat) because it is not necessary that Saturday is
working day everywhere.
Note that in Type Boolean = (false, true);
This automatically implies that the standard identifiers True and False indicate that False is less than
True.
Note also that the rational operator =, <>, <,>=<=,>=and >are applicable in all scalar type provided that
both
Co-operands are of the same type. The order is determined by the sequence in which the constants are
listed.
e.g type day=(Mon..Sun);

We can say Mon < Wed, but not Mon < red.

The order of occurrence of declaration appearing in a program is as follows


1) Constant declaration or definition.
2) Type definition
3) Var, declaration.

e.g program pref (input, output )


Const N=20
type
Colour= (white, red, black);
Day= (Monday..Friday);
var
X,Y,Z: real;
K,N: integer ;

STANDARD FUNTIONS WITH ARGUMENTS OF SCALAR TYPE .

The standard functions need to locate specific components in a scalar type are:
SUCC(X) for Successor (X); or successor of x components
PRED(X) for predecessor of the component X
ORD(X) for ordinal or positional number of X

e.g following the declaration;

21
Introducing Pascal programming
TYPE
colour:=( white, red, blue, green, yellow, purple, orange, black); we would have the following:-

SUCC (blue):=yellow
PRED (blue):=red
ORD (blue):=2. (We start numbering from 0)

Note; the ordinal number of the first component is zero such that the ordinal number of the 2nd element
becomes 1 etc, etc

Therefore ord (X) =ord(pred) +1.


- Ord(pred(blue)=1
- Ord (succ(blue)=3
- Ord (pred(succ(red)=1
- Succ(pred(ord(red)))=there is no predecessor of 1.

SUBRANGE TYPE
Any type may be defined as a subrange of any other already defined type called its associated scalar
type; The definition of a subrange simply indicates the least and thee largest constant value in the
subrange where the lower bound .

The general form is:-

Type <identifiers>=<constant>...<constant >;

A subrange of type real is not allowed.

Example:-

TYPE
Days= (Mon, Tues, Wed, Thu, Fri, Sat, Sun); {scalar type}
Work days =Mon..Fri; {subrange of days}
Index =0. .63; {subrange of integer}
Latter=`A’. .`Z’; {subrang of charts}

Var days in months: integer;

Suppose we wish to declare a variable say days in months days which means total number of days in
a particular month as Var days in months :integer; The declaration is possible and quite acceptable
but there could be some problem when entering the actual data(days in months) into the computer.
It is possible that one enters -999, which is acceptable by earlier declaration but definitely will give
wrong results.

To avoid this, since we know that the possible values are 28, 29, 30 and31 ie 28...31, Pascal allows us
through its subrange facility to make declaration like the following:-

22
Introducing Pascal programming
days in month 28..31;or days in months:28..31 of integer.{we have it of the form identifier: X..Y;}

ARRAYS
Scalar and subrange types are unstructured type , but all other types in Pascal are structured e.g
Array, Record ,File, set etc are structured .
-Structured types are compositions of other types eg a: array [1..n] of integer;
It is the type of the component and the structuring method .ie (packed or unpacked) that characterize
the structure type.
THE ARRAY TYPE
An array type consists of a fixed number of components where all are of the same type called the
component or based type. Each component can explicitly be denoted and directly accessed by the
name of the array variable followed by its index in square brackets.
The time required to select or access a component does not depend upon the value of the index, hence
the array is termed a RANDOM ACCESS STRUCTURE.
e.g You can select the last component in a 1st execution. The definition of an array specifies both the
component type and the index type.
The general form is name: array (min…max) of TYPE, where
1) Name is the array variable name
2) Array is the key word which specifies the component type or data type
3) Min and max are the min and max subscript range respectively.
4) TYPE is the type of index or subscripts.
e.g
Count: array (1…4) of integer;
Suppose we have a type defined as type months= (Jan, Feb…….Dec) a table of day in each month
can be defined as follows.
DAYS –IN-MONTH: array (months) of 28..31;
DAY IN MONTH [Jan]:=31.
Before this we must have defined months above in our program.

Program to determine Rainfall.


Segment:
Type months = (Jan, Feb… Dec);
Var
Month: months; {or integer or real or character.}
Total: real;
Rainfall: array [months] of real; {or of integer, or 28-31}
Begin

23
Introducing Pascal programming
(* to determine amount of rainfall from April to September *)
Total: =0;
Month: =April
While month <= Sept do
Begin
Total:=total + rainfall [month];
Month:= succ (month)
end;
end.

POSSIBLE ARRAY DECLARATION

1) Summer rainfall; array [Jan..Aug] of real;


2) Yearly rainfall: array [1900..1999] of real;
3) Car count: array [char] of integers;
4) Lines: array [1..120] of char;

Note that the array declaration come in the var definition part.

MULTIDIMENSIONAL ARRAYS

e.g a matrix is a two dimensional array. Suppose you have M x N matrix you can declare
Var a: array[1…m, 1…n] of integer; or
a: array[1…4, 1…3]of integer for a 4x3 matrix.

e.g marks Stud M101 M102 M103 M104 M105 M106 --- M
1 37 40 50 6 73 80 57
2 20 0 100 90 45 62 73
-- ----- ------ ------- ------- ------- ------- --------
-- ----- ------ ------- ------- ------- ------- --------
-- ------ ------ ------- ------- ------- -------- --------
--
N 65 80 60 50 44 52 77

Note that the students are in arrays as well as marks and papers or subjects are all in arrays.
1st method
A: array [1..M] of 0..100;
S: array [1..N] of integer;

1st method of declaring such arrays


Mark: array [..N] of array [1..M] of 0..100;
2nd method.
Mark: array [1… N, 1…..M] of 0….100;
Now to locate a component, we have,
Mark: array [No of stud, paper]….;

24
Introducing Pascal programming
If we have mark [2], this implies that, the set of marks obtained by student 2 .The computer will give all
the marks of student 2 i.e. row 2 marks i.e. 20, 0, 100, 90.
For such access as
Mark [2, 4] implies the mark of student 2 in paper 4, in this case, the answer from our table is 90.
Exercise
Write a program to perform matrix multiplication of any two matrices.

PACKED ARRAYS
An array element occupies a unit computer store. To economies storage, Pascal provides facilities for
packing several elements of an array into a single location. As a consequence, a packed array containing
up to 10 elements may be treated as a single string variable (for example output, assignment and
relational statements).
Array packing is utilized by including the reserved words PACKED ARRAY , in the type or variable
specification.
The genera form is
Var
array name: PACKED ARRAY[index 1 type…..index n type] of type.

Pascal includes two standard procedures. Pack and unpacked, that are used to convert unpacked arrays
into packed arrays and vice- versa.

The syntax (command):- Pack (unpacked array name, index, packed array name); where index refers to
the first element of the unpacked array to be transferred.

Var unpacked: ARRAY [1..20] of char;


Packed: ARRAY [1..20] of char;
The statement
Pack (unpacked, 1, packed); will cause each element of unpacked, starting at position 1 to be
transferred to the corresponding location within packed.
Packed [1]:= unpacked [1];
--------
-------
Packed [20]:=unpacked [20];

The standard procedure unpack will transfer the element of a packed array to an unpacked array:-
Unpacked (packed array name, unpacked array name, index);
Var packed: PACKED ARRAY [1….13] of char;
Unpacked: ARRAY [1...20] of char;
The statement
Unpacked (packed, unpacked, 5); will result in the assignment
Unpacked [5]:=packed [1]
…….
......
Unpacked [17]:=packed [13]
Example: rewrite the integer sum program using an array of 50 real numbers.
Program SUM in Pascal Program SUM in FORTRAN

Program sum(input ,output); Program sum (input, output …….)

25
Introducing Pascal programming
Var sum: real; Dimension A(50)
n, i : integer Sum=0 ,
a:array [1…50]of real; read(5 ,*)n
Begin Do 20 I =1,n
Read (n); sum:=0 Read (5,30) A(I)
For i =1 to N do Sum=sum +a(I)
Begin 20 continue
Read (a[i]); Write (6,40) sum
sum:=sum + a[i] 40 format (2x, F 5.2).
end; 30 format (3I)
Write (sum); Stop
End. End.

NB The PRED and SUCC are not used for arrays.

Example: write a program in Pascal to read an array of real values and write out all the negative values
and their positions in the array.

Program segment to print –ve numbers in Pascal Program to print –ve numbers in FORTRAN

Program negative(input, output) Dim A(50)


Var i, n: integer Do 1 I = 1, N
A: array[1..n] of real; If(a[i].ge.0) goto 1
begin Write(6x, I, a[i])
For i :=1 to n do 1 continue
Begin Stop
Read a[i] End
If a[i]<0 then
Write(‘position =’ i:4 , a[i] : 10:2);
End;
End.

Eg: Program to look for the min and max of an array a=( a1, a2, ..., an)

Program segment in Pascal Program segment in FORTRAN


Read min, max
Min:=[a1]; max:=a[1] Min=a(1) and max=a(1)
For i=2 to n do Do 2 I =2,N
If min>a[i] then min:=a[i] If (min –a(i))1,1,3
If max<a[i] then max :=a[i]; 1 if (max-a(1))4,2,2
Written (min, max) 4 max =a(i)
End. Go to2
3 min= a(i)
2 continue.

Function average (var (a: array[1..100])of real; count: integer);


Using the above function declaration write a program to calculate the average and the deviation from the
average.
26
Introducing Pascal programming
SOLUTION
Program averages (input, output)
Var
Function average ()
Begin
------
End;
Begin(*main program*)
---------
End.
Assignment: Write a program that will read a table of real numbers and store them in a two dimensional
array, calculate the sum of the numbers in every row and every column and then write out the table along
with the calculated row sums and column sums.
Solution.
Program table (input, output)
Var row ,col:1…11
n row, n col :1…10
table :ARRAY[1..11, 1..11] of real
Procedure rowsums ( Begin ......... end)
Procedure columnsums (begin ... end)
Procedure readinput (begin ... end)
Procedure writeoutput( begin .. end)
Begin (* main program *) readinput; rowsums; columnsums; writeoutput; end.

SEARCHING AND SORTING

Searching and sorting are two operations frequently carried out on arrays. Searching is finding the
position of a given value in an array. Sorting is arranging the component of an array into some desired
order.
SEQUENTIAL SEARCH
To read a value and search for its equivalence in an array of numbers, eg. a: array [1..100] of integers; this
can be done using the following procedure:-

------ Alternatively we can write


var
size, vfind, i: integer; found: Boolean; Program(input, output)
Begin Var
i=1; a[size +1]:=vfind; I:0..N; found: Boolean;
while a[i] <>vfind do. a:array[1…N]of integers;
i:=i+1 vfind: integer;
found :=(i<=size); Begin
if found then I:=0,; found:=false
writeln(‘item is found’) repeat
Else i:=i+1; found :=(a[i]=vfind
Writeln (‘item not listed’) until found or (i=n).
Write(found); End.
End.
BINARY SEARCH
It is used for searching in an ordered array; i.e. in a sorted set.
Procedure for binary search, with an array say a[1000] is given as follows:-
27
Introducing Pascal programming

First := 1; last := size;


Repeat
Mid := (first + last)div 2;
If (vfind <a[mid]) then
Last := mid – 1
If (find > a[mid]) then
First := mid+1
Until
Vfind := a[mid] OR (first > last)
If first <last then
Begin
Found := true
Position := mid
End;
Else found: =false
End.
Home work. A telephone directory is stored into a computer. Write a program to read in the directory,
then read names and print the corresponding phone number. The directory has the form:-
Names phone number
Name 1 +237 76551063
Name 2 +237 96023235
The program should use a sequential search procedure and the following declarations.

Name: PACKED ARRAY (1…..20) of char;


Phone_ number: PACKED ARRAY [23776551063 . . 23796023235] of integer.

SORTING
The common types of sorting include, Bubble sorting; shell sort and quick sort.
- Procedure for sorting
List :array [1….500]
For i :=1 to size -1
if list [i] > list[i+1] then
temp:=list[i];
list[i]:=list[i+1]
list[i + 1] := temp
# For i := 1 to N
# For i := N down to 1
Example: Write a program to perform bubble sort on an array with an arbitrary number of entries.
Complete procedure for bubble sort.
Program sort (input, output)
Var
Limit, i, temp ,size: integer;
List: array[1..size] of integer;
Begin
For limit:=size Down to 2 Do
For i=1 to size -1 Do
If list [i]>list[i+1] THEN
Begin
temp :=list[i]
list[i]:=list [i+1]
list[i+1]:=temp

28
Introducing Pascal programming
end;
End.

SEARCHING AND SORTING.


Searching and sorting are two operations frequently carried out on array. Searching is finding the position
of a given value in array. Sorting is arranging the component of an array into some desired order. Sorting
is usually done to aid latter searching.
A one dimensional array of integers can be searched for a given value by first declaring the following
variables.
List: Array [1….100] of integer;
Size, vfind, i : integer;
Found: Boolean;

Where the component list [1] through list[size] hold, the list to be searched while list [size +1] through
list [100] are currently unused. It is required that there be at least one unused component.
With a starting value of i equal to1 the entries on the list are examined one after the other. If a particular
entry equal vfound, then the search is stopped. These could be represented by any of the following control
statements:
(i) i:=1
While list [i] <> vfind Do
i:=i+1.

OR

(ii)
i:= 0
REPEAT
I:= I +1
UNTIL List[i] = vfind;

Some way to keep the program from running off the end of the list if it does not find the value being
sought is required. One way of doing this is by storing the value of vfind in the first unused component,
such that
list [size +1]:= vfind
which acts like a sentinel.
After the repetition stops, one has to determine whether the value was on the part of the list
currently in use or whether the search was stopped by the sentinel. This can be done by evaluating the
Boolean expression
I <= size.
Taking statement (ii) above can be expanded to search list for a value vfind. If the search is successful,
then when it is over the value of found is true and i is less than or equal to size. Otherwise found is true
and i is equal to size+1

i:=0;
found:=false;
list[size+1]:=vfind;
Repeat
i:=i+1
found =list [i]=vfind

29
Introducing Pascal programming
Until <found>

Exercise: Design an algorithm for the binary search method.

EFFICIENCY OF SEARCHING ALGORITHM

The sequential search algorithm can be seen to be of order n i.e O (n) where n is the length of data to be
searched.
With each comparison for the binary search algorithm , the list under consideration is halved. The
list will therefore be 1/2, ¼, 1/8, 1/16, ..... its original size. These can be represented by saying that the
greatest possible number of comparison will be K where K is defined as the first integer value such that
2k >= n or K>= log2n
Thus the order of the binary search algorithm can be given as
O(log2n)
this means for instance that, for a list of 50,000 items, sequential search would in the worst case require
50,000 comparisons while the binary search would require not more than log2 50,000 or about 16
comparisons. This represents an improvement factor of about 3000.

STRUCTURE TYPES: RECORDS

A record is a structure type consisting of components of different types. The formal declaration of a
record type is:-
TYPE
Record name= Record
1st component: type;
2nd component: type;
3rd component: type;
.....
......
last component: type;
end;

It can also be declared as a variable ie


Var
Record name= Record
1st component: type;
2nd component: type;
3rd component: type;
.....
......
last component: type;
end;
The field identifiers by which record components are referenced cannot be computed at execution time
but must be specified when the program is written.

Example:
TYPE
Weather = Record
Sky: (clear, cloudy, partly cloudy);
Precipitate: (rain, snow, sheet, hail, none);
Low, high: real;
End;

30
Introducing Pascal programming

Where weather is the record type defined. The identifiers sky, precipitate, low, high is the field identifiers
that can be used to refer to the components of the type weather. Following the type declaration weather,
the following available declarations might follow:-

Var
U, V, W: weather; where U is a record of the form
U Cloudy
rain
30
50
Suppose C1, C2, ...,Cn are components of a record C. The record component s are accessed by the dot
notation.

C.C1 first component


C.Cn lastt component
U.sky Cloud
y
U.precipitate rain
U.low 30
Ile. U.high 50
If we want to refer to a particular datum in the record, we can declare as U.low = 40. If all the data is
required, we just write V:=U, this will mean that
V.sky U.sky
=
V.precipitate U.precipitate
=
V.low U.low
Eg Given a student record defined by
=
TYPE
V.high U.high
Stdrecord = RECORD
=
Name: alpha, {array [1..20] of char;]
Age : integer;
Sex : (male, female);
Year-of-study :[1..5];
end;
Example:
Write a program in Pascal programming language that will read a file containing students records and
determine if the student with the following description in on the file.

Identifier Student Student 2 Student


fields 1 3
Name Ali Rose Peter
Age 20 18 21
Sex Male Female Male
Year of 2 1 3
study
(Any of the students can be used for illustration)

Solution: Var stud: student;


Program search(input, output); Begin
31
Introducing Pascal programming
TYPE For i := 1 to 80 Do
Line = packed array[1..80] of char; Read(stud[i]);
Student = RECORD; If(name=Ali) and (age = 20) and (sex = male) and
Name: line, or array[1..20] of char;
(year-of-study = 2) THEN
Age: integer;
Sex: (male, female); writeln(‘student is found at position’, i:4) Else
Year-of-study: [1..5]; writeln (‘student is not in the file);
end; End.
The WITH Structure
The general format is
WITH recordname DO statements
In which any reference to an element within a specific record need not include the record name.
eg
WITH Student DO
If(name=Ali) and (age = 20) and (sex = male) and (year-of-study = 2) THEN .......
Exercise

Example: Given a data type


Complex = Record
i, r:real
End and
Variable X, Y, Z: complex
It is intended for x.r to be the real part value of x and x.r the imaginary part.
Write the following procedure
Sum (x, y,z) sets, z equal to the sum of the complex numbers x and y
Diff (X.Y, Z)
Prod (X.Y, Z)
Quot (X.Y, Z)

STRUCTURED TYPES: FILES

A file is any sequence of items where the items may be either structured or unstructured e.g. may
be a file of character, a file of integer, a file of record or a file of array. There are two kinds of files;
sequential and direct access. The value in a sequential file can only be accessed in the order in which
they are stored in auxiliary memory. The values in a direct access file can be accessed in a direct access
file can be accessed in any order designed by the programmer. Standard Pascal supports only sequential
files.
A file is defined as any other variables in the type or variable declaration section. A general form
of declaring a file is given by
Var
File name: file if type
Or in a type declaration given by
TYPE
File name: File of type
Followed by an appropriate variable declaration, declaring other files of kind filename. A file integer for
instance can be declared as follows:-
32
Introducing Pascal programming
TYPE
Data= file of integer
Var
F: data
A file has infinite cardinality that is, it may contain any number of components, including zero. The
following are simple file definition.
Var
Symbols: file of char;
This defines a file in which each of the file components is a simple, Char type data.
TYPE table =array (1..50, 1..20) of real;
Var
Data: file of table
This defines a file in which each component is a two dimensional real array
Type Status = (current, overdue, delinquent)
Account = record
Cust name: packed array (1….80) of Chari
Cust no: 1….99999;
Cust type: status;
Cust balance: real;
End;
Customer= file of account.
Var
Old customer, new customer, customer, creating and reading a file are accomplished by means of
the procedures REWRITE, RESET, GET and PUT. Writing or accessing individual data items within a
file are accomplished by means of a file buffer. Suppose a program includes the definition of a file called
data, then the corresponding file buffer will be called data .If the components of data are records, the data
will represent one such record.
The procedure statement
REWRITE (F)
Assigns an empty file to the file variable (f) or if the file already exist with the given name, then
all information within the existing file is erased and the beginning of the new file is established, after the
necessary data items have been assigned to the buffer, the information is transferred to the file by means
of statement procedure PUT. Repeated execution of the statement
fdata items (file components)
Put (f)
Will cause a sequence of data items written to the file f in the name order as they are (recall)
Example 1: The following program creates a file called data that contains simple type components.
Programs create file (input, output, and data).
Var
Data: file of rest;
Items: real;
Count vital: integer;
Begin
Write (how many values will be entered);
Reading (total);
Rewrite (data);
33
Introducing Pascal programming
For count: = 1 to total DO
Begin
Readln (item); data =item; put (dark);
End;
End: A file from which information is to read must be initiated by a RESET statement. i.e. RESET (f).
The procedure statement
GET (F)
Moves buffer to the next component of the file. The expression eof (f), Is false as long as the file buffer is
positioned over a component of the file.
Example 2: the following control statement computes the sum of the values in a file of integer.

Var f: file of integer;


Begin
Sum=0, reset (f)
While not eof (f) do
Begin
Sum= sum+ f ; get (f);
End;
End:
Example 3:- The program below causes the component of a file called old file to be applied to another
file called new file.
Solution: - program :( new file, old file);
TYPE
Account = record
Custro:1…..9999
Oldbalance: real
New balance:real
Payment: real
End;
Var
newfile, oldfile: file of account;
Begin
RESET (oldfile);
REWRITE (newfile);
While not eof (old file) do
Begin
Newfile : = oldfile
get (oldfile); put (newfile);
end;
End:
Exercise: Suppose the file class is declared as follows:-
type student=record
id :pack array (1…..90) of chari;
name: pack array (1…..40) of chari
grade :integer
34
Introducing Pascal programming
end
var class: file of student
suppose that two classes are to be combined we want to merge the files class1 and class2 into a single file
class 3, where class 1, class 2, class 3, file of student. The records of class 1 and class 2 are in ascending
order according to the values of the id-field and class 3 should be likewise. Write a Pascal program to
perform the merge.

SETS

In Pascal a set is defined as a collection of ordered simple data items that are all of the same type.
It is defined over any scalar type ( integer, character, enumerated data item) and may contain up to 59
items.
The general format for defining a set is by just defining the base type of form.
TYPE base type = (data, item1,.., data itemn) or
TYPE base type=first data item..last data item;
This is followed by defining the set type in terms of the base type.
Set type = set of base type;
And finally a set of type variable is declared ie
Var set name: set type;
Or
Var set name1, set name2,…..setmane n; set type;
TYPE sizes = (small, medium, large);
Shirtsize= set of sizes;
Var short sleave, longsleeve: shirtsizes;
E.g. TYPE letterset = set of ‘A’…’Z’
Var v, w, x, y, z; letterset
Type numbers= set of integers
Type digit= set of 0…..9;
To indicate set constant, square brackets are used
X= (‘A’, ‘B’, ‘C’);
V = (‘A’, ‘B’, ‘R’, ‘Z’); W = (‘A’, ‘E’, ‘O’, ‘I’ ‘U’);
Y=(), Z:= (‘I’, ‘N’,);
Shortleeve:= (Small)

SET OPERATIONS
There are three different operations that can be applied to set to yield new sets.
+ = set union
- = set different
*= set intersection.

EgV: = w+x (‘A’, ‘B’, ‘C’ ‘E’, ‘O’, ‘I’ ‘U’)


V: = w-x (‘E’, ‘O’, ‘I’ ‘U’)
V: = w*x (‘A’)
Four relational; operations can be used with sets form biclear –type operations;
= set equality
35
Introducing Pascal programming
<> set inequality
< = set inclusion > = set exclusion
e.g( small, large) True
( small, large, medium) = ( small, large) True
( small, medium) < = ( small, large) False
Another useful set operator is the set membership IN Set Membership
It is used to avoid complex Boolean-expression
Eg if (C = ‘F’) OR ( C ≤ ‘Z’) WE CAN WRITE C IN ( ‘A’…’Z’)

(* program that counts the frequency of occurrence of the punctuation characters . , ; = - ( ) [ ] on a line
of text *) ie C = (. , ; = - ( ) [ ] ) begins.

Segment count: = 0
Punctuation: = ( ‘.’ ‘,’ ‘;’ ‘=’ ‘-‘ ‘(‘ ‘)’ ‘[‘ ‘]’ )
While not eoln do
Begin
Read ( c ); write ( c );
If C in punctuation then count : = count + 1;
End
Write/n; write/n ( number of occurrences of punctuation character = ; count) ;
End
Exercise: Read in a file of characters and develop a frequency count of all alphabets characters contained
in the file. The output of the program shall be a report in the following format.

Letter Frequency count Percentage

A Xx xx.xx

B Xx xx.xx

. . .

. . .

Z Xx xx.xx

Total alphabetical Xxx 100.00


character

POINTER TYPES
The variable declared when a program is written and remains in existence throughout the
execution of the block in which they are declared are called static variable. Through the value of these
variables can be changed as the program executes. No program statement can create a new static variable
or destroy an old one.
The Pascal compiler can recycle, disposed of memory location and reuse them when new
variables are created. Variable that are created or disposed off as the program executes are called
Dynamic variables.
POINTER TYPE DATA

36
Introducing Pascal programming
Pointer type data are used to construct dynamic structure data type, the routine that creates a
dynamic variable returns the address of the memory location allocated. Such a memory address is called
a Pointer. (It is an address or reference to a data structure).
Pointer variable are declared in the following form.

TYPE type name = base type

It it is an integer, we don’t need type


Eg P :integer ^ integer
Integer or integer is the data type whose values are pointer to integer variables and red or ^ red.
The declaration P:integer specify that the value of P is a pointer to the variable itself. P is
followed by an upward arrow ( )
P the varaible pointed to by the value of P
P P

Dynamic variables can be created and development by standard procedures.


New ( P ) creates a dynamic variable
Dispose (P ) destroy
The statement new ( P ) creates a dynamic variable is assigned to the variable P.
P

The procedure dispose ( p ) destroys the variable pointed by P and returns the space just realised
to some variables space for future use.
The statement P : nil is the case that the value if P does not point to any variable. Therefore P is
meaningless when the value of P is nil
Student = record
Name: packed array ( 1..20) of char;
Grade: integer
Link: student
End;
Var First Student
Name

Grade

link link

A procedure that reads in a series of student name and build a linked list of students’ record.
Var
P, q : student
i: integer
Begin (* creates headings *)
New (P)
First: = P;
While not eof (input) do
37
Introducing Pascal programming
Begin
New (q): (* creates a new record*)
P link : = q ( * link new end of list *)
P : = q ; (* points to new end of list*)
For i: = 1 to 20 do
Read (P ; name (ij) ;readln ;
End;
Plink : nil ( * link if list record is nil * )
End

38

You might also like