Pascal Programming Study Notes KSM
Pascal Programming Study Notes KSM
PASCAL PROGRAMMING
BY
DWASI G
©2019
Table of contents
Table of contents .......................................................................................................................... I
INTRODUCTION TO PASCAL................................................................................................. 1
THE STRUCTURE OF A PASCAL PROGRAM ...................................................................... 1
(a) The Pascal character set...................................................................................................... 1
(b) Reserved words .................................................................................................................. 2
(c) Identifiers ............................................................................................................................ 2
(d) Standard identifiers ............................................................................................................ 2
(e) Numbers ............................................................................................................................. 2
(f) String ................................................................................................................................... 3
(g) Data types ........................................................................................................................... 3
(h) Constants ............................................................................................................................ 3
(i) Variable ............................................................................................................................... 4
(j) Expressions ......................................................................................................................... 4
(k) Statements .......................................................................................................................... 4
SIMPLE TYPE DATA ................................................................................................................ 4
OPERATORS .............................................................................................................................. 5
(a) Arithmetic operators ........................................................................................................... 5
(b) Logical operators ................................................................................................................ 6
(c) Relational Operators ........................................................................................................... 6
(d) The assignment statement .................................................................................................. 6
ORDER OF PRECEDENCE ....................................................................................................... 7
STANDARD CONSTANTS ....................................................................................................... 8
STANDARD FUNCTIONS ........................................................................................................ 9
DATA INPUT & OUTPUT ....................................................................................................... 10
(a) The read statement ........................................................................................................... 10
(b) The readln statement ........................................................................................................ 10
(c) The write statement .......................................................................................................... 10
(d) The writeln statement ....................................................................................................... 10
CONTROL STRUCTURES ...................................................................................................... 11
SELECTION .......................................................................................................................... 11
II
III
SEARCHING ............................................................................................................................. 37
a)Linear Search ...................................................................................................................... 37
b) Binary Search .................................................................................................................... 38
DATA STRUCTURES .............................................................................................................. 40
(a) Sets ................................................................................................................................... 40
(i) Defining a Set Type ....................................................................................................... 40
(ii) Constructing a Set ........................................................................................................ 41
(iii) Operations with Sets ................................................................................................... 42
(b) Stacks ............................................................................................................................... 43
(i) Introduction ................................................................................................................... 43
(ii) Operations of stack ...................................................................................................... 44
(c) Queues .............................................................................................................................. 45
(i) Introduction ................................................................................................................... 45
(ii) Operations on Queue ................................................................................................... 45
(d) Linked Lists ...................................................................................................................... 47
Double linked Lists ............................................................................................................ 49
(e) Binary trees ....................................................................................................................... 50
(i) Introduction ................................................................................................................... 50
Binary Tree Traversal ........................................................................................................ 51
RECORDS ................................................................................................................................. 54
a) Defining a record ............................................................................................................... 54
b) Processing a record ............................................................................................................ 57
c) The with structure .............................................................................................................. 57
d) Declaration of records using arrays .................................................................................. 58
FILES ......................................................................................................................................... 59
a) Introduction ........................................................................................................................ 59
b) Defining of a file................................................................................................................ 60
c) Creating a file..................................................................................................................... 60
d) Reading a file ..................................................................................................................... 62
e) Updating a file ................................................................................................................... 62
TEXT FILES .............................................................................................................................. 64
IV
INTRODUCTION TO PASCAL
Pascal is a general –purpose, high level programming language that was derived from ALGOL-
60. It‟s instructions are made up of algebra like expressions and certain English words such as
BEGIN, END, READ, WRITE, IF, THEN REPEAT, WHILE , DO. Pascal was designed to
encourage the use of structured programming.
Pascal was named in honour of Blaise Pascal (1623-1662), the brilliant French scientist
and mathematician whose many accomplishments include the invention of the world‟s first
calculating machine.
Pascal was originally developed in the early 1970‟s by Niklaus Wirth at the Technical University
in Zurich, Switzerland. Wirth‟s original idea was to develop a disciplined, high level language
for teaching structured programming. Pascal is widely used in in America and Europe both as a
teaching language and as a powerful general purpose language for a variety of different
applications.
(c) Identifiers
An identifier is a name that is given to some program element, such as a constant, variable, a
procedure or a program. Identifiers are comprised of letters or digits. In order to except that the
first letter must be a letter. Both upper and lower case letters are permitted and are considered to
be indistinguishable.
(e) Numbers
Numbers can be written in several different ways in Pascal. In particular a number can include
assign, a decimal point and an exponent. The following rules apply to all numbers.
1 Commas and blank spaces cannot be included within the number.
2 The number can be preceded by a plus (+) or a minus (-) sign if desire. If aa sign
does not appear the number will be assumed to be positive.
3 Numbers cannot exceed a specified maximum and minimum values. These values
depend upon the type of number, the particular computer and the particular compiler
being used.
a. Integer number
An integer number contains neither a decimal point nor a exponent.
b. Real number
A real number must contain either a decimal point or an exponent (or both). If a
decimal point is included it must appear between two digits
(f) String
A string is a sequence of characters (i.e letters, digits and special characters) enclosed by a
apostrophes. Both upper cae and lowercase letters can be used.
Example „red‟ „dit 05‟, „3453‟
(h) Constants
It is often convenient to associate a simple data item, such as a numerical value or a string with
an identifier, thus providing a name for the data item. The identifier is called constant if the data
item is assigned permanently (constant must always be defined before it can appear in a Pascal
statement)
Const name= value
Name is an identifier that represents the constant name and value is the actual data item that is
assigned to a name.
Example
Const fraction = 0.1667
(i) Variable
An identifier whose value is allowed to change during the execution of a program is called
variable. Every variable must be individually declared (i.e. define) before it can appear in a
program.
The general form of a variable declaration
Var name : type if they are several then
Var name1, name2, - - - -- - - -namen; type
Name1, name2 --- namen are identifiers that represents individual variables and type refers to
the data type of the variables
Example var row,col:integer;
Value :real;
Flag:char;
(j) Expressions
An expression is a collection of operands (i.e. numbers, constants, variables etc) joined together
by certain operators to an algebraic term that represents a value (i.e. simple data item). There are
two types of expressions in Pascal: A numerical expression and Boolean expressions. A
numerical expression represents a numerical value where a Boolean expression represents a logic
condition which is either true or false.
(k) Statements
A Pascal statement is an instruction or a group of instructions that causes the computer to
carryout certain action. There are two basic types of statements in Pascal : simple and structured.
Simple statements are essentially single unconditional instruction that perform ano of the
following tasks
1. assign a data item to a variable (this is called assignment statement)
2. access a self-contained computational module called a procedure
3. transfer program control unconditional to another part of the program(The goto
statements
OPERATORS
Operators make it possible for you to manipulate data of the same type. Visual FoxPro operators
can be grouped according to the following data types
Collectively, the operators that are used to carry out numerical type operations are called
arithmetic operators. There are six arithmetic operators that can be used in Pascal
INTEGER TYPE REAL TYPE DATA
DATA
Operator Purpose Type of Type of Type of Type of
operands resultant operands resultant
+ Additions Integer integer Real Real
- Subtraction Integer Integer Real Real
* Multiplication Integer Integer Real Real
/ Division Integer Real Real Real
DIV Truncated Integer Integer N/A N/A
division
MOD Remainder Integer integer N/A N/A
after division
The assignment statement is written in the form variable: = data item. A data item can be a
single item (e.g a constant, another variable or a function reference) or it can be an expression.
The data item must however be of the same type as the variable to which it is Assigned example
The statement causes the value of the expression 3.14 x sqr (radius) to be assigned to the variable
area.
ORDER OF PRECEDENCE
An expression can sometimes become quite complex, because of the presence of multiple
operators within an expression. The order in which these operations are carried out is
Procedure Operators
1(Highest) NOT
2 X/DIV MOD AND
3 + - OR
4(LOWEST) = < > < < = > > = IN
NB Sometimes it is a good idea to use parentheses to clarify an expression even though the
parentheses may not be required.
The following grammatical rules must always be observed when constructing numerical &
Boolean expressions
1. The resultant will be positive if both operands are of the same sign. Otherwise the
resultant will be negative.
2. The two division operators (/ & DIV) and the MOD operator require that the second
operant be non zero
3. Use of the DIV operator with a negative operand will result in truncation toward zero. i.e
The resultant will be smaller in magnitude than the true quotient
4. Undefined identifiers cannot appear within an expression (In other words, each identifier
must be assigned a value before it can appear within an expression)
5. Proceeding an identifier with a minus sign is equivalent to multiplication by -1 thus – a x
b is equivalent to -1 x a x b
6. Arithmetic operators cannot appear consecutively. Hence, the expression a x –b is not
allowed but a x (-b) is permitted
7. Arithmetic operations cannot be implied expression 2 (x + y) is incorrect, but the
expression 2x (x + y) is valid.
8. Arithmetic operation cannot be carried out on char or Boolean type data therefore
expression such as „A‟ + „B‟ and (n>0) + (n<20) are not allowed
NB
STANDARD CONSTANTS
Pascal includes three standard identifiers that represent constants. They are Maxint, False or
true. The first of these maxint, specifies the largest value that may be assumed by an integer-
type quantity. False and True represent the two values that may be assigned to a Boolean-type
data item (Note false and True represent an ordered set with false preceding true)
STANDARD FUNCTIONS
Pascal also contains a number of standard function (i.e Intrinsic or built functions)
The read statement is used to read data items from the input file and assign to integer real or char
– type variables. The statement is written as
Read(input variables)
Where the input variable are separated by commas (note that Boolean type variable cannot be
included in the list of input variables)
Examples
Read(a);
Read(a,b,c)
The data items are read from the input file and assigned to their respective variables in the same
order that they are stored. Each variable must be of the same type as its corresponding data item.
10
CONTROL STRUCTURES
SELECTION
The If Structure
The if structure is a conditional control structure that allows some action to be taken only. If
agiven logical condition has a specified value(either true or false ). This structure has two
different forms.
Syntax
If Boolean expression then
Statement
The statement part of the structure will be executed if and only if the boolean expression is true.
If the boolean statement is false, then the statement part will be ignored.
Examples
IF status=’s’ THEN
11
Tax:+0.2*pay
ELSE
Tax:=0.14 *pay;
IF circle THEN
BEGIN
Readln(radius);
Area:=3.14*sgr(radius);
Writeln(‘area of cicle=’,area)
END
ELSE
BEGIN
Readln(lenth,width);
Area:=length*width;
Writeln(‘area of rectangle=’,area)
END;
NB
The IF statement is used in conjunction with boolean expressions, the value of which is either
true or false.
Nested Selection
When if statement are embedded one another they are said to be nested. If is
recommended that each IF-THEN- ELSE. Statement is terminated with the comment {endif}.
The most general form of nested loops
The CASE structure is a conditional control that allows some particular group of statements to
be chosen from several available to groups
The general form CASE structure
12
CASE EXPRESSION of
CASE Labell list 1 : Statement 1
CASE Labell list 2 : Statement 2
CASE Labell list 3 : Statement 3
.
.
.
CASE Labell list n : Statement n
Else
END;
The expression can be any simple type expression other than real. It often takes the form of a
single simple type variable. Each of the case labels represents one of the permissible values of
the expressions. Thus if the expressions is of type integer, the case labels would represents
integer values that fall within the permissible range. The statement can be either simple or
structure.
Example1
CASE choice OF
‘R’: writeln((‘RED’);
‘B’: Writeln(‘BLUE’);
‘W’:writeln(‘WHITE’);
ELSE
Writeln(‘BLACK’);
END;
Example2
CASE trunc(x/10) OF
1:y:=y+5;
3,5: y:=y-2
6: y:=2*(y+1)
2,4:;
9:y:=0
END;
Example 3
CASE operator OF
‘+’: Result:=a+b;
‘-’: Result:=a-b;
‘*’: Result:=a*b;
‘/’: Result:=a/b;
Else
Writeln(‘Error operator not value’);
END;
13
In writing computer programs it is often necessary to repeat part of a program a number of times.
This is achieved through the use of repetition control structures.
14
digit :=1;
REPEAT
Writeln(digit);
Digit:=digit+1;
UNTIL DIGIT>20;
Is used to carryout unconditional looping I Pascal. This structure allows action to be repeated a
specified number of times. The syntax is
FOR control variable: =value1 to value 2 DO
Statements
The statement part can be simple or structured. This statement will be executed for each several
consecutive values assigned to the control variables. The number of values assigned to the
control variable therefore determines the number of times the statement will be executed. The
control variable must be simple type variable of any type other than real.
The statement will be executed (valu2-value1+1) times
Example
BEGIN
WRITELN(‘input hourly rate pay=>’);
READLN(rateofpay)
FOR counter:= 1 to 5 DO
Begin
Writeln(‘Input a number of hours=>’);
Read(hoursworked);
Grosspay:=hoursworked*rateofpay
Writeln(‘Gross weekly wage is’,grosspay);
END
{EndFor}
When the statement FOR counter := 1 to 5 D is executed, counter is initially set to 1 after the
initial executed of the code between BEGIN and END; the computer increase the value of the
counter by 1 and tests whether the new value of the counter ha exceeded the final value of 5.
Example 2
FOR digit:= 1 to 20 Do
Writeln(digit)
This second form of FOR structure is similar to the first except for the use of the key word
DOWNTO in the place of TO thus FOR structure can be written as
15
Each statement label must be declared before it can be utilized within a program (Remember
Label declaration must preceed the constant and variables declaration)
Example
PROGRAM sample;
LABEL 100, 200,300;
CONST factor=0.5;
Var a,b,c:Real ;
Labeled statements are written in the form
Statement label : statement
Example
10: readln(a,b,c)
20: For counter :=1 to n DO
Begin
.
.
End
A program may contain several different GOTO statements that transfer control to the same
palce (i.e. to the same remote statement) within the program.
Example
Program sample(input,output);
16
LABEL 10;20;
Var…..
BEGIN
.
.
.
10: READLN(A,B,C);
.
.
IF A<-0 then
GOTO 20;
.
.
GOTO 10
.
.
IF flag THEN
GOTO 20
20: WRITELN (X,Y,Z);
.
.
.
.
END
In general program of this type must be avoided. Some care must be exercised when using
GOTO statement. Control can be transferred out of or within a compound statements and control
can be transferred to the beginning of a compound statement. However control cannot be
transferred into compound statement. Moreover if control is transferred internally to the END of
a compound statement (i.e. if the keyword End is labeled) then the label must be preceded by an
empty (null) statement. This is accomplished by placing a semicolon after the statement that
proceeds END ;
Example
17
any special declaration that are unique to the procedure. When all action statements have been
executed control is immediately after the procedure reference.
Each procedure has it‟s own header and block. The header is written as
18
PARAMETERS
The use of parameters offers a better approach to the exchange of information between a
procedure and its referenced point. Each data item is transferred between actual parameters
which is included within the procedure reference and corresponding formal parameter which is
defined within the procedure itself. When the procedure is accessed the actual parameters replace
the formal parameters thus creating an information exchange mechanism between the procedure
and it‟s reference point
Example
PROGRAM sample([Link]);
VAR a,b,c: Real;
PROCEDURE flush(x,y:real);
Begin
.
.
(*Process the values x,and y*)
.
.
End
Begin(*Main program action statements*)
.
.
.
Flush(a,b,);
.
.
Flush(c,d);
.
.
.
End
X,y – Formal parameters within the procedure . The first procedure reference causes the values
of the actual parameters a and b to be transferred to the formal parameters x and y. this process is
then repeated in the second. This process is then repeated in the second procedure statement this
time transferring the values of c and d to x and y. the values. The values of c and d are thus
passed to flash where they are processed accordingly.
The following rules must be observed when using parameters
1. The number of actual parameter in the procedure reference must be same as the number
of formal parameters in the procedure definitions.
2. Each actual parameter must same type as its corresponding formal parameter.
3. Each actual parameter must be in a manner which is consistent with sits corresponding
formal parameter as determined by the class of formal parameter.
19
TYPES OF PARAMETERS
FUNCTIONS
A function is a self contained program structure similar to a procedure, however a function
is used to return a single simple –type value to its reference point.
The function itself consists of a function header and a block.
General form/syntax
FUNCTION name; type or
FUNCTION name(formal parameters): type
Example
Program factorial;
(* this program uses a function to calculate a factorial of a given integer*)
Var x:integer;
FUNCTION factorial(n:integer):integer;
20
21
Type name = (data item1, data item2 ,….., data item 2);
Where name is the name of the enumerated data type and data item1 data item2 are actual data
items.
Example1
Type day =(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
Var offdays:day;
Since enumerated type data are defined in an ordered sequence, relational operators may be
applied to them to form Boolean expression. Also the standard function pre and succ may be
used to determine which data items precede or succeed any data item
using example 2 above
Expression Value
Sun< tue True
Wed >= sat False
Mon <> fri True
Pred(fri)= thu True
Succ(fri)=sat True
Succ(tue)<> pred(thu) False
22
b) Subrange
A sub-range refers to some portion of the original range of an ordered simple data. Sub-range
type are the data items that fall within this sub-range, thus forming a subset contiguous ordered
data. The original data is referred to as the host data type.
The sub range concept can be applied to any set of ordered simple data. This includes previously
defined enumerated data as well as three of the standard types i.e integer, char, Boolean.
The general form
Type name first data item.. last data item
Where
Name is the name of the sub-range data type .
First data item is the first of the ordered items within the subrange
Last data item is the las of the ordered data items
Examples
type day =(sun, mon, tue, wed, thu, fri, sat);
weekdays =mon..fri.
month =1..31;
caps =‟a‟..‟z‟;
var workdays,holidays: weekdays;
dayofthemonth: month;
hoursworked: 1..24;
grosspay,netpay: real;
employment: 1..999
case workdays of
mon: writeln(„the first work day‟);
tue: writeln(„the secondwork day‟);
wed: writeln(„the third work day‟);
thu: writeln(„the fourth work day‟);
23
end;
24
ARRAYS
Is a structured type data which is referred to by a single identifier. In many situations sets of data
items such as set of examination for a class may be conveniently arranged in to a sequence. An
array becomes easier to use in this case. Individual data items in an array are often called
elements.
There are three types of arrays
a) One dimensional array
b) Two dimensional array
c) Multi dimensional array
List[1]
List[2]
.
List = .
.list[n]
25
26
d)Packed arrays
some types of arrays can be defined so that they can utilize the computer‟s memory more
efficiently by “packing” the data items close together. This feature allows a greater quantity of
information to be stored in a given amount of memory.
Example
Var list : packed array[1..4] of char
This feature is most effective with array elements of type char, boolen or enumerated or with
sub range type data. Storage economy gained by packing may offset by loss of computing speed.
27
SORTING
Sorting is the process of rearranging an initially unordered sequence of records until they are
ordered with respect to all of or that part of each record designated as its key. Usually desired
result is that the records be placed in ascending order.
At least five considerations may influence the choice of an internal sorting algorithm:
1. Running time: How long does it take to sort n records and by what factor does this time
increase ib order to sort 2n records?
2. Memory space: Do main memory limitations force choice of an algorithm that sorts “in
place”(only one or two record spaces are needed beyond the space needed to hold n
records), or are there an additional n record spaces available beyond the space needed to
hold the data to be sorted?
3. Initial order: are the records known to be already ordered with just a few exceptions?.
This is not the usual situation algorithm may well be one that is not at all efficient when
the initial order of the records is essentially random.
4. Key range: Do record keys span a very large range or possibly only a very restricted
range (such as integers 0 to 999). Certain algorithm applicable to keys of narrow range
are not feasible for keys that span a large range.
5. Programming language: For reasons of availability, must a particular programming
language be used if so, does that language support recursion since many of the most
efficient internal sorting algorithms are most naturally expressed recursively.
a) Selection sort
Selection sort involves looking thro all n records to find the one with smallest key, then thro the
remaining n-1 records a to find the one of the next smallest key, etc. by exchanging each record
of successively smaller key with appropriate record at the top of the unsorted sequence of
records, the records can be sorted in place, the length of the sorted sequence at the top growing
gradually longer as the length of the unsorted sequence at the bottom shrinks to zero. Selection
sort is slow. Selection sort is suitable for few records. Another advantage of this algorithm is that
records of successively larger key are identified on one by one, so that output of the sorted list
can proceed virtually in parallel with the sort itself.
Example
APASCAL PROGRAM FOR SELECTION SORT.
program sorting;
var k,i,max,maxpos,temp:integer;
28
list:array[1..6]of integer;
begin
writeln(' enter numbers to sort');
for i :=1 to 6 do
read(list[i]);
for k:= 1 to 5 do
begin
max:=list[k];
maxpos:=k;
for i:=k+1 to 6 do
if list[i]>max then
begin
max:=list[i];
maxpos:=i;
end;
temp:=list[k];
list [k] := list[maxpos];
list[maxpos]:=temp;
end;
for i :=1 to 6 do
write(list [i], ' ');
end.
b) Bubble sort
Bubble sort is is based on obvious idea on the simplistic notion that if two adjacent records are
out of order they should be exchanged. If this is done to successive (overlapped) record pairs,
from the first thro the record pair that starts at the (n-1)st position, the original list will not
necessarily yet be sorted, but one can be sure that the record of the largest key (assuming an
ascending order sort) will have reached the end of the list. Then by repeating the process n-2
more times, the entire list is certain to be sorted. Successive phases of the sort are called passes.
Bubble sort is also known as exchange sort. Like selection sort this algorithm is very slow.
The idea of bubble sort is just comparing all the data. The first data is compared to the second, to
the third, and so on until the end of the data. Then the second data compared to the third, to the
fourth, so on. Then the third data to the fourth and so on ... and so on.
Why it is called as the Bubble sort. It is because that the comparison and the swapping make the
desired data to gradually come up like a bubble. Example : Suppose we have data like this
29
5 3 8 4 1 7 6 2 (unsorted)
Follow the algorithm -- i.e. comparing the first and the second data : 5 and 3. 5 is greater than 3,
hence it must be swapped out
3 5 8 4 1 7 6 2 (1st step)
Then the first and the third. Since 3 is smaller than 8, no swapping is necessary. Then the first
and the fourth : No swapping either. The first and the fifth -- since 1 is smaller than 3, it must be
swapped :
1 5 8 4 3 7 6 2 (4th step)
And so on, till the end of data, the sequence remains the same. Then the second with the third --
no changes this time. The second with the fourth. Change must be done :
14853762
then becomes :
13854762
And so on :
1 2 8 5 4 7 6 3
1 2 5 8 4 7 6 3
1 2 4 8 5 7 6 3
1 2 3 8 5 7 6 4
1 2 3 5 8 7 6 4
1 2 3 4 8 7 6 5
1 2 3 4 7 8 6 5
1 2 3 4 6 8 7 5
1 2 3 4 5 8 7 6
1 2 3 4 5 7 8 6
12345687
Finally, sorted : 1 2 3 4 5 6 7 8
You see that smaller data comes up like bubble and bigger data sank down gradually, as you may
note the 8. That's why this method is called bubble sort.
Example
A PASCAL PROGRAM FOR BUBBLE SORTING
program bubblesort(input,output);
{program that uses bubble sort to sort numbers in an
array}
const maxnum=8;
30
var
sort:array[1..maxnum]of integer;
sorted:boolean;
i,pass,temp:integer;
begin
writeln('enter the number to be sorted');
for i:=1 to maxnum do
read(sort[i]);
writeln('unsorted data');
for i:=1 to maxnum do
write(sort[i],' ');writeln;writeln;
begin
pass:=1;
repeat
sorted:=true;
for i:=1 to maxnum-pass do
begin
sorted:=false;
if sort[i] > sort[i+1] then
begin
temp:=sort[i];
sort[i]:=sort[i+1];
sort[i+1]:=temp;
end;
end;
pass:=pass+1;
until sorted;
writeln;
writeln('sorted data is');
for i :=1 to maxnum do
write(sort[i],' ');
readln;
end;
readln;
end.
31
c) Insertion Sort
The insertion sort algorithm is likely to occur to anyone who is playing cards by simply holding
them in the hand and inserting them one by one into the proper position in the stack or hand of
already sorted items. In the computer version room has to be made for insertion of the records at
the top of the list necessitating movements of all records in the partially ordered list down by one
position. But whenever a record is encountered whose key is larger than that of the last one in the
partially ordered list, it merely needs to be appended to the list. Insertion sort is done using the
same list by letting the partially sorted list at the top of the combined sequences gradually
displace the diminishing list of the unsorted records stored directly underneath.
Procedure InsertionSort(varA: list;n:integer);
{ sorts the n numbers of A, where type list = array[1..
limit]}
Var I,j,k,t,: integer;
Begin
For i:= 2 to n do
If A[i] < A[1] then
Begin
t:=A[i];
A[i]=A[1];
A[1]:=t;
End
For j:=1 to n-1 do
Begin
T:=A[j+1];
K:=j;
While A[k] >t do
Begin
A[k+1]:=A[k];
K:=k-1;
End;
A[k+1]:=t
End
end
d) Quick Sort
This is a fast sorting algorithm that sorts a list of n elements in O(nlogn) time. The method is
used as follows. One element is chosen as the partitioning element (central value). The elements
are partitioned into two sub list. Exchanges are performed so that all the elements to one side are
smaller than or equal to it and all the elements on the other side are greater the or equal to it.(One
contains the elements that are smaller than the partitioning element and the other contains
32
element larger than the partitioning element.). This should produce two lists of equal length.
Each of this is partially sorted in a similar way. In turn each of the four lists are sorted in similar
way and so on. It is sometimes referred to as partition exchange sort
Example
Program quicksort(input,output);
Const max=1001;
Var
A:array[1..max] of integer;
I:=integer;
N: integer;
Procedure quicksort(l,r:integer);
Var I, j, piv,t:integer;
Begin
If l<r then
Begin
I:=l+1;
J:=r;
Piv:=A[l];
Repeat
While A[i] <=piv do
I:=i+1;
While A[i] > piv do
J:=j-1;
If i<j then {exchange items pointed to by I
and j}
begin
t:=A[i];
A[i]:=a[j];
A[j]:=t;
End;
Until i>j;
[now two final replacements finish a partition]
A[l]:=A[j];
A[j]:=piv;
Quicksort(l,j-1);
Quicksort(j+1,r);
End;
33
End;
Begin
Write(„Enter number of integers to be sorted‟);
Readln(n);
For i:= 1 to n do
Read(a[i]);
A[n+1]:=maxint;
Quicksort(1;n)
For i:= 1 to n do
Write(A[i]:5);
Writeln;
End.
e) Merge Sort
Merging is an information processing technique similar to that of sorting that makes no sense
except when applied to two (or more) lits that are already separately in order. To merge such lists
then means to intersperse their elements to form one overall output liost that is entirely in order.
The merging algorithm can be stated in pseudocode as:
While{still more unmerged items in either list} do
Begin
If A is empty take the next item from B, else
If B is empty take the next item from A, else
Take the smaller of the two at the heads of list A and B
End;
In the course of being merged, each number in each list is processed only once. This means that
the running time needed to merge two lists of size m and n will be proportional to m+n.
Program merge(input,output);
{program that reads in two lists ordered numbers A and
B and merges them into C}
Const al=7;
Bl=9;
Cl=16;
Var A: array[1..al] of real;
B: array[1..bl] of real;
C: array[1..cl] of real;
Begin
For i=:= 1 to al do
Read(A[i]);
34
For j:=1 to bl do
Read(B[j]);
I:=1; j:=1; k:=1;
While (i<=al) and (j<bl) do
If A[i] <B[j] then
Begin
C[k]:= A[i];
I:=i+1;
K:=k+1;
End
Else
begin
C[k]:= B[j];
J:=j+1;
K:=k+1;
End;
While i<=al do
Begin
C[k] :=a[i];
I:=i+1;
K:=k+1;
End;
While j<=bl do
Begin
C[k] :=a[i];
j:=j+1;
K:=k+1;
End;
35
For i:= 1 cl do
Write(C[i]:6:0);
End.
f) Shell Sort
This is a sorting algorithm resembles the bubble sort algorithm. The only difference between
them I that in this method successive elements are not compared and exchanged instead,
elements at a distance d are compared and exchanged if the second is smaller than the first.
The initial value of d is in n/2 location where n is the number of elements in the list. After one
iteration is over the value of d is reduces by half. This is continued until the list is sorted. The
sorting order decided by the user is encoded in the variable order.
Example
PASCAL PROGRAM FOR SHELL SORT
program shellsort;
const maxnum=8;
var
shell:array[1..maxnum]of integer;
p1,p2,p3,p4,temp,i,d:integer;
procedure datain;
begin
writeln('input numbers to be sorted');
for i:=1 to maxnum do
readln(shell [i]);
end;
procedure swap;
begin
p3:=p1-d;
p4:=p1;
temp:=shell[p1];
shell[p1]:=shell[p2];
shell[p2]:=temp;
while(p3>0)and(shell[p3]>shell[p4]) do
begin
temp:=shell[p3];
shell[p3]:=shell[p4];
shell[p4]:=temp;
end;
end;
36
procedure perform;
begin
repeat
begin
p1:=1;d:=trunc(d/2);
p2:=d+p1;
repeat
if shell [p1]>shell[p2] then
swap;
p1:=p1+1;
p2:=p1+1;
until p2> maxnum;
end;
until d=1;
end;
procedure dataout;
begin
writeln('sorted data is');
for i:=1 to maxnum do
write(shell[i], ' ');
end;
begin(*main block*);
d:=maxnum;
datain;
perform;
dataout;
readln;
end.
SEARCHING
Searching for an element in a list is the process of checking if a specified element is present in
the list and determining the location of the desired element. There are mainly two types of
searching algorithm namely
a) Linear Search
b) Binary Search
a)Linear Search
Is a searching technique also known as sequential search algorithm, given a list the elements are
scanned from the first one till either the required element is found or the list is exhausted. The
37
elements do not have to be in any specific order. The advantage of this method is its simplicity
however the method is inefficient when the number of elements is large.
Example
(i) Linear search
program linearsearch(input,output);
var a: array[1..5] of integer;
elem,i,n: integer;
found:boolean;
begin
writeln('enter the number of elements in the array');
readln(n);
for i:= 1 to n do
read(a[i]);
readln;
write('enter the element to be serached for ');
readln(elem);
i:=1;
while (not found) and (i<n) do
begin
if (a[i] = elem) then
found := true;
i:=i+1;
end;
if found then
writeln('element found at position
',i-1:2)
else
writeln('element not found in the
list');
end.
b) Binary Search
Binary search algorithm is used to search for an element in a sorted list. The search is conducted
as follows. The value of the element in the middle of the list is compared with the value of the
element to be searched for. If the middle element is smaller, them the desired element has to be
in lower half of the list. If the middle element is larger, the desired element has to be in the upper
half of its present. The number of elements to be searched is reduced by half in every iteration.
Example
Binary Search
38
program binary_search(input,output);
var a :array[1..50] of integer;
elem,low,n,i,mid,high:integer;
begin
writeln('binary_search');
write('enter the number of elements:');
readln(n);
writeln('enter the elements of the vector(sorted:');
for i :=1 to n do
read(a[i]);
readln;
writeln('enter the element to be searched
for');
readln(elem);
low:=1;
high:=n;
mid:=(low+high)div 2;
while((low<high) and (a[mid]<>elem))do
begin
if(a[mid]>elem)then
high:=mid-1
else
if(a[mid]<elem)then
low:=mid+1;
mid:=(low+high)div 2;
end;
if(a[mid]=elem)then
writeln('enter',elem:1,'found at position:',mid)
else
writeln('element',elem:1,'not found');
end.
39
DATA STRUCTURES
(a) Sets
In Pascal asset is a collection of ordered data items that are all of the same type. Thus a set may
be a collection of integers or characters or enumerated data items. In order to utilize the set
concept, we must first define a set type. We can then declare set type variables whose individual
values are elements of that set type.
The set type that we wish to define is then introduced in terms of the base type i.e.;
Thus, the set type will refer to the same collection of data items sat the base type
Once a set has been defined we can declare a set-type variable in the following manner
VAR set name: set type
Or if several different set-type variables are desired
VAR set name 1, set name 2, . . ., set name n: set type.
Examples 1
TYPE sizes=(small,medium,large);
Shirtsizes= SET Of sizes;
VAR shortsleeve, longsleeve: shirtsizes;
In this example is the base type; consisting of the enumerated data items small, medium and
large. The set type is shirtsizes. Note that shirtsizes is defined in terms of the base type sizes.
Finally, shortsleeve and longsleeve are set type variables of type shirtsizes.
Examples 2
TYPE sizes=(small,medium,large);
Shirtsizes, dresssizes= SET Of sizes;
VAR shortsleeve, longsleeve: shirtsizes;
Shorthem, lonthem : dresssizes;
40
We can also define asset type in terms of a standard, ordered simple type (e.g. integer or char) or
subrange of a standard, ordered simple type. In such situations the standard data type or its
subrange becomes the base.
Examples 3
TYPE numbers = SET OF integer;
TYPE digits = SET OF 0..9;
TYPE lowercase = SET OF „a‟..‟z‟;
If some of the set members are consecutive set elements they may be represented as subrange
First consecutive element . . last consecutive element
TYPE sizes=(small,medium,large);
Shirtsizes = SET Of sizes;
VAR shirt, blouse: sizes;
[small . . large]
[shirt]
[shirt,blouse]
[small, medium, large]
Asset element may not be included in a set more than once. It is possible, however that a single
element will indirectly (and perhaps unintentionally) be specified two or more times, particularly
if the set specification includes both explicit set elements and variables( A variable may
represent a set element that has already been specified thus resulting in unwanted duplication.) in
such situations the repeated specifications will be ignored.
41
Once a set has been constructed, it can be assigned to asset type variables. This is accomplished
in the usual manner, by writing
Variable name: = [set element 1, set element 2 … set
element n]
It should be understood that the set appearing on the right hand side is regarded as a single-
valued data item. This data item must be of the same set type as the variable to which it is
assigned.
Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;
Begin
……….
Shortsleeve:=[small,large];
………
Longsleeve:=[small,medium,large];
…………
End.
Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;
Begin
……….
Shortsleeve:=[small]+[large];
………
Longsleeve:=[small,medium]+[small,large];
42
…………
End.
The intersection of two sets is set whose members are common to both of the original sets. we
use the operator * to denote this operation.
Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;
Begin
……….
Shortsleeve:=[small, medium]*[medium ,large];
………
Longsleeve:=[small]+[medium, large];
…………
End.
The set difference of two sets is set whose members are in the first set but not in the second.
This operation is denoted by the operator – as in the example below.
Program sample;
TYPE sizes=(small,medium,large);
Shirtsizes, = SET OF sizes;
VAR shortsleeve, longsleeve: shirtsizes;
Begin
……….
Shortsleeve:=[small, medium]-[small ,large];
………
Longsleeve:=[small, medium, large]- [medium] ;
…………
End.
(b) Stacks
(i) Introduction
A stack is an abstract data type consisting of sequence of items, in which the items are added and
removed from one end only. Another way of describing a stack is that the last item put in the
stack will be the first one to be taken out of the stack. Consequently, a stack is referred to as
“Last In First Out (LIFO)”, structure. For example if the integers 10, 20, 30, 40 and 50 are put in
a stack, they would come off the stack in the order 50, 40, 30, 20, and 10.
43
A simple stack can be created using an array. Stack elements are integers but they can be float,
char, structures etc.
44
writeln(„stack full‟);
end;
Algorithm for Pop() Operation
The pop() is an operation in which the top most item of a stack is to be removed or delete.
Popping the stack reference the value from the top of the stack. If s is a stack and v is a variable
of the type of element in the stack, pop(s,v) will put the value on the top of the stack s in the
variable v. pop also makes the stack one item shorter. Before one attempts to pop() an item from
the stack, it is essential to check whether any item is stored in the stack. If not, he stack is empty
and nothing can be popped ands hence an error message „stack is empty‟ will be displayed.
The following procedure shows how to realize pop() operation for a stack:
(c) Queues
(i) Introduction
A queue is sequence of data items for which additions and deletions are possible only at an end
of the sequence. The difference between a queue and stack is that the addition and deletion of
items to a queue are at opposite ends whereas the addition and deletion of items in stack are done
at the same end.
Stacks are useful in problems that reverse the order of items and queues are useful in problems
that preserve the order of the items. A queue is an ordered group of items in which new elements
are added at one end called the rear and elements are removed at the other end called the front.
Queues are also known as FIFO-, First In First Out‟ structure. The term front will denote the end
of the queue from which items are removed and rear will denote the end at which items are
added.
45
qstore()
qdelete()
The qstore() procedure is used to add new elements to the queue while qdelete() procedure is
used to remove an item from the queue.
For example
Stack operation contents
qstore(a) a
qstore(b) ba
qstore(c) cba
qstore(d) dcba
qdelete() dcb a is removed
qdelete() dc b is removed
qstore(e) edc
end;
Algorithm for qdelete()
The qdelete() is an operation in which an item is removed from a queue. Items are removed from
the end, opposite to the end used for addition. The end from which removals are made is the
46
front of the queue. Before one attempts to delete an item from the queue, it is essential to check
whether any item has been stored or not. If there is no item in the queue, it is an error to use the
qdelete() procedure and appropriate error message „queue empty‟ will be displayed
The following procedure shows how to realize qdelete () operation in a queue
Linked lists like stacks and queues are linear data structures in which the items are stored and
retrieved linearly in an organized manner like one item after another. A linked list is like a chain
of data items connected by pointers and each item contains a pointer to the address of the next
item.
There are several different kinds of linked structures
a) linear linked lists :In which the components are all linked together in some sequential
manner,
b) Linked list with multiple Pointers: Permitting forward and backward traversal thro‟ the
list.
c) Circular list: Linear list having no beginning and no ending.
d) Trees: in which the components are arranged in a hierarchical structure.
For example the following program segment illustrates how a linear linked list is declared and
connected with another list with the aid of pointer.
type
pointer=^list;
list=record
data:integer;
47
next:pointer;
end
var
a,b,c:pointer;
begin
a^.data:=10;
b^.data:=20;
c^.data:=30;
a^.next:=b
b^.next:=c;
c^.next:=nil;
end.
a b c
10 20 30 nil
next next next
Linked lists are used for example in construction of compilers, operating systems and database
management systems.
Example of a program that demonstrates how a simple linear linked list is working
program selfglist(input,output);
type
pointer=^list;
list=record
data:integer;
next:pointer;
end
var
a,b,c:pointer;
x,y,,z:integer;
begin
a^.data:=10;
b^.data:=20;
c^.data:=30;
a^.next:=b
48
b^.next:=c;
c^.next:=nil;
writeln(„contents of the lits‟);
write(„value of „);
x:=a^data;
writeln(„a = „,x);
writeln(„a is linked to b‟);
y:=a^.next^.data;
writeln(„b = „,y);
writeln(„b is linked to c‟);
z:=a^.next^.data;
writeln(„c = „,z);
a^.next^.next^.next:=nil;
end.
type
doubleptr=^node
node= record
llink:doubleptr;
value: integer;
rlink:doubleptr;
var
head,tail:doubleptr;
Data = 10
10
Prev next
49
Data = 20
20
Prev next
Data = 30
30
Prev next
(i) Introduction
Data structures such as stacks, queues and linked lists are linear organization of data in which
items or components are arranged sequentially, one object after another. On the other hand,
components or items are arranged in hierarchical order then it is called a tree. Tree is more
flexible abstract data type than linear types.
A tree has a finite set of elements called nodes. A tree has a unique node called root. A binary
tree ia a tree whose elements have two nodes such as a left node and a right node. Each left node
contains a number less than the value in the preceding node. Each right node value is greater than
the value in the preceding node. Anode with no branch is called a leaf.
The advantage of a binary tree is that items can be placed in the tree in a sorted manner. Thus the
processes of inserting a node, deleting anode, searching for a node and retrieving information can
be accomplished in a more efficient manner than with a linear linked list. The node above a
given node in a tree is called a parent and the node below a given node in a tree is called a child.
The root is the unique node of a tree without a parent. The node with no child is called a leaf.
The link from a parent node to a child is called a branch. The tree that is part of another tree is
called a subtree.
The declaration of a binary tree is:
type
pointer=^node;
node=record
data:integer;
left:pointer;
right: pointer;
end;
50
(i) inorder
Inorder traversal is a process of a binary tree in which a node is visited between the traversal of
the node‟s left sub tree and the traversal of the node‟s right sub-tree.
Example
A
C
B
Diagram 1
In the example in ther inorder tree traverse, first the left sub-tree of the root is traversed(B). the
root is then visited(A). then the right sub tree is visited(C).
The following recursive procedure prints the contents of the binary tree in the inorder traversal
method.
Procedure inorder(ptr1:pointer);
(*inorder binary tree traverse*)
Begin
If ptr1<> nil then
Begin
Inorder(ptr1^.left);
Write(ptr1^.data:7);
Inorder(ptr1^.right);
End;
End;
(b) Preorder
In a preorder tree traverse a node is visited before its sub tree are traversed. It first visits the root
node(A), then traverse the left sub tree(B) and then the right sub tree(C).
The following recursive procedure prints the contents of the binary tree in the preorder traversal
method.
51
Procedure preorder(ptr1:pointer);
(*preorder binary tree traverse*)
Begin
If ptr1<> nil then
Begin
Write(ptr1^.data:7);
preorder(ptr1^.left);
preorder(ptr1^.right);
End;
End;
(c) postorder
When a postorder traversal on a tree is performed, both the left and the right sub tress are
traversed before the root node is visited. Using the previous diagram 1 the order will be B C A
The following recursive procedure prints the contents of the binary tree in the postorder traversal
method.
Procedure postorder(ptr1:pointer);
(*postorder binary tree traverse*)
Begin
If ptr1<> nil then
Begin
postorder(ptr1^.left);
postorder(ptr1^.right);
Write(ptr1^.data:7);
End;
End;
Example
A program to create a binary tree and to display the contents of the tree using the inorder tree
traversal methods
program binary(input,output);
type
pointer=^node;
node=record
data:integer;
left:pointer;
52
right: pointer;
end;
var root:pointer;
item:integer;
i,n:integer;
procedure inorder(ptr1:pointer);
(*inorder binary tree traverse*)
begin
if ptr1<> nil then
begin
inorder(ptr1^.left);
write(ptr1^.data:7);
inorder(ptr1^.right);
end;
end;
53
begin
writeln('enter a number');
readln(item);
buildtree(root,item);
i:=i+1;
end;
writeln;
writeln('output from the binary tree');
write('using inoreder algorithm');
inorder(root);
end.
RECORDS
A record can be defined as a group of fields made up of different data items. In pascal we refer a
record as a collection of heterogeneous (different) types of data grouped together.. the entire
collection is referred to as a record. The individual components which are called fields or
members can be accessed and processed separately.
a) Defining a record
The general form of a record variable decaration is:
Var record name= record
Field1;
Field2;
.
.
Fieldn
End;
Where field1 represents the first field declaration, field2 represents the second field and sos on.
Each field declaration is written in manner that is similar to an individual variable declaration i.e
field name: type
Where field name is an identifier that represents the name of the field and type is their data type
of the item that will occupy the field. Therefore full declaration would be
54
End;
Example 1
Var customer= RECORD
Custno: integer;
Custtype: char;
Custbalance: real
end
records can also be declared using type definition as in the following example
general form is
Example 2
type account= RECORD
Custno: integer;
Custtype: char;
Custbalance: real
end
var
customer: account;
Individual fields can be associated with user defined types as well as standard data types
Example
type status=(current, overdue, delinquent);
account= RECORD
Custno: integer;
Custtype: char;
Custstatus=status;
Custbalance: real
end
var
customer: account;
or
55
Example 3
type status=(current, overdue, delinquent);
line= ARRAY[1..80] of char;
date = record
month:1..12;
day: 1..31;
yeay: 1900..2100;
end;
account= RECORD
custname: line;
lastpayment: date;
Custno: integer;
Custtype: char;
Custstatus=status;
Custbalance: real
End;
var
customer: account;
56
b) Processing a record
It is possible to assign a record to another record in the course of working using the cost example
for
Customer:= regular;
When processing a field the general form is
[Link]
(Note the period between the two names)
Example 4
Writeln.(„enter the name‟);
Readln([Link]);
[Link] :=1942;
57
Read(month);
Read(day);
Read(year);
END;
58
Assignment
Write a program that will accept 20 records with the following fields and output then on the
screen.
FILES
a) Introduction
Is a structured type like an array ( ie a collection of data items) unlike the array however, a file
can be stored on a auxiliary storage ( magnetic tape or disk). Thus the file structure allows us to
store information permanently and access that information whenever necessary.
There are two types of files, permanent files and temporary files. Permanent files are maintained
on auxiliary memory device and therefore preserved after the program has completed its
59
execution. The contents of such files can be accessed and or modified either by the same
program that creates or by some other program.
Temporary files on the other hand are stored within the computer main memory. A temporary
lost as soon as the program that created the file has completed its execution
b) Defining of a file
The simplest way to define a file is to include the file definition as part of the file- type variable
declaration. The general form is
Where file name is an identifier that represents the name of the file and type refer to the data
type the individual file components
Examples (Valid)
1) VAR symbols : FILE OF CHAR;
2) TYPE table = ARRAY (1..50,1..20) of Real;
VAR Data : FILE of table;
3) TYPE status = (current overdue, deliquescent);
account = RECORD
custname: string;
custno : interger;
custtype: status ;
custbal: real;
END;
VAR customers: file of account ;
4) Account= RECORD
Custname :string;
Custno: integer
Custbal: real
END;
Customer= FILE of account;
VAR oldcustomers, newcutomers : customers
c) Creating a file
The first step in creating a file is to prepare the file for writing. This is accomplished with
the standard procedure REWRITE. Thus we begin by writing
Rewrite(FileName)
If the specified file is being created for the first time the rewrite statement simply establishes the
beginning of the file. If the file already exists then the effect of rewrite statement is to erase all of
60
the information within the existing file and establish the beginning of the new file. After the
necessary data items have been assigned to a file buffer, this information is transferred to the file
by means of Write statement.
The WRITE statement is used to write a file component on to a file. The general
expression is
Write (file name,identifier);
Where identifier represents a variable or other identifiers whose value (or values incase of
structured type file buffer) is assigned to the file buffer.
Example
If the declaration of a file is as follows
PROGRAM CREATEFILE(INPUT,OUTPUT,CUSTOMERS);
TYPE ACCOUNT = RECORD
CUSTNAME: STRING;
CUSTNO: REAL;
CUSTBAL: REAL;
CUSTTPAY: REAL;
CUSTPAID: REAL;
END;
VAR CUSTOMERS: FILE OF ACCOUNT;
C:INTEGER;
CUSTREC:ACCOUNT;
Then writing the file customers will be a follows
WITH CUSTREC DO
BEGIN
WRITELN('ENTER CUSTOMER NAME');
READLN(CUSTNAME);
WRITELN('ENTER CUSTOMER NUMBER');
READLN(CUSTNO);
WRITELN('ENTER PAID ');
READLN(CUSTPAID);
CUSTTPAY:=15000;
CUSTBAL:= CUSTTPAY-CUSTPAID;
END;
WRITE(CUSTOMERS,CUSTREC);
61
d) Reading a file
The process of reading a file is essentially a mirror image of the process of creating a file. The
first step is to prepare the file foe reading by means of a standard procedure RESET. The general
form is
Reset(Filename)
If the file contains one or more components, the reset statement causes the value of the first file
component to be read and assigned to the file buffer. The read statement is used to read the file to
a buffer. Once a file component has been read and assigned to the file buffer , the buffer contents
may be processed as desired for example, the contents of the file buffer may be assigned to a
variable, printed to another file e.t.c. the Read statement has the following general expression.
Read(filename,variable name);
Using declaration for example on writing on the file then reading will be a follows
READ(CUSTOMERS,CUSTREC);
e) Updating a file
In Pascal it is not possible to read a file component, modify a file component and then write the
modified component back to the original file. This restriction tends to complicate the process of
updating an existing file. To update the old file we carryout the following steps for each
component within the file
Read the file component into the computer memory and determine whether
or not particular component must be updated
(a) If the current component does not require updating the
copy it directly to a new file.
(b) If updating is required, then new information is entered
from the input device and merged with the old
information in appropriate manner. The modified file
component is then written to a new file.
This scheme is repeated until the file components have been read from the
old file(i.e. until the end of the file has been reached.)
If additional file component must be appended to the original, then they are
entered from the input device at this time, in the proper order. Each new file
component is written to the new file at it is entered. For this scheme to work
properly, the new information must be entered sequentially from the input
device, in the correct order.
Example
PROGRAM CREATEFILE(INPUT,OUTPUT,CUSTOMERS,NEWCUST);
TYPE ACCOUNT = RECORD
CUSTNAME: STRING;
CUSTNO: REAL;
CUSTBAL: REAL ;
62
CUSTTPAY: REAL;
CUSTPAID:REAL;
END;
VAR CUSTOMERS,NEWCUST: FILE OF ACCOUNT;
NUM:INTEGER; ANS:CHAR;
CUSTREC,NEWREC:ACCOUNT;
PROCEDURE COPYRECORDS;
BEGIN
WHILE NOT EOF(CUSTOMERS) DO
BEGIN
READ(CUSTOMERS,CUSTREC);
NEWREC:=CUSTREC;
WRITE(NEWCUST,NEWREC);
END;
END;
PROCEDURE UPDATERECORDS;
BEGIN
REWRITE(CUSTOMERS);
RESET(NEWCUST);
REPEAT
IF NOT EOF(NEWCUST) THEN
BEGIN
READ(NEWCUST,NEWREC);
CUSTREC:=NEWREC;
END
ELSE
BEGIN
WITH CUSTREC DO
BEGIN
WRITE('ENTER THE CUSTOMER NAME=>');
READLN(CUSTNAME);
WRITE('ENTER CUSTOMER NUMBER=>');
READLN(CUSTNO);
WRITE('ENTER CUSTOMER PAYMENT');
READLN(CUSTPAID);
CUSTTPAY:= 15000;
CUSTBAL:=CUSTTPAY-CUSTPAID;
63
END;
END;
WRITE(CUSTOMERS,CUSTREC);
WRITELN('MORE RECORDS Y FOR YES AND N FOR NO =>');
READLN(ANS);
UNTIL (ANS='N') OR (ANS='n')
END;
PROCEDURE OUTPUT;
BEGIN
RESET(CUSTOMERS);
WHILE NOT EOF(CUSTOMERS) DO
BEGIN
WITH CUSTREC DO
BEGIN
READ(CUSTOMERS,CUSTREC);
WRITELN(CUSTNAME,' ',CUSTNO:6:0,'
',CUSTTPAY:6:0,' ',CUSTPAID:5:0,' ',CUSTBAL:5:0)
END;
END;
READLN;
END;
BEGIN
ASSIGN(CUSTOMERS,'FREDS');
ASSIGN(NEWCUST,'FREDS');
RESET(CUSTOMERS);
REWRITE(NEWCUST);
COPYRECORDS;
UPDATERECORDS;
OUTPUT;
END.
TEXT FILES
A stream of characters input via a keyboard and output to the screen of a monitor can be thought
of as the contents of text files being read from a keyboard or written to a screen. Indeed the
heading PROGRAM identifiers (INPUT, OUTPUT); essentially defines two system text files,
INPUT and OUTPUT. Text files, however are not confined to keyboard input and screen output,
they can be read from or written to secondary storage media or a disk.
64
The method of re-directing the input is through the program heading. The INPUT and OUTPUT
system file declaration are replaced by the explicit names of the text files being used. For
example
PROGRAM students(data,results);
Specifies two files data and results that are used in place of INPUT and OUTPUT. Thses two
files must be declared as variables of type TEXT for example
Var data, results: TEXT;
But this does not prohibit the use of INPUT and OUTPUT
PROGRAM students(INPUT, data OUTPUT, ,results);
In the above example the program reads data from both the keyboard and file data and writes
information to both the screen and file results.
There are two ways in which a text file may be created. The first is from within a program by
using Write and Writeln statements to direct output to magnetic disc or tape instead of the
screen. The second is by using the system editor in the way as a program is created(via keyboard
entry) and stored on magnetic tape or disk. A text file is a stream of ASCII characters, divided in
to lines, each with an end of line marker, and the end of file is appended by the system, with and
end of the file marker. Atext data is stored in the same format as a source program file.
65
66
program emplo(input,output);
type employee= record
name:string[15];
age:integer;
hrs:real;
rate:real;
gross: real;
end;
var empl1:employee;
inp,out:text;
begin
assign(inp, '[Link]');
assign(out,'[Link]');
reset(inp);
rewrite(out);
while not eof(inp) do
begin
with empl1 do
begin
readln(inp,name,age,hrs,rate);
gross:=hrs*rate;
writeln(out,
name:15,Age:3,hrs:10:1,rate:11:1,gross:11:2);
writeln(name:15,' ',age:4,' ',hrs:4,' ',rate:4,'
',gross:4:2);
end;
end;
close(inp);
close(out);
end.
67