PASCAL II - Data Structures Philip Fees CS341
Introduction  What will be studied? Data Types Arrays Records Abstract Data Pointers Linked lists, Stacks, Queues What is a data structure?
Workshop 1 File I/O Concepts Pascal File I/O User Defined Types
File I/O Concepts Generally termed Device I/O Could be hard disk, CD-ROM, tape, etc. Could be terminal, socket (IPC/Internet), etc. Delimited files (whitespace, eol, eof) vs. non delimited Encoded (ASCII, EBCDIC) vs. binary Open and Close Read or write via file/device handle (symbolic name) Seek vs. non-seek devices Sequential vs. Indexed
Pascal File I/O - Handles Identify handle (symbolic name) Program myProgram (input, output,  fileHandle ); … VAR fileHandle :  text; Associate file to handle “ create procedure file prior to compiling and running the program” TP:  assign(fileHandle,’myTextFile.txt’);
Pascal File I/O - Open & Seek Open the file reset(fileHandle); rewind is part of  “seeking” delimiter tests WHILE not eol DO WHILE not eol(fileHandle) DO WHILE not eof DO WHILE not eof(fileHandle) DO
Pascal File I/O - Read & Write Read from file via handle readln(fileHandle, variable1, variable2, …); Write to file via handle writeln(fileHandle, ‘this is a test’, variable1, …); Ease old file contents rewrite(fileHandle); See example pg. 444
Exercises Pg. 448 25 - 30
User Defined Types Characteristic of a data type (int, char, boolean) set of value fixed amount of memory Ordinal data type have pred() and succ() values User defined a.k.a. enumerated data type
Enumerated Data Type Syntax Type Weekday = (Mon, Tues, Wed, Thur, Fri); Usage VAR Day : Weekday; … Day := Mon; if (Day = Mon) then
Subranges Define one type as subset of another type Examples TYPE USYears = 1776..1998; Days = (Sun, Mon, Tues, Wed, Thur, Fri, Sat); Weekdays = Mon..Fri; Operations: succ() and pred()
Exercises Pg. 454-455 # 2, 15 Pg. 461 #22-26 Pg. 465 #8, 20, 21, 22
Workshop 2 Single Dimensional Arrays Selection Sort Arrays and Subroutines Searching Arrays
Arrays Collection of data elements Data elements are the same type Contiguous in memory Access individuals by subscript Array size determined by: element size * number of elements
Pascal Arrays name :  ARRAY [  index type  ] OF  type ; Example 1: VAR List : ARRAY [1..5] OF integer; Example 2: TYPE Numbers = ARRAY [1..5] OF integer; VAR List : Numbers;
Pascal Arrays (cont.) index type alternatives TYPE DAYS = (SUN, MON, TUES, WED, THUR, FRI, SAT); VAR StockPriceList : ARRAY [9..16] OF real; NegativeList : ARRAY [-2..3] OF char; HoursWorked : ARRAY [MON..FRI] of real;
Use of Constants Good Pratice CONST ClassSize = 35; Type TestScores = 0..100; VAR Score : ARRAY [1..ClassSize] of TestScores;
Arrays and Loops “ Looping” over the array Example: FOR J := 1 to ClassSize DO BEGIN write(‘next: ‘); readln(Score[J]); writeln(‘value = ‘, Score[J]); END
Review Example 10.7 pg. 491 Example 10.9 pg. 493 Example 10.10 pg. 494
Selection Sort Sorting a list of values Algorithm start with first element [1] (current) find smallest element in array and exchange with current current := next array element (current + 1) continue to end of array What is the best and worst case?
Arrays and Subroutines See GetData example on pg. 508 Call by value vs. call by reference Call by value: create a copy of the array Call by reference: refer to the passed array Performance implications
Search Algorithms Sequential Search (pg. 526) search entire array until value located or “hit” the end of the array Average of N iterations of loop Binary Search (pg. 528) Assumes sorted array start in middle; look in upper or lower half Average of log N iterations of loop
Analysis Overhead of inserting new value in sorted array What should maximum size of the array be? When should an array be used?
Exercises Arrays: pp. 497-500 # 1-5, 10, 20 Sorts: pg. 507 # 2, 3, 6 Subroutines: pg. 516 # 16-19 Searching: pg. #533 5, 15
Workshop 3 Multi-dimensional arrays
Array in Memory Array stored in contiguous memory Location is calculated: Starting address + (row index * # of columns) + column index Row Major vs. Column Major
Pascal Syntax Syntax <name> : ARRAY [ <row index>, <column index> ] OF <element type>
Two Dimensional Example Example 1: VAR Table : ARRAY [ 1..3, 1.. 4 ] OF integer; Example 2: TYPE Maxtrix = [ 1.. 3, 1.. 4] OF integer; VAR Table : Matrix;
Iteration Example: FOR row := 1 to 3 DO FOR column := 1 to 4 DO writeln(‘Table[‘,row,’, ‘, column,’] = ‘, Table[row][column]);
Higher Dimensional Arrays Syntax <identifier> : ARRAY [ A1 .. B1, A2 .. B2, …, An .. Bn] OF <type> Example1: cube : ARRAY [ 1..3, 1..4, 1..5] OF integer; Example 2: cube : ARRAY [ 1..3 ] OF ARRAY [ 1..4, 1..5 ] OF integer;
Exercises pg. 567 # 4, 9-12, 13-15
Workshop 4 Records Variants Binary Files
Workshop 5 Sets
Defining and Declaring Syntax TYPE <type name>  = SET OF <base type> ; VAR <variable name> : <type name> ; Example TYPE Digits  = SET OF 0..9; VAR numbers : Digits;
Different than Subtypes Assignment numbers := [ 0, 2, 4, 6, 8 ]; Set is undefined until assignment Assigned values must be in base type -  elements of the set Universal sets  contain all values Subsets  - one set contains all members of another set See set definitions on top of page 735.
Set Operations Union:  A + B Intersection: A * B Difference: A - B
Relational Operators equal: A = B sets A and B are identical not equal: A <> B set A and B are not identical subset: A <= B A is a subset of B superset A >= B A is a superset of B (A<=B)
Membership Syntax <element> IN <set> Example 2 IN numbers Boolean value: is 2 in the  numbers  set?
Membership Example Useful for “edit checks” Example IF response IN [‘Y’, ‘y’] THEN (continue action here) ELSE (alternative action here) Review example on page 744.
Exercises Page 739 # 9-15, 26-30 Page 743 # 2, 7-20, 27 Programming Problem Page 759 # 1, 3
Workshop 6 Model Builder Abstract Data Type (ADT) String ADT Linked List ADT
Model Builder Model, design, or abstraction - analysis without being concern for details  Examples World Wide  Web Windows Virus UNIX: parent process, child process, kill, fork, etc.
Abstract Data Type collection of data (objects) shared properties shared operations Examples: Array, Integers,
ADT Example - String definition - finite sequence of characters terminated with null character access individual elements (substring) Operations: create, read, write, assign, length reconsider operations if string is defined by length not null terminator.
ADT Example - Linked List Definition - list of data items associated by a link to one or more nodes. Typically point to next node (single linked) or previous node (double linked) Head node is first node in list To “walk” the list, must start at head and proceed sequentially. Task: Define operations, define interfaces, implement
Workshop 7 Linked Lists Array Implementation of Linked Lists Pointers Pointer Implementation of Linked Lists
Why Linked Lists Arrays Size fixed at Compile Time, inefficient space utilization Inserting, deleting, organizing are costly.  Why? Requirement Size determined at Run Time Minimal cost to insert, delete, and organize data Examples Sorting,  data with undetermined number of items
Linked Lists Diagram data structure (See page 872) Define operations (See page 881) Define implementation base data structures (See page 873) Diagram operation’s effect on sample data structure (See page 887)
Introduction to Pointers A pointer doesn’t contain the data, but contains a way of locating the data. Example:  Array subscript pointer : integer data : array [1..100] of char; … pointer := 5; writeln(array[pointer]);
Array Implementation of Linked Lists Issues Still have compile time limit on number of nodes, wasted space Which nodes are “free” Benefits Simple base data type Ok if max nodes know  at compile time Still have benefits of low  cost insert, update, and organize
Array Implementation (cont.) Free nodes Mark all free node - sequential search Keep linked list of free nodes Book has special procedures to handle free nodes Modify linked list procedures to handle free linked list Move InitializeSpace logic into Create Procedure Pass InsertNode the data in place of the pointer P
Pointers & Dynamic Memory Declaring a pointer (see page 874) Var intPtr :  ^integer; Allocate memory new(intPtr); Access and deallocate memory intPtr^ := 10; writeln(intPtr^); dispose(intPtr^);
Pointers & Dynamic Memory Declaring a pointer (see page 874) Var intPtr :  ^integer; Allocate memory new(intPtr); Access and deallocate memory intPtr^ := 10; writeln(intPtr^); dispose(intPtr^);
Pointers & Dynamic Memory Declaring a pointer (see page 874) Var intPtr :  ^integer; Allocate memory new(intPtr); Access and deallocate memory intPtr^ := 10; writeln(intPtr^); dispose(intPtr);
Pointers & Dynamic Memory (cont.) NIL value - doesn’t point to anything Memory allocated by new comes from heap Must deallocate via dispose  Must keep track of all allocated memory - memory leaks
Pointer Implementation of Linked Lists See page 889
Variations on Linked List Dummy Header - avoid test for empty list Circularly Linked - no NIL Doubly Linked List - don’t need previous node
Exercises Pg 872 # 16 Pg 880 # 9-19

Cs341

  • 1.
    PASCAL II -Data Structures Philip Fees CS341
  • 2.
    Introduction Whatwill be studied? Data Types Arrays Records Abstract Data Pointers Linked lists, Stacks, Queues What is a data structure?
  • 3.
    Workshop 1 FileI/O Concepts Pascal File I/O User Defined Types
  • 4.
    File I/O ConceptsGenerally termed Device I/O Could be hard disk, CD-ROM, tape, etc. Could be terminal, socket (IPC/Internet), etc. Delimited files (whitespace, eol, eof) vs. non delimited Encoded (ASCII, EBCDIC) vs. binary Open and Close Read or write via file/device handle (symbolic name) Seek vs. non-seek devices Sequential vs. Indexed
  • 5.
    Pascal File I/O- Handles Identify handle (symbolic name) Program myProgram (input, output, fileHandle ); … VAR fileHandle : text; Associate file to handle “ create procedure file prior to compiling and running the program” TP: assign(fileHandle,’myTextFile.txt’);
  • 6.
    Pascal File I/O- Open & Seek Open the file reset(fileHandle); rewind is part of “seeking” delimiter tests WHILE not eol DO WHILE not eol(fileHandle) DO WHILE not eof DO WHILE not eof(fileHandle) DO
  • 7.
    Pascal File I/O- Read & Write Read from file via handle readln(fileHandle, variable1, variable2, …); Write to file via handle writeln(fileHandle, ‘this is a test’, variable1, …); Ease old file contents rewrite(fileHandle); See example pg. 444
  • 8.
  • 9.
    User Defined TypesCharacteristic of a data type (int, char, boolean) set of value fixed amount of memory Ordinal data type have pred() and succ() values User defined a.k.a. enumerated data type
  • 10.
    Enumerated Data TypeSyntax Type Weekday = (Mon, Tues, Wed, Thur, Fri); Usage VAR Day : Weekday; … Day := Mon; if (Day = Mon) then
  • 11.
    Subranges Define onetype as subset of another type Examples TYPE USYears = 1776..1998; Days = (Sun, Mon, Tues, Wed, Thur, Fri, Sat); Weekdays = Mon..Fri; Operations: succ() and pred()
  • 12.
    Exercises Pg. 454-455# 2, 15 Pg. 461 #22-26 Pg. 465 #8, 20, 21, 22
  • 13.
    Workshop 2 SingleDimensional Arrays Selection Sort Arrays and Subroutines Searching Arrays
  • 14.
    Arrays Collection ofdata elements Data elements are the same type Contiguous in memory Access individuals by subscript Array size determined by: element size * number of elements
  • 15.
    Pascal Arrays name: ARRAY [ index type ] OF type ; Example 1: VAR List : ARRAY [1..5] OF integer; Example 2: TYPE Numbers = ARRAY [1..5] OF integer; VAR List : Numbers;
  • 16.
    Pascal Arrays (cont.)index type alternatives TYPE DAYS = (SUN, MON, TUES, WED, THUR, FRI, SAT); VAR StockPriceList : ARRAY [9..16] OF real; NegativeList : ARRAY [-2..3] OF char; HoursWorked : ARRAY [MON..FRI] of real;
  • 17.
    Use of ConstantsGood Pratice CONST ClassSize = 35; Type TestScores = 0..100; VAR Score : ARRAY [1..ClassSize] of TestScores;
  • 18.
    Arrays and Loops“ Looping” over the array Example: FOR J := 1 to ClassSize DO BEGIN write(‘next: ‘); readln(Score[J]); writeln(‘value = ‘, Score[J]); END
  • 19.
    Review Example 10.7pg. 491 Example 10.9 pg. 493 Example 10.10 pg. 494
  • 20.
    Selection Sort Sortinga list of values Algorithm start with first element [1] (current) find smallest element in array and exchange with current current := next array element (current + 1) continue to end of array What is the best and worst case?
  • 21.
    Arrays and SubroutinesSee GetData example on pg. 508 Call by value vs. call by reference Call by value: create a copy of the array Call by reference: refer to the passed array Performance implications
  • 22.
    Search Algorithms SequentialSearch (pg. 526) search entire array until value located or “hit” the end of the array Average of N iterations of loop Binary Search (pg. 528) Assumes sorted array start in middle; look in upper or lower half Average of log N iterations of loop
  • 23.
    Analysis Overhead ofinserting new value in sorted array What should maximum size of the array be? When should an array be used?
  • 24.
    Exercises Arrays: pp.497-500 # 1-5, 10, 20 Sorts: pg. 507 # 2, 3, 6 Subroutines: pg. 516 # 16-19 Searching: pg. #533 5, 15
  • 25.
  • 26.
    Array in MemoryArray stored in contiguous memory Location is calculated: Starting address + (row index * # of columns) + column index Row Major vs. Column Major
  • 27.
    Pascal Syntax Syntax<name> : ARRAY [ <row index>, <column index> ] OF <element type>
  • 28.
    Two Dimensional ExampleExample 1: VAR Table : ARRAY [ 1..3, 1.. 4 ] OF integer; Example 2: TYPE Maxtrix = [ 1.. 3, 1.. 4] OF integer; VAR Table : Matrix;
  • 29.
    Iteration Example: FORrow := 1 to 3 DO FOR column := 1 to 4 DO writeln(‘Table[‘,row,’, ‘, column,’] = ‘, Table[row][column]);
  • 30.
    Higher Dimensional ArraysSyntax <identifier> : ARRAY [ A1 .. B1, A2 .. B2, …, An .. Bn] OF <type> Example1: cube : ARRAY [ 1..3, 1..4, 1..5] OF integer; Example 2: cube : ARRAY [ 1..3 ] OF ARRAY [ 1..4, 1..5 ] OF integer;
  • 31.
    Exercises pg. 567# 4, 9-12, 13-15
  • 32.
    Workshop 4 RecordsVariants Binary Files
  • 33.
  • 34.
    Defining and DeclaringSyntax TYPE <type name> = SET OF <base type> ; VAR <variable name> : <type name> ; Example TYPE Digits = SET OF 0..9; VAR numbers : Digits;
  • 35.
    Different than SubtypesAssignment numbers := [ 0, 2, 4, 6, 8 ]; Set is undefined until assignment Assigned values must be in base type - elements of the set Universal sets contain all values Subsets - one set contains all members of another set See set definitions on top of page 735.
  • 36.
    Set Operations Union: A + B Intersection: A * B Difference: A - B
  • 37.
    Relational Operators equal:A = B sets A and B are identical not equal: A <> B set A and B are not identical subset: A <= B A is a subset of B superset A >= B A is a superset of B (A<=B)
  • 38.
    Membership Syntax <element>IN <set> Example 2 IN numbers Boolean value: is 2 in the numbers set?
  • 39.
    Membership Example Usefulfor “edit checks” Example IF response IN [‘Y’, ‘y’] THEN (continue action here) ELSE (alternative action here) Review example on page 744.
  • 40.
    Exercises Page 739# 9-15, 26-30 Page 743 # 2, 7-20, 27 Programming Problem Page 759 # 1, 3
  • 41.
    Workshop 6 ModelBuilder Abstract Data Type (ADT) String ADT Linked List ADT
  • 42.
    Model Builder Model,design, or abstraction - analysis without being concern for details Examples World Wide Web Windows Virus UNIX: parent process, child process, kill, fork, etc.
  • 43.
    Abstract Data Typecollection of data (objects) shared properties shared operations Examples: Array, Integers,
  • 44.
    ADT Example -String definition - finite sequence of characters terminated with null character access individual elements (substring) Operations: create, read, write, assign, length reconsider operations if string is defined by length not null terminator.
  • 45.
    ADT Example -Linked List Definition - list of data items associated by a link to one or more nodes. Typically point to next node (single linked) or previous node (double linked) Head node is first node in list To “walk” the list, must start at head and proceed sequentially. Task: Define operations, define interfaces, implement
  • 46.
    Workshop 7 LinkedLists Array Implementation of Linked Lists Pointers Pointer Implementation of Linked Lists
  • 47.
    Why Linked ListsArrays Size fixed at Compile Time, inefficient space utilization Inserting, deleting, organizing are costly. Why? Requirement Size determined at Run Time Minimal cost to insert, delete, and organize data Examples Sorting, data with undetermined number of items
  • 48.
    Linked Lists Diagramdata structure (See page 872) Define operations (See page 881) Define implementation base data structures (See page 873) Diagram operation’s effect on sample data structure (See page 887)
  • 49.
    Introduction to PointersA pointer doesn’t contain the data, but contains a way of locating the data. Example: Array subscript pointer : integer data : array [1..100] of char; … pointer := 5; writeln(array[pointer]);
  • 50.
    Array Implementation ofLinked Lists Issues Still have compile time limit on number of nodes, wasted space Which nodes are “free” Benefits Simple base data type Ok if max nodes know at compile time Still have benefits of low cost insert, update, and organize
  • 51.
    Array Implementation (cont.)Free nodes Mark all free node - sequential search Keep linked list of free nodes Book has special procedures to handle free nodes Modify linked list procedures to handle free linked list Move InitializeSpace logic into Create Procedure Pass InsertNode the data in place of the pointer P
  • 52.
    Pointers & DynamicMemory Declaring a pointer (see page 874) Var intPtr : ^integer; Allocate memory new(intPtr); Access and deallocate memory intPtr^ := 10; writeln(intPtr^); dispose(intPtr^);
  • 53.
    Pointers & DynamicMemory Declaring a pointer (see page 874) Var intPtr : ^integer; Allocate memory new(intPtr); Access and deallocate memory intPtr^ := 10; writeln(intPtr^); dispose(intPtr^);
  • 54.
    Pointers & DynamicMemory Declaring a pointer (see page 874) Var intPtr : ^integer; Allocate memory new(intPtr); Access and deallocate memory intPtr^ := 10; writeln(intPtr^); dispose(intPtr);
  • 55.
    Pointers & DynamicMemory (cont.) NIL value - doesn’t point to anything Memory allocated by new comes from heap Must deallocate via dispose Must keep track of all allocated memory - memory leaks
  • 56.
    Pointer Implementation ofLinked Lists See page 889
  • 57.
    Variations on LinkedList Dummy Header - avoid test for empty list Circularly Linked - no NIL Doubly Linked List - don’t need previous node
  • 58.
    Exercises Pg 872# 16 Pg 880 # 9-19