Programming With Pascal Notes

download Programming With Pascal Notes

of 28

Transcript of Programming With Pascal Notes

  • 8/7/2019 Programming With Pascal Notes

    1/28

    Table of contents

    Table of contents .......................................................................................................................... 1

    USER DEFINED SIMPLE TYPE DATA ...................................................................................1

    a) Enumerated type data ...........................................................................................................1b) Subrange ..............................................................................................................................1

    Utilizing User Defined Data Type ........................................................................................... 2

    ARRAYS ...................................................................................................................................... 3a) One dimensional array ......................................................................................................... 3

    b) Two Dimensional Array ...................................................................................................... 4

    c) Multi dimension arrays ........................................................................................................ 4d)Packed arrays .......................................................................................................................5

    RECORDS ...................................................................................................................................5

    Processing a record ...................................................................................................................7

    SORTING .....................................................................................................................................7

    a) Selection sort ........................................................................................................................ 8b) Bubble sort ...........................................................................................................................8

    c) Insertion Sort ......................................................................................................................10d) Quick Sort ..........................................................................................................................10

    e) Merge Sort ..........................................................................................................................12

    f) Shell Sort ............................................................................................................................13SEARCHING .............................................................................................................................13

    a)Linear Search ......................................................................................................................14

    b) Binary Search .....................................................................................................................14DATA STRUCTURES ..............................................................................................................14

    (a) Sets ....................................................................................................................................14

    Constructing a Set .................................................................................................................. 15Operations with Sets ...............................................................................................................16

    (b) Stacks ................................................................................................................................17

    (c) Queues ..............................................................................................................................19(d) Linked Lists ......................................................................................................................21

    (e) Binary trees .......................................................................................................................23

    1

  • 8/7/2019 Programming With Pascal Notes

    2/28

    USER DEFINED SIMPLE TYPE DATA

    They are data types which are designed by the programmer to meet special purpose. They are

    of two types

    i.) Enumerated

    ii.) Subrange

    a) Enumerated type data

    Consists of an ordered sequence of identifiers, where each identifier is interpreted as an

    individual data item. These data items will collectively be associated with a particular name

    which serves to identify the data type. The association between the name of the data type andindividual data items is established bt a type definition.

    Type name = (data item1, data item2 ,.., data item 2);Where name is the name of theenumerated data type and data item1 data item2 are actual data

    items.Example1Type day =(Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)Var offdays:day;

    Note data items are enclosed in parenthesis and separated by commas.

    Example 2type day =(sun, mon, tue, wed, thu, fri, sat);

    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 ValueSun< tue TrueWed >= sat FalseMon fri TruePred(fri)= thu TrueSucc(fri)=sat TrueSucc(tue) pred(thu) False

    b) Subrange

    A sub-range refers to some portion of the original range of an ordered simple data. Sub-rangetype 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 includespreviously defined enumerated data as well as three of the standard types i.e integer, char,

    Boolean.

    1

  • 8/7/2019 Programming With Pascal Notes

    3/28

    The general formType 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

    Examplestype 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

    Utilizing User Defined Data Type

    Once enumerated and subrange data types have been defined, they can be used just as other

    simple data items are used within apascal program this includes their use as control variables

    in FOR and Case examplesfor workkdays : mon to fri do

    beginwriteln(workdays);

    .end;

    case workdays ofmon: writeln(the first work day);tue: writeln(the secondwork day);wed: writeln(the third work day);thu: writeln(the fourth work day);fri: writeln(the fifth work day);

    end;

    2

  • 8/7/2019 Programming With Pascal Notes

    4/28

    ARRAYS

    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 areoften called elements.

    There are three types of arrays

    a) One dimensional arrayb) Two dimensional array

    c) Multi dimensional array

    a) One dimensional array

    it can be thought of as a list of data items, all of the same type , that they arecollectively referred to by the same name. Each individual array element (i.e each of the data

    items) can be referred to by specifying the array name followed by an index, enclosed inbrackets. The general expression of an array is

    The easier way to defined are array is to include it in a variable declaration

    Var array name: array [index type] of typeThe index type can be ordinal simple (i.e integer, char, Boolean or enumerated or a

    subrange. The array it self can be of any type including structured types. Examples of

    declarations

    i). VAR List : ARRAY[1..100] OF Real;ii). Type index= 1..100;

    VAR List: ARRAY [index] of Real;

    Individual array elements can be used in expressions, assignment statements,

    read and write statements as though they are ordinary simple type variables. Anarray element must be written sa the array name followed by an appropriate

    index value enclosed in square brackets

    List[1]

    List[2].

    .

    .list[n]

    List =

    3

  • 8/7/2019 Programming With Pascal Notes

    5/28

    b) Two Dimensional Array

    Can be thought of as a table of data items consisting of rows and columns. Is a repetition of

    one dimension array. The structure can be thought of as a matrix or grid structure. The firstdimension might refer to the row number and the second dimension to the column number

    The general expressionVAR array name : array [index 1 type, index 2 type ] of type

    The index types can be ordinal, simple types(i.e integer char, boolen or enumerated) or

    subranges. The array element must all be of the same type though they can be of any type.

    Example of declarationsi.) Var table: array[1..60,1..150] of real;ii.) Type index=1..60;

    Index2=1..150;Var: table :array [index1,index2] of realiii.) Const limit1=60;

    Limit2=150;Type index1=1..limit1;

    Index2=1..limit2;Var table: array [index1,index2] of real

    c) Multi dimension arrays

    A three dimension array might be thought of as a collection of two dimensional array

    (repetition) afour dimension array might be thought of as a repetition of a three dimensionalarray etc . regardless of its dimension, an array always consists of a collection of data items of

    the same type.

    Examples

    i.) Type twod= array[1..10,1..5] of integer;Var threed:array[1..4] of twod;

    ii.) Type threed= array[1..10,1..5,1..10] of integer;Var fourd: array [1..4] of threed;

    table[1,1] table[1,2] .. table[1,n]

    table[2,1] table[2,2] .. table[2,n]

    table[3,1] table[3,2] .. table[3,n]. . .

    . . .

    . . .

    . . .

    . . .

    . . .

    table[m,1] table[m,2] .. table[m,n]

    table =

    4

  • 8/7/2019 Programming With Pascal Notes

    6/28

    The method of access to the arrays will be through their respective indices for exampleThreed[2,2,4]:=20;

    Readln(threed[1,8,3]);Writeln(foud[3,2,8,4]);

    d)Packed arrays

    some types of arrays can be defined so that they can utilize the computers memory more

    efficiently by packing the data items close together. This feature allows a greater quantity ofinformation to be stored in a given amount of memory.

    ExampleVar 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 computingspeed.

    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 ormembers can be accessed and processed separately.

    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: typeWhere 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

    Var record name= record

    Field name 1: type;Field name 2: type;..Field name n: type;

    End;

    5

  • 8/7/2019 Programming With Pascal Notes

    7/28

    ExampleVar customer= RECORD

    Custno: integer;Custtype: char;Custbalance: real

    end

    records can also be declared using type definition as in the following examplegeneral form is

    type record name= recordField name 1: type;Field name 2: type;

    ..Field name n: type;

    End;

    Example 2type 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

    Exampletype status=(current, overdue, delinquent);

    account= RECORDCustno: integer;Custtype: char;Custstatus=status;Custbalance: real

    end

    varcustomer: account;or

    type status=(current, overdue, delinquent);line= ARRAY[1..80] of char;

    account= RECORDcustname: line;

    6

  • 8/7/2019 Programming With Pascal Notes

    8/28

    Custno: integer;Custtype: char;Custstatus=status;Custbalance: real

    End;

    var customer: account;

    Example 3type status=(current, overdue, delinquent);

    line= ARRAY[1..80] of char;date = record

    month:1..12;day: 1..31;yeay: 1900..2100;

    end;

    account= RECORDcustname: line;lastpayment: date;Custno: integer;Custtype: char;Custstatus=status;Custbalance: real

    End;var

    customer: account;

    you can declare several records using the same typee.g

    VAR customer, regular: account;

    Processing a record

    SORTING

    Sorting is the process of rearranging an initially unordered sequence of records until they areordered 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

    7

  • 8/7/2019 Programming With Pascal Notes

    9/28

    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 restrictedrange (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 programminglanguage be used if so, does that language support recursion since many of the most

    efficient internal sorting algorithms are most naturally expressed recursively.

    The following sorting algorithms will be discusseda) Selection sort

    b) Bubble sort

    c) Insertion sort

    d) Quick sorte) Shell sort

    f) Merge sortg) Binary sort

    a) Selection sort

    Selection sort involves looking thro all n records to find the one with smallest key, then throthe 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 topgrowing 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

    See sample programs

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

    8

  • 8/7/2019 Programming With Pascal Notes

    10/28

    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

    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 :

    1 4 8 5 3 7 6 2

    then becomes :1 3 8 5 4 7 6 2

    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 31 2 3 8 5 7 6 4

    1 2 3 5 8 7 6 4

    1 2 3 4 8 7 6 51 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 61 2 3 4 5 6 8 7

    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

    9

  • 8/7/2019 Programming With Pascal Notes

    11/28

    See sample programs

    c) Insertion Sort

    The insertion sort algorithm is likely to occur to anyone who is playing cards by simplyholding 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 listdown 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 combinedsequences 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 doIf A[i] < A[1] thenBegin

    t:=A[i];A[i]=A[1];A[1]:=t;

    EndFor j:=1 to n-1 do

    BeginT:=A[j+1];K:=j;While A[k] >t do

    BeginA[k+1]:=A[k];K:=k-1;

    End;A[k+1]:=t

    Endend

    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 toone 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 element larger than the partitioning element.). This should produce two lists of

    10

  • 8/7/2019 Programming With Pascal Notes

    12/28

    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 aspartition exchange sort

    ExampleProgram quicksort(input,output);Const max=1001;

    VarA:array[1..max] of integer;I:=integer;N: integer;

    Procedure quicksort(l,r:integer);Var I, j, piv,t:integer;Begin

    If l

  • 8/7/2019 Programming With Pascal Notes

    13/28

    Write(A[i]:5);Writeln;End.

    e) Merge SortMerging 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 inorder. The merging algorithm can be stated in pseudocode as:

    While{still more unmerged items in either list} do

    BeginIf 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 BEnd;

    In the course of being merged, each number in each list is processed only once. This meansthat 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 mergesthem 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 doRead(A[i]);

    For j:=1 to bl doRead(B[j]);

    I:=1; j:=1; k:=1;While (i

  • 8/7/2019 Programming With Pascal Notes

    14/28

    End;While i

  • 8/7/2019 Programming With Pascal Notes

    15/28

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

    ExampleSee sample programs

    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 thevalue 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

    See sample programs

    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 whoseindividual values are elements of that set type.

    Defining a Set Type

    We begin by associating a group of ordered simple, simple data items with a data type using

    TYPE defining, as we have done earlier. This data type will be known as the base type. We

    can therefore establish the base type as

    TYPE base type =(data item1, data item 2, . . . ,data item n)Or

    TYPE base type= first data item .. last data item.

    The set type that we wish to define is then introduced in terms of the base type i.e.;

    Set type = SET Of base type

    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 mannerVAR set name: set type

    Or if several different set-type variables are desired

    14

  • 8/7/2019 Programming With Pascal Notes

    16/28

    VAR set name 1, set name 2, . . ., set name n: set type.

    Examples 1TYPE 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 2TYPE sizes=(small,medium,large);

    Shirtsizes, dresssizes= SET Of sizes;VAR shortsleeve, longsleeve: shirtsizes;

    Shorthem, lonthem : dresssizes;

    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 3TYPE numbers = SET OF integer;TYPE digits = SET OF 0..9;TYPE lowercase = SET OF a..z;

    Constructing a Set

    A set can consist of any number of elements from associated base set. The set is constructed by

    writing the individual elements consecutively, enclosed in square brakets and separated bycommas. Thus an individual set will appear as[set element 1, set element 3, . . . . set element n]

    The included elements are known as the members of the set. A set can consists of only one

    element, and it is also possible to construct a set that does not contain any element. This is

    known as an empty (or null) set. It is written as [].Example

    [small, medium, large][medium, large][small, large][medium][]

    If some of the set members are consecutive set elements they may be represented as subrangeFirst consecutive element . . last consecutive element

    TYPE sizes=(small,medium,large);

    15

  • 8/7/2019 Programming With Pascal Notes

    17/28

    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 variablemay represent a set element that has already been specified thus resulting in unwanted

    duplication.) in such situations the repeated specifications will be ignored.

    Once a set has been constructed, it can be assigned to asset type variables. This isaccomplished in the usual manner, by writingVariable 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.

    Operations with Sets

    There are three difference operations that can be carried out with sets, each of which results in

    the creation of a new set. We refer to the resultant of this operation (i.e., the newly created

    sets) as the union, the intersection and the set difference of the original two sets, respectively.Each set operation requires two operands(i.e, two set) of the same type. The resultant will then

    be of the same type as the operands. The union of the two sets is a new set that contains all themembers of the original two sets. The + operator is used to indicate this operation as illustrated

    below

    Program sample;TYPE sizes=(small,medium,large);

    16

  • 8/7/2019 Programming With Pascal Notes

    18/28

    Shirtsizes, = SET OF sizes;VAR shortsleeve, longsleeve: shirtsizes;

    Begin.

    Shortsleeve:=[small]+[large];Longsleeve:=[small,medium]+[small,large];

    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

    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 inthe stack will be the first one to be taken out of the stack. Consequently, a stack is referred to

    17

  • 8/7/2019 Programming With Pascal Notes

    19/28

    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.

    Operations of stack

    Two main operations are involved in the use of stack. The operations of adding an item to the

    stack is known as pushing the item on to the stack and the operation opposite pushing on tothe stack is a called popping the stack.

    Push()

    Pop()Push() procedure is used to add new elements to the top of the stack where as the pop()

    procedure is used to remove an element from the stack. Initially an empty stack must be

    created whenever there is attempt to push an element into a stack, it must be checked whether

    any space is there to accommodate new elements in the stack or not. While attempting to userpopping operation it must be checked whether any element is there which is to be popped out.

    For example

    Stack operation contents

    Push(a) aPush(b) ba

    Push(c) cbaPush(d) dcba

    Pop() cba d is removed

    Pop() ba c is removed

    Push(e) eba

    A simple stack can be created using an array. Stack elements are integers but they can be float,

    char, structures etc.

    Algorithm for push() operation

    The push() is an operation for storing an item in a stack. If s is attack and x is and item to bepushed on to s, we will use push(s,x) to denote the process by which thee value denoted by x is

    added to the top of the stack s. before pushing an item into a stack, it is essential to check

    whether enough space is there to accommodate the item. Otherwise, an appropriate errormessage ,stack full will be displayed.

    The following procedure shows how to realize push() operation for a stack:

    procedure push(var s:stack; var spointer:integer; item,max:intger);begin

    if spointer < max thenbegin

    spointer:=spoiter+1;s[spointer]:=item;

    endelse

    18

  • 8/7/2019 Programming With Pascal Notes

    20/28

    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 avariable 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() anitem 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:

    procedure pop(var s:stack; var item, spointer:integer);begin

    if spointer >0 then

    begin item:=s[spointer];spointer:=spoiter-1;

    endelse

    writeln(stack empty);end;

    To type aprogram

    (c) Queues

    A queue is sequence of data items for which additions and deletions are possible only at an endof 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 calledthe 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.

    Operations on Queue

    The main operations on aqueue are additions of items of the queue and removal (deletiond) of

    items from the queue

    qstore()

    qdelete()

    19

  • 8/7/2019 Programming With Pascal Notes

    21/28

    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 contentsqstore(a) a

    qstore(b) ba

    qstore(c) cbaqstore(d) dcba

    qdelete() dcb a is removed

    qdelete() dc b is removed

    qstore(e) edc

    Algorithm for qstore()

    The qstore() is an operation in which an item is stored in the queue. The end to whichadditions are made is the rear of the queue. Before one attempts to store an item in to a queue,

    it essential to check whether enough space is there to accommodate the item in the queue ornot. If there is no space in the queue an appropriate error message queue full is displayed.

    The following procedure shows how to realize qstore() operation in a queue

    procedure qstore(var q:queue; var rear: integer; item,max, front :integer);

    beginrear:=rear+1;

    if rear >max thenrear:=1;if front rear then

    q[rear]:=itemelsebegin

    writeln(queue is full);rear:=rear-1;if rear =0 then

    rear:=max;end;

    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 front of the queue. Before one attempts to delete an item from the queue, it is essential to

    20

  • 8/7/2019 Programming With Pascal Notes

    22/28

    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

    procedure qstore(var q:queue; var item, front: integer;

    max, rear :integer);beginif front rear then

    beginfront:=front+1;if front > max then

    front:=1;item:= q[front];writeln(value =,item)

    endelse

    writeln(queue empty);end;

    (d) Linked Lists

    Linked lists like stacks and queues are linear data structures in which the items are stored andretrieved 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 sequentialmanner,

    b) Linked list with multiple Pointers: Permitting forward and backward traversal thro thelist.

    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=recorddata:integer;next:pointer;

    endvar

    a,b,c:pointer;begin

    a^.data:=10;

    21

  • 8/7/2019 Programming With Pascal Notes

    23/28

    b^.data:=20;c^.data:=30;a^.next:=bb^.next:=c;c^.next:=nil;

    end.

    The graphical representation of the above structure is

    Linked lists are used for example in construction of compilers, operating systems and database

    management systems.Example of aprogram that demonstrates how a simple linear linked list is workingprogram selfglist(input,output);type

    pointer=^list;list=record

    data:integer;next:pointer;

    endvar

    a,b,c:pointer;

    x,y,,z:integer;begina^.data:=10;b^.data:=20;c^.data:=30;a^.next:=bb^.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;

    10 20 30 nil

    a b c

    next nextnext

    22

  • 8/7/2019 Programming With Pascal Notes

    24/28

    end.

    Double linked Lists

    A linked list that has two links in each of its nodes, with one link pointing to the preceding

    node and the other pointing to the succeeding node is called a double linked list. In other

    words a double linked list in a data structure has two pointer elements; one pointing to the nextelement and the other pointer pointing to the previous element and can traverse the list in

    either direction.

    The declaration of a double linked list structure is:

    typedoubleptr=^nodenode= record

    llink:doubleptr;value: integer;rlink:doubleptr;

    var head,tail:doubleptr;

    The graphical representation of the double linked list is shown below:

    (e) Binary trees

    Data structures such as stacks, queues and linked lists are linear organization of data in whichitems 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.

    Data = 10

    Prev next

    10

    Data = 20

    Prev next

    20

    Data = 30

    Prev next

    30

    23

  • 8/7/2019 Programming With Pascal Notes

    25/28

    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 isgreater 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 retrievinginformation 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 childis 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;

    Binary Tree Traversal

    A binary tree is built and searched by moving downwards thro the tree node by node, until an

    empty child is reached or anode with a specific item is found. There are several ways to visitelements of a binary tree. This include inoder, preorder and postorder.

    (i) inorder

    Inorder traversal is a process of a binary tree in which a node is visited between the traversalof the nodes left sub tree and the traversal of the nodes right sub-tree.

    Example

    Diagram 1

    A

    B C

    24

  • 8/7/2019 Programming With Pascal Notes

    26/28

  • 8/7/2019 Programming With Pascal Notes

    27/28

    BeginIf ptr1 nil then

    Beginpostorder(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=recorddata:integer;left:pointer;right: pointer;

    end;var root:pointer;

    item:integer;i,n:integer;

    procedure inorder(ptr1:pointer);

    (*inorder binary tree traverse*)begin

    if ptr1 nil thenbegin

    inorder(ptr1^.left);write(ptr1^.data:7);inorder(ptr1^.right);

    end;end;

    procedure buildtree(var bnode:pointer; value:integer);

    beginif bnode=nil then

    beginnew(bnode);bnode^.data:=value;bnode^.left:=nil;bnode^.right:=nil

    end

    26

  • 8/7/2019 Programming With Pascal Notes

    28/28

    else if value