Real Pascal Programming Notes
Real Pascal Programming Notes
Real Pascal Programming Notes
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
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)
Magnetic drum
Flowchart: magnetic disk
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).
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
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.
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 , + , - , = , < , > , <= , >= , <>.
REPETITION STATEMENTS
9
Introducing Pascal programming
Pascal provides three statements to control repetition: The FOR statement, the WHILE statement and the
REPEAT until statement.
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:-
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;
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.
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;
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.
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 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
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.
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);
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.
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 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.
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 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.
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 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
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
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 .
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}
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.
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.
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;
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.
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
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.
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
Eg: Program to look for the min and max of an array a=( a1, a2, ..., an)
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:-
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.
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>
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.
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;
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.
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.
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.
(* 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.
A Xx xx.xx
B Xx xx.xx
. . .
. . .
Z Xx xx.xx
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.
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