Presentation is loading. Please wait.

Presentation is loading. Please wait.

History of Computing – Pascal

Similar presentations


Presentation on theme: "History of Computing – Pascal"— Presentation transcript:

1 History of Computing – Pascal
Prof. Steven A. Demurjian Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Box U-255 Storrs, CT (860) 486–4818 (Office) (860) (CSE Office)

2 GNU Pascal http://www.gnu-pascal.de/gpc/h-install.html
Suggest Dev-Pascal

3 Dev Pascal

4 New Source File

5 Cut and Paste in Code/Execute Compile

6 Hit Execute

7 Another Sample

8 Another Example

9 Read/Write from files letterGrades.txt A B D pointGrades.txt 4 3 1
program readwritetofiles; var readfilename : string; writefilename : string; myreadfile : text; mywritefile : text; c : char; gpa : integer; Begin (* put files in c:\Dev-Pas directory *) readfilename:='letterGrades.txt'; writefilename:='pointGrades.txt'; assign(myreadfile, readfilename); reset(myreadfile); assign(mywritefile, writefilename); rewrite(mywritefile); while NOT EOF (myreadfile) do begin readln(myreadfile, c); case (c) of 'A' : gpa := 4; 'B' : gpa := 3; 'C' : gpa := 2; 'D' : gpa := 1; 'F' : gpa := 0; otherwise gpa := -1; end; (* case *) writeln(mywritefile, gpa); end; writeln(mywritefile,'Completed writing'); close(myreadfile); close(mywritefile); end. letterGrades.txt A B D pointGrades.txt 4 3 1 Completed writing

10 Reading and writing lines
program readwritetofiles; var readfilename : string; writefilename : string; myreadfile : text; mywritefile : text; line : packed array [1..100] of char; begin (* put files in c:\Dev-Pas directory *) readfilename:='inputfile.txt'; writefilename:='outputfile.txt'; assign(myreadfile, readfilename); reset(myreadfile); assign(mywritefile, writefilename); rewrite(mywritefile); while NOT EOF (myreadfile) do readln(myreadfile, line); writeln(mywritefile, line); end; writeln(mywritefile,'Completed writing'); close(myreadfile); close(mywritefile); end. inputfile.txt Here is a file with multiple words that you also have to process outputfile.txt Here is a file with multiple words that you also have to process Completed writing For Pascal Project – read a line at a time and Process the array of char

11 Even worked on HoCMoviesAssignment.txt
terms assessing the ?realistic? nature of the computing in the movie as compared to the release time In this assignment related to HoC, you are to select one of the movies listed below to watch and rev movie. You are to assess the movies in terms of HoC in regards to the following questions: 1. Identify and discuss technologies/software in the movie. 3. Are the technologies/software Futuristic at time Movie Released? 2. Are the technologies/software Realistic at time Movie Released? 4. Are any of the Futuristic technologies/software available today? 5. When did the Futuristic technologies/software become available? 6. Are any of Futuristic technologies/software still not available? On the horizon? 7. Does the movie contain technologies/software now Available? 8. Identify and discuss any ethical, social, or professional issues in the movie. 9. Any other pertinent information related to HoC? These movies were selected from: * Billion Dollar Brain (1967) * Desk Set (1957) * 2001: A Space Odyssey (1968) * The Computer Wore Tennis Shoes (1969) * Colossus: The Forbin Project (1970) * The Aries Computer (1972) * The Andromeda Strain (1971) * Demon Seed (1977) * Blade Runner (1982) * Tron (1982) * Electric Dreams (1984) * WarGames (1983) * D.A.R.Y.L. (1985) * Prime Risk (1985) * Flight of the Navigator (1986) * Defense Play (1989) * Short Circuit (1986) * Sneakers (1992) * Disclosure (1994) * Hackers (1995) * The Net (1995) If you have another movie, before 1995, that you want to review, please me for approval. Deliverable: 2 page MS word document that explores answers each of the questions given above. 1 pag is 12pt, 1in margins, single spaced, Times New Roman fonts. You must submit an MS Word Document. ? You can use the next page as a template for your submission. Name: Movie: HoC Movies Assessment/Analysis Assignment Completed writing

12 Getting Started With Pascal Programming
Getting Started With Pascal Programming

13 Basic Structure Of Pascal Programs
Program name.p (Pascal source code) Part I: Header Program documentation program name (input, output); Part II: Declarations const : Part III: Statements begin : end.

14 Details Of The Parts Of A Pascal Program
Headers Program documentation Version number, date of last modification, what does the program do etc. Comments for the reader of the program (and not the computer) (* Marks the beginning of the documentation *) Marks the end of the documentation Program heading Name of program, input and/or output operations performed by the program Example (* * Tax-It v1.0: This program will electronically calculate your tax return. *) program taxIt (input, output);

15 The Smallest Pascal Program
(* * Smallest.p: * The smallest Pascal program that will still compile written by James Tam * v1.0. *) program smallest; begin end. Note: The name "smallest" should match the filename "smallest.p". You can find an online version of this program in the Unix file system under /home/231/examples/intro/smallest.p (the compiled version is called "smallest").

16 Variables Set aside a location in memory
Used to store information (temporary) Types: integer – whole numbers real – whole numbers and fractions Can't start or end with a decimal char – alphabetic, numeric and miscellaneous symbols boolean – true or false values Usage: Declaration Accessing or assigning values to the variables Real – complete – must include a fractional and a whole number portion e.g., 82.1 not 82. Getting Started With Pascal Programming

17 Declaring Variables (2)
Occurs in the variable declaration ("var") section i.e., var name of first variable, name of second variable…: type of variables; e.g., height, weight: real; age: integer;

18 Accessing And Assigning Values To Variables (2)
Assignment Performed via the assignment operator := Usage: Destination := Source;1 Example: x := 5; x:= y; interest := principle * rate; character := 'a'; Avoid assigning mixed types e.g., var num1: integer; num2: real; begin num1 = 12; num2 = 12.5; num2 := num1; 1 The source can be any expression (constant, variable or formula) Not allowed! num1 := num2;

19 Named Constants (2) Examples: const TAXRATE = 0.25; SAMPLESIZE = 1000;
YES = True; NO = False;

20 Output Displaying information onscreen
Done via the write and writeln statements Syntax (either write or writeln): write ('text message'); or writeln('text message'); write(name of variable or constant); writeln (name of variable or constant); write('message', name of variable, 'message'…); writeln('message', name of variable, 'message'…);

21 Output (2) Examples: var num : integer; begin num := 10;
writeln('line1'); write('line2A'); writeln('line2B'); writeln(num); writeln('num=',num); line1 line2Aline2B 10 num=10 Getting Started With Pascal Programming

22 Automatic formatting of output
Formatting Output Automatic formatting of output Field width: The computer will insert enough spaces to ensure that the information can be displayed. Decimal places: For real numbers the data will be displayed in exponential form. Manually formatting of output: Syntax: write or writeln (data: Field width for data: Number decimal places for data); Getting Started With Pascal Programming

23 Formatting Output (2) Examples var num : real; begin num := 12.34;
writeln(num); writeln(num:5:2); e+01 12.34 Getting Started With Pascal Programming

24 Formatting Output (3) If the field width doesn’t match the actual size of the field Field width too small – extra spaces will be added for numerical variables but not for other types of data. Examples: num := ; writeln(num:3); writeln('123456':3); Field width too large – the data will be right justified (extra spaces will be put in front of the data). num := 123; writeln(num:6); Writeln('123':6); Eg1., Eg2., 123 Eg3.,---123 Eg4.,---123 Getting Started With Pascal Programming

25 Formatting Output (4) If the number of decimal places doesn’t match the actual number of decimal places. Set number of decimal places less than the actual number of decimal places – number will be rounded up. Example: num1 := writeln (num1:6:2); Set number of decimal places greater than the actual number of decimal places – number will be padded with zeros. num1 := ; writeln(num1:6:6); e.g1., e.g2., Getting Started With Pascal Programming

26 Formatting Output: A Larger Example
For the complete program and executable look under /home/231/examples/intro/out1.p (out1 for the compiled version) program out1; var num1 : integer; num2 : real; begin num1 := 123; num2 := ; writeln('Auto formatted by Pascal', num1, num2); writeln('Manual format':13, num1:3, num2:7:3); writeln('Manual not enough':13, num1:2, num2:6:3); writeln('Manual too much':16, num1:4, num2:8:4); end. Auto formatted by Pascal e+02 Manual format Manual not en Manual too much Getting Started With Pascal Programming

27 Input The computer program getting information from the user
Done via the read and readln statements Syntax: (single input) read (name of variable); or readln (name of variable); (multiple inputs) read (nv1, nv2…); readln (nv2, nv3…);

28 Input (2) Examples: var num1, num2 : integer begin read (num1);
read (num1, num2);

29 Input: Read Vs. Readln Both: Read Readln
Reads each value inputted and matches it to the corresponding variable. Read If the user inputs additional values they will remain Readln Any additional values inputted will be discarded

30 Input: Read Vs. Readln (An example)
For the complete version of this program look in Unix under: /home/231/examples/intro/read1.p (or read1 and read2 for the compiled version) e.g., read1.p write('Input some integers making sure to separate each one with a space '); write('or a new line: '); read (num1, num2); write('or a newline: '); read(num3, num4); Getting Started With Pascal Programming

31 Input: Read Vs. Readln (An example (2))
For the complete version of this program look in Unix under: /home/231/examples/intro/read2.p (or read2 for the compiled version) e.g., read2.p write('Input some integers making sure to separate each one with a space '); write('or a newline: '); readln (num1, num2); readln(num3, num4); 5 6 Getting Started With Pascal Programming

32 Extra Uses Of Readln To filter out extraneous input As an input prompt
e.g., writeln('To continue press return'); readln;

33 Remaining Topics Arrays Conditionals Looping Files
Multi-Dimensional Arrays Functions/Procedures Pointers and Lists \

34 Arrays const CLASSSIZE = 5; var
classGrades : array [1..CLASSSIZE] of real; i : integer; total, average : real; begin total := 0;

35 for i := 1 to CLASSSIZE do begin
write('Enter grade for student no. ', i, ': '); readln (classGrades[i]); total := total + classGrades[i]; end; average := total / CLASSSIZE; writeln; writeln('The average grade is ', average:6:2, '%'); writeln('Grade for student no. ', i, ' is ', classGrades[i]:6:2, '%');

36 CONDITIONALS: If-Then-Else (Simple Body)
Body of if-then-else consists of a single statement Format: if (Boolean Expression) then s1 else s2; s3; No semi-colon (indicates end of decision-making!)

37 If-Then-Else (Simple Body(2))
Example (for full example look under /home/231/examples/decisions/simpleIfThenElse.p): if (x = 1) then writeln('body of if') else writeln('body of else'); writeln('after if-then-else');

38 If-Then-Else (Compound Body)
Body of if-then-else consists of multiple statements Format: if (Boolean Expression) then begin s1; : sn; end else sn+1; sn + m; end; Sn + m + 1; No semi-colon (marks end of decision-making!)

39 If-Then (Compound Body(2))
Example (for full example look under /home/231/examples/decisions/compoundIfThenElse.p): if (x = 1) then begin writeln('Body of if 1'); writeln('Body of if 2'); end else writeln('Body of else 1'); writeln('Body of else 2'); end; writeln('after if-then-else');

40 Case Statements An alternative to the if, else-if (only one condition is true) Format (integer): Case (expression) of i1: body; i2: : in: otherwise: Expression (variable, constant, arithmetic) must evaluate to an integer

41 Case Statements: Integer Example
Example (look for complete example in Unix under /home/231/examples/decisions/caseOf1.p): case (gpa) of 4: begin writeln(‘You got an A’); end; (* GPA of 4 *) 3: writeln(‘You got a ‘B’); end; (* GPA of 3 *) 2: begin writeln(‘You got a C’); end; (* GPA of 2 *) 1: writeln(‘You got a D’); end; (* GPA of 1 *) 0: writeln(‘You got an F’); end; (* GPA of 0 *) end; (* case *)

42 Case Statements: Characters
Format (char): Case (expression) of ‘c1’: body; ‘c2’: : ‘cn’: otherwise Expression (variable, constant, arithmetic) must evaluate to a character

43 Case Statements: Character Example
case (letter) of ‘A’: begin writeln(‘GPA = 4’); end; (* GPA of 4 *) ‘B’: writeln(‘GPA = 3’); end; (* GPA of 3 *) ‘C’: begin writeln(‘GPA = 2’); end; (* GPA of 2 *) ‘D’: writeln(‘GPA = 1’); end; (* GPA of 1 *) ‘F’: writeln(‘GPA = 0’); end; (* GPA of 0 *) end; (* case *)

44 Pre-Test Loop: While-Do
Can be used if the number of times that the loop executes is not known in advance. Syntax: while (Boolean expression) do body Example (Full text-only version can be found in Unix under /home/231/examples/repetition/whileDo.p) i: = 1; while (i <= 10) do begin writeln('i = ', i); i := i + 1; end; (* while *) Initialize control Test condition Execute body Update control

45 First For Loop Example Example one (A compilable text-only version can be found in Unix under /home/231/examples/repetition/forLoopUp.p) var i, total : integer; begin total := 0; for i := 1 to 10 do total := total + i; writeln('i = ':4, i:2, 'total = ':13, total:2); end; (* for *) end. Initialize control Update control Test condition Execute body

46 Second For Loop Example
Example one (A compilable text-only version can be found in Unix under /home/231/examples/repetition/forLoopDown.p) var i, total : integer; begin total := 0; for i := 5 downto 1 do total := total + i; writeln('i = ':4, i:2, 'total = ':13, total:2); end; (* for *) end.

47 Post Test Loops: Repeat-Until
Used instead of a while-do loop if you need the loop to execute at least once. Syntax: repeat body until (Boolean expression);

48 Repeat-Until: An Example (2)
begin answer := trunc(Random * MAX); write('Enter your guess: '); readln(guess); if (guess = answer) then writeln('You guessed correctly!') else writeln('You guessed incorrectly'); writeln('Play again?'); writeln('Enter "Y" or "y" to play again'); writeln('Enter "N" or "n" otherwise'); write('Choice: '); readln(choice); end; until (choice = 'N') OR (choice = 'n'); Execute body Test condition Initialize control Update control

49 Infinite Loops Loops that never end (the stopping condition is never met). Infinite loops can be caused by logical errors: The loop control is never updated (Example 1). The updating of the loop control never brings it closer to the stopping condition (Example 2). Example 1 (a compilable version can be found in Unix under /home/231/examples/repetition/infinite1.p) i := 1; while (i < 10) do writeln ('i = ', i); To stop a program with an infinite loop in Unix simultaneously press the <ctrl> and the <c> keys

50 Nested Loops One loop executes inside of another loop(s).
Example structure: Outer loop (runs n times) Inner loop (runs m times) Body of inner loop (runs n x m times) Example program (complete compilable program can be found in Unix under: /home/231/examples/repetition/nested.p) for i := 1 to 2 do for j := 1 to 3 do writeln('i = ':9, i, 'j = ':9, j); writeln('All done!');

51 FILES: Indicating What File You Are Reading From
Syntax: program name (name of input file1); Example: program grades (output, letterGrades); A variable that is associated with a file on disk Syntax: name of file2 : text; Example: letterGrades : text; 1 The name of input file must correspond to an actual file in the same directory that the executable program resides 2 The name of file variable must correspond to an actual file in the same directory that the executable program resides

52 Opening Files Purpose: Syntax: Example:
Prepares the file for reading (positions the file pointer) Syntax: reset (name of input file3); Example: reset(letterGrades); 3 The name of file being opened must correspond to an actual file in the same directory that the executable program resides

53 Reading Information From Files
Performed with read or readln Syntax: read (name of input file4, variable(s)); readln (name of input file4, variable(s)); Example: readln(letterGrades, letter); 4 The name of file being read from must correspond to an actual file in the same directory that the executable program resides

54 Reading Information From Files (2)
Typically reading is done within the body of a loop Syntax: while NOT EOF (name of input file5) do begin read (name of input file5, variable(s)); readln (name of input file5, variable(s)); end; (* Done reading from input file *) Example: while NOT EOF (letterGrades) do readln(letterGrades, letter); writeln(letter); end; (* Loop to read letter grades file *) 5 The name of the input file must correspond to an actual file in the same directory that the executable program resides

55 Alternative Approach To Reading Files
Employ a sentinel in the file Keep reading from the file until the sentinel value is encountered Example: var inputFile : text; num : integer; : : readln (inputFile, num); while NOT (num = -1) do begin writeln(num); readln(inputFile, num); end; (* Done reading input file *)

56 Reading From Files: Putting It All Together
program grades (output, letterGrades); var letterGrades : text; letter : char; begin reset(letterGrades); writeln('Opening file "letterGrades" for reading.'); while NOT EOF (letterGrades) do readln(letterGrades, letter); writeln(letter); end; (* Loop to read letter grades file *) close(letterGrades); writeln('Completed reading of file "letterGrades"'); end. (* End of program *)

57 Opening The File Two methods:
Rewriting – erases the old contents of the file (rewrites over what was already there). Appending – retain the old contents of the file (appends the new information at the end). Syntax (rewriting / appending): rewrite (name of file); append (name of file); Example (rewriting / appending): rewrite(gradePoints); append(gradePoints);

58 Writing To A File: Putting It All Together
A complete version of this program can be found in Unix under: /home/231/examples/files/grades2.p program grades (output, letterGrades, gradePoints); var letterGrades : text; gradePoints : text; letter : char; gpa : integer; begin reset(letterGrades); rewrite(gradePoints); writeln('Opening file "letterGrades" for reading.'); writeln('Opening file "gradePoints" for writing.'); while NOT EOF (letterGrades) do

59 Writing To A File: Putting It All Together (2)
readln(letterGrades, letter); case (letter) of 'A' : gpa := 4; 'B' : gpa := 3; 'C' : gpa := 2; 'D' : gpa := 1; 'F' : gpa := 0; otherwise gpa := -1; end; (* case *) writeln(gradePoints, gpa); end; (* Loop to read letter grades file *) writeln('Finished reading and writing to files.'); close(letterGrades); close(gradePoints); end.

60 Details Of Write And Writeln For Files: Intuitive View
Program statement Effect on file rewrite (data); (Open file "data" and position ^ file pointer at start) write (data, 'x'); x ^ write(data, 'y'); xy write(data, 'z'); xyz writeln(data); xyz _ write(data,'a'); xyz a

61 Details Of Write And Writeln For Files: Actual View
Program statement Effect on file rewrite (data); (Open file "data" and position ^ file pointer at start) write (data, 'x'); x ^ write(data, 'y'); xy write(data, 'z'); xyz writeln(data); xyz<EOL> write(data,'a'); xyz<EOL>a A file does not consist of physical lines but instead it's a continuous stream of characters

62 Details Of Read And Readln For Files: Intuitive View1
Program statement Effect on file Effect in program reset (data); xyz (Open file "data" and position ^ file pointer at start) a read(data, ch); xyz Value of ch: 'x' ^ readln(data, ch); xyz Value of ch: 'y' ^ read(data, ch); xyz Value of ch: 'a' 1 Assume that the code on the previous slide has created the file called "data"

63 Details Of Read And Readln For Files: Actual View1
Program statement Effect on file Effect in program reset (data); xyz<EOL>a (Open file "data" and position ^ file pointer at start) read(data, ch); xyz<EOL>a Value of ch: 'x' ^ readln(data, ch); xyz<EOL>a Value of ch: 'y' ^ read(data, ch); xyz<EOL>a Value of ch: 'a' ^ read(data,ch); xyz<EOL>a 1 Assume that the code on the previous slide has created the file called "data"

64 Details Of Read And Readln For Files: Actual View1
Program statement Effect on file Effect in program reset (data); xyz<EOL>a (Open file "data" and position ^ file pointer at start) read(data, ch); xyz<EOL>a Value of ch: 'x' ^ readln(data, ch); xyz<EOL>a Value of ch: 'y' ^ read(data, ch); xyz<EOL>a Value of ch: 'a' ^ read(data,ch); xyz<EOL>a Error – reading past end of file 1 Assume that the code on the previous slide has created the file called "data"

65 Passing File Variables As Parameters
Must be passed as variable parameters only. Syntax: procedure nameProcedure (var nameFile :text); Example: procedure fileInputOuput (var letterGrades : text; var gradePoints : text);

66 MULTI-DIMENSIONAL ARRAYS: When To Use Arrays Of Different Dimensions
Determined by the data – the number of categories of information determines the no. of dimensions to use. Examples: (1D array) Tracking grades for a class Each cell contains the grade for a student i.e., grades[i] There is one dimension that specifies the student (2D array) Personal finances program One dimension of information specifies the financial category (cash in or cash out). The other dimension is used to specify the time One dimension (which student)

67 When To Use Arrays Of Different Dimensions (2)
(2D array continued) Time Financial category January February March Income -Rent -Food -Fun -Transport -Misc Net income

68 When To Use Arrays Of Different Dimensions (3)
(2D array continued) Notice that each row is merely a 1D array (A 2D array is an array containing rows of 1D arrays) [1] [2] [3] [4] Income [1] [2] [3] [4] [5] [6] [7] -Rent -Food -Fun -Transport -Misc Net income

69 When To Use Arrays Of Different Dimensions (5)
-Misc Income -Rent -Food Net income -Transport -Fun March February January John’s finances Mary’s finances Bob’s finances

70 Declaring Multi-Dimensional Arrays
Syntax: (Two dimensional arrays) Name : array [min..max, min..max] of type; (Three dimensional arrays) Name : array [min..max, min..max, min..max] of type; Example: johnFinances : array [1..7, 1..7] of real; cube : array[1..3, 1..4, 1..6] of char; Rows Columns Syntax: name [row][column] := name [row][column]; finances [1][1] := 4500; writeln (finances[1][1]);

71 Example Program: Map Generator And Editor
program map (input, output); const MAXROWS = 10; MAXCOLUMNS = 10; var world : array[1..MAXROWS, 1..MAXCOLUMNS] of char; r, c : integer; randomValue : real; quitChoice : char; editChoice : char; rowToEdit : integer; columnToEdit : integer; charToChange : char;

72 Example Program: Map Generator And Editor (2)
begin for c := 1 to MAXCOLUMNS do world[1][c] := '-'; world[MAXROWS][c] := '-'; for r := 1 to MAXROWS do world[r][1] := '|'; world[r][MAXCOLUMNS] := '|';

73 Example Program: Map Generator And Editor (3)
for r := 2 to (MAXROWS-1) do begin for c:= 2 to (MAXCOLUMNS-1) do randomValue := Random; if (randomValue <= 0.05) then world [r][c] := '~' else if (randomValue <= 0.25) then world [r][c] := '^' else if (randomValue <= 0.30) then world [r][c] := 'C' else if (randomValue <= 0.40) then world [r][c] := 'T' else world [r][c] := ' '; end; (* inner for *) end; (* outer for *)

74 Example Program: Map Generator And Editor (4)
repeat begin for r := 1 to MAXROWS do for c := 1 to MAXCOLUMNS do write(world[r][c]); end; (* inner for loop *) writeln; end; (* for loop - displays world *) write('Enter "Y" or "y" if you wish to edit the world or the return '); write('key otherwise: '); readln(editChoice);

75 Example Program: Map Generator And Editor (5)
if (editChoice = 'Y') OR (editChoice = 'y') then begin writeln; write('Enter row (2 - 9) to edit: '); readln(rowToEdit); write('Enter column (2 - 9) to edit: '); readln(columnToEdit); if (rowToEdit < 2) OR (rowToEdit > (MAXROWS-1)) OR (columnToEdit < 2) OR (columnToEdit > (MAXCOLUMNS-1)) then writeln('Value for row must be in the range of 2 - 9')

76 Example Program: Map Generator And Editor (6)
else begin writeln('What do wish to change this square to? Choices include:'); writeln('"~" for water'); writeln('"^" for trees'); writeln('"C" for a city'); writeln('"T" for a town'); writeln('" " (A space) for an open field'); write('Enter choice and hit return: '); readln(charToChange); world[rowToEdit][columnToEdit] := charToChange; end; (* else *) end; (* if edit mode chosen. *) writeln('Type "Q" or "q" to quit, or return to continue: '); readln(quitChoice); end; (* repeat loop *) until (quitChoice = 'Q') OR (quitChoice = 'q'); end.

77 RECORDS: Declaring Types
Syntax: Type Name(1) = Type for name (1); Name(2) = Type for name (2); : : : : Name(n) = Type for name (n); Example: World = array [1..20,1..20] of char; Var map : World; biosphere: World;

78 Declaring Types (3) Can be used to provide alternative names for existing types Example: type FloatingPoint = real; var gpa : FloatingPoint; income: real;

79 Declaring Types (3) Can be used to provide alternative names for existing types Example: type FloatingPoint = real; var gpa : FloatingPoint; income: real; Original type still usable

80 Declaring Types (4) Example: Type world = array [1..20,1..20] of char;
Var map : world; biosphere: world; Declaring the type - defining what the type consists of Declaring variables of the new type

81 Where Type Declarations Fit Into Pascal Programs
program name; (* Declarations *) const (* Declaration of constants) type (* Declaration of new types *) var (* Declaration of variables *) (* Declarations of functions & procedures – defining what they do *) begin end.

82 Declaring Records Syntax: Name = record
name of field (1) : type of field (1); name of field (2) : type of field (2); name of field (3) : type of field (3); : : : : : : name of field (n) : type of field (n); end; (* Record declaration *)

83 Declaring Records (2) Example: Syntax: Example: StudentRecord = record
studentIdentification : integer; firstName : array [1..20] of char; lastName : array [1..20] of char; initial : char; addressLineOne : array [1..20] of char; addressLineTwo : array [1..20] of char; phoneNumber : integer; end; Syntax: name of variable : name of declared record; Example: jamesTam : studentRecord; bartSimpson : studentRecord;

84 Declaring Arrays Of Records
Method: 1) Declare the record 2) Declare a type for the array of records The second step is essential in Pascal for passing the array as a parameter into functions and procedures!

85 Declaring Arrays Of Records
type StudentRecord = record studentIdentification : integer; firstName : array [1..20] of char; lastName : array [1..20] of char; initial : char; addressLineOne : array [1..20] of char; addressLineTwo : array [1..20] of char; phoneNumber : integer; end; StudentRecordList = array [ ] of StudentRecord; var universityOfCalgaryStudentRecords : StudentRecordList;

86 Declaring Arrays Of Records
type StudentRecord = record studentIdentification : integer; firstName : array [1..20] of char; lastName : array [1..20] of char; initial : char; addressLineOne : array [1..20] of char; addressLineTwo : array [1..20] of char; phoneNumber : integer; end; StudentRecordList = array [ ] of StudentRecord; var universityOfCalgaryStudentRecords : StudentRecordList; Declaring Record Declaring a new type Declaring a new instance of type "StudentRecordList"

87 Passing Records And Arrays Of Records As Parameters
Looks the same as passing in other types of variables Can be passed in as value or variable parameters Examples (function or procedure calls): displayStudent (jamesTam); initializeStudentRecords (universityOfCalgaryStudentRecords); Examples (function or procedure definition) procedure displayStudent (jamesTam :StudentRecord); begin end; (* Procedure displayStudent *) procedure initializeStudentRecords (var universityOfCalgaryStudentRecords : StudentRecordList); end; (* Procedure initializeStudentRecords *)

88 Returning Composite Types From Functions
You cannot return composite types of variables (arrays and records) from functions. To have changes to these types of variables be retained after the function or procedure has ended they must be passed as variable parameters (example shown on previous slide)

89 Using Record Variables
Indicate which variable you wish to use (by stating the name of the variable) e.g., type Person = Record name : array [1..8] of char; age : integer; height : real; weight : real; end; (* Declaration of Person *) begin jo, jack : Person;

90 Using Record Variables (2)
(If applicable) indicate which field of the record that you wish to use. e.g., jo.name := 'joanne'; jo.age := 20; jo.height := 68.5; jo.weight := 110; Assignment Can be done on a field by field basis: jack.age = jo.age; Can be done for the whole record (if the records are the same type) jack := jo;

91 Using Record Variables (3)
Input and output via read/readln and write/writeln Must be done on a field by field basis e.g., write('Enter age for Jack : '); readln(jack.age); writeln('Jack is ', jack.age, ' years old);

92 A Shortcut For Referencing All The Fields Of A Record: With-do
Allows you to refer to the fields of a record without having to constantly refer to the name of the record variable. Syntax: with name do body Example: with jack do begin writeln('Jack's stats'); writeln('Age: ', age); writeln('Height :', height); writeln('Weight :', weight); end; (* With do for jack *)

93 Putting This All Together
You can find a version of this program in Unix under: /home/231/examples/records/person.p program person (input, output, peopleValues); const NAMELENGTH = 16; NOPEOPLE = 4; type Person = Record name : array [1..NAMELENGTH] of char; age : integer; height : real; weight : real; end; (* Declaration of Person *) People = array [1..NOPEOPLE] of Person; var peopleValues : text;

94 Putting This All Together (2)
procedure manuallyInitializeCalgaryPeople (var calgaryPeople : People ); var i : integer; begin for i := 1 to NOPEOPLE do with calgaryPeople[i] do write('Enter name of person: '); readln(name); write('Enter age of person in whole years: '); readln(age); write('Enter the height of the person in inches: '); readln(height); write('Enter the weight of the person in pounds: '); readln(weight); writeln; end; (* With-do *) end; (* Initialization for-loop *) end; (* Procedure manuallyInitializeCalgaryPeople *)

95 Putting This All Together (3)
procedure defaultInitializeCalgaryPeople (var calgaryPeople : People); var i : integer; begin reset(peopleValues); writeln('Reading initial values from file "peopleValues"'); for i := 1 to NOPEOPLE do with calgaryPeople[i] do readln(peopleValues,name); readln(peopleValues,age); readln(peopleValues,height); readln(peopleValues,weight); readln(peopleValues); end; (* With-do *) end; (* Initialization for-loop *) close(peopleValues); end; (* Procedure defaultInitializeCalgaryPeople *)

96 Putting It All Together (4)
procedure displayCalgaryPeople (calgaryPeople : People); var i : integer; begin writeln; for i := 1 to NOPEOPLE do with calgaryPeople[i] do writeln('Name: ', name); writeln('Age: ', age); writeln('Height: ', height:0:2); writeln('Weight: ', weight:0:2); end; (* With-do *) end; (* Display for-loop *) end;

97 Putting It All Together (5)
begin var calgaryPeople : People; var initializationMethod : integer; writeln; writeln('Select method to set starting values for the people'); writeln('Enter "1" to read the values in from a file'); writeln('Enter "2" to manually enter in the values yourself'); write('Enter your choice: '); readln(initializationMethod); case (initializationMethod) of 1 : defaultInitializeCalgaryPeople(calgaryPeople); displayCalgaryPeople(calgaryPeople); end; 2 : manuallyInitializeCalgaryPeople(calgaryPeople);

98 Putting It All Together (6)
begin var calgaryPeople : People; var initializationMethod : integer; writeln; writeln('Select method to set starting values for the people'); writeln('Enter "1" to read the values in from a file'); writeln('Enter "2" to manually enter in the values yourself'); write('Enter your choice: '); readln(initializationMethod); case (initializationMethod) of 1 : defaultInitializeCalgaryPeople(calgaryPeople); displayCalgaryPeople(calgaryPeople); end; 2 : manuallyInitializeCalgaryPeople(calgaryPeople);

99 Putting It All Together (6)
otherwise begin writeln('Your choice was not one of the available options.'); writeln('Restart program and select again.'); end; (* otherwise *) end; (* case *) writeln; end.

100 FYI – REST NOT LIKELY NEEDED FOR PASCAL PROGRAMMING ASSGINMENT FUNCTIONS AND PROCEDURES Defining Procedures Syntax (Basic case – no parameters): procedure name; begin (* Statements of the function go here *) end; (* End of procedure name *) Example (Basic case – no parameters): procedure displayInstructions; writeln ('These statements will typically give a high level'); writeln('overview of what the program as a whole does'); end; (* End of procedure displayInstructions *)

101 Procedures: Putting Together The Basic Case
procedure displayInstructions; begin writeln ('These statements will typically give a high level'); writeln('overview of what the program as a whole does'); end; (*Procedure displayInstructions *) displayInstructions; writeln('Thank you, come again!'); end. (* Program *)

102 Procedures: Putting Together The Basic Case
procedure displayInstructions; begin writeln ('These statements will typically give a high level'); writeln('overview of what the program as a whole does'); end; (*Procedure displayInstructions *) displayInstructions; writeln('Thank you, come again!'); end. (* Program *) Procedure definition Procedure call

103 Defining Procedures With Parameters
Syntax: procedure name (Name of parameter 1 : type of parameter 1; Name of parameter 2 : type of parameter 2; : : Name of parameter n : type of parameter n); begin (* Statements of the function go here *) end; Example: procedure celciusToFahrenheit (celciusValue : real); var fahrenheitValue : real; fahrenheitValue := 9 / 5 * celciusValue + 32; writeln(temperature in Celsius: ', celciusValue:0:2); writeln(temperature in Fahrenheit: ', fahrenheitValue:0:2); end; (* Procedure celciusToFahrenheit *)

104 Procedures: Putting Together The Case With Parameters
A compilable version of this example can be found in Unix under /home/231/examples/functions/temperatureConverter..p program temperatureConverter (input, output); var celciusValue : real; procedure celciusToFahrenheit (celciusValue : real); fahrenheitValue : real; begin fahrenheitValue := 9 / 5 * celciusValue + 32; writeln('Temperature in Celsius: ', celciusValue:0:2); writeln('Temperature in Fahrenheit: ', fahrenheitValue:0:2); end; (* Procedure celciusToFahrenheit *)

105 Procedures: Putting Together The Case With Parameters
A compilable version of this example can be found in Unix under /home/231/examples/functions/temperatureConverter.p program temperatureConverter (input, output); var celciusValue : real; procedure celciusToFahrenheit (celciusValue : real); fahrenheitValue : real; begin fahrenheitValue := 9 / 5 * celciusValue + 32; writeln('Temperature in Celsius: ', celciusValue:0:2); writeln('Temperature in Fahrenheit: ', fahrenheitValue:0:2); end; (* Procedure celciusToFahrenheit *) Procedure definition

106 Procedures: Putting Together The Case With Parameters (2)
begin writeln; writeln('This program will convert a given temperature from a Celsius's); writeln('value to a Fahrenheit value.'); write('Input temperature in Celsius: '); readln(celciusValue); celciusToFahrenheit(celciusValue); writeln('Thank you and come again.'); end. (* Program *)

107 Procedures: Putting Together The Case With Parameters (2)
begin writeln; writeln('This program will convert a given temperature from a Celsius's); writeln('value to a Fahrenheit value.'); write('Input temperature in Celsius: '); readln(celciusValue); celciusToFahrenheit(celciusValue); writeln('Thank you and come again.'); end. (* Program *) Procedure call

108 How Retain Information From A Module After The Module (Function Or Procedure) Has Ended (2)
e.g., producing an income statement program taxes (input, output); var (* Assume declarations made *) begin calculateGrossProfit (grossSales); : : calculateGrossProfit (grossSales: real); var (* Assume declarations made *) begin grossProfit := grossSales – costOfGoodsSold; end;

109 Defining Functions Syntax: Example:
function name (Name of parameter 1 : type of parameter 1; Name of parameter 2 : type of parameter 2; : : Name of parameter n : type of parameter n): return type; begin (* Statements of the function go here *) : : name := expression; (* Return value *) end; Example: function calculateGrossIncome (grossSales, costOfGoodsSold : real) : real; calculateGrossIncome := grossSales - costOfGoodsSold; Should be the last statement in the function

110 Functions: Putting It All Together
A compilable version of this example can be found in Unix under /home/231/examples/functions/financialStatements.p program financialStatments (input, output); function calculateGrossIncome (grossSales, costOfGoodsSold : real) : real; begin calculateGrossIncome := grossSales - costOfGoodsSold end; function calculateNetIncome (grossIncome, expenses : real) : real; calculateNetIncome := grossIncome - expenses; Function definitions

111 Functions: Putting It All Together (2)
procedure produceIncomeStatement; var grossSales : real; costOfGoodsSold : real; grossIncome : real; expenses : real; netIncome : real; begin write('Input gross sales $'); readln(grossSales); write('Input cost of the goods that were sold $'); readln(costOfGoodsSold); write('Input corporate expenses $'); readln(expenses); grossIncome := calculateGrossIncome (grossSales, costOfGoodsSold); netIncome := calculateNetIncome (grossIncome, expenses); Function calls

112 Functions: Putting It All Together (3)
(* Procedure produceIncomeStatement *) writeln; writeln('Gross sales $':26, grossSales:0:2); writeln('Less: cost of goods sold $':26, costOfGoodsSold:0:2); writeln('Gross income $':26, grossIncome:0:2); writeln('Less: expenses $':26, expenses:0:2); writeln('Net income $':26, netIncome:0:2); end; (* End of procedure produceIncomeStatement *)

113 Functions: Putting It All Together (3)
(* Start of program *) begin writeln; writeln('This program will produce an income statement based upon your'); writeln('gross sales figures, the cost of the goods that you sold and writeln('your expenses.'); produceIncomeStatement; writeln('Thank you, come again!'); end. (* End of entire program. *)

114 Procedure Definitions When Passing Parameters As Variable Parameters
Syntax: procedure name (var Name of parameter 1 : type of parameter 1; var Name of parameter 2 : type of parameter 2; : : var Name of parameter n : type of parameter n); begin (* Statements of the function go here *) end; Example: procedure tabulateIncome ( grossSales : real; costOfGoodsSold : real; var grossIncome : real; expenses : real; var netIncome : real); grossIncome := grossSales - costOfGoodsSold; netIncome := grossIncome - expenses;

115 Calling Procedures With Variable Parameters
Same as calling procedures with value parameters! Syntax: name (name of parameter 1, name of parameter 2…name of parameter n); Example: tabulateIncome(grossSales,costOfGoodsSold,grossIncome,expenses, netIncome);

116 Passing Variable Parameters: Putting It All Together
A compilable version of this example can be found in Unix under /home/231/examples/functions/financialStatements2.p program financialStatments (input, output); procedure getIncomeInformation (var grossSales : real; var costOfGoodsSold : real; var expenses : real); begin write('Input gross sales $'); readln(grossSales); write('Input the cost of the goods that were sold $'); readln(costOfGoodsSold); write('Input business expenses $'); readln(expenses); end; (* End of procedure getIncomeInformation *)

117 Passing Variable Parameters: Putting It All Together (2)
procedure tabulateIncome ( grossSales : real; costOfGoodsSold : real; var grossIncome : real; expenses : real; var netIncome : real); begin grossIncome := grossSales - costOfGoodsSold; netIncome := grossIncome - expenses; end; (* End of procedure tabulateIncome *) procedure displayIncomeStatement (grossSales : real; grossIncome : real; netIncome : real);

118 Passing Variable Parameters: Putting It All Together (3)
(* Procedure displayIncomeStatement *) begin writeln; writeln('INCOME STATEMENT':40); writeln('Gross sales $':40, grossSales:0:2); writeln('Less: Cost of the goods that were sold $':40, costOfGoodsSold:0:2); writeln('Equals: Gross Income $':40, grossIncome:0:2); writeln('Less: Business Operating Expenses $':40, expenses:0:2); writeln('Equals: Net income $':40, netIncome:0:2); end; (* End of procedure displayIncomeStatement *) procedure produceIncomeStatement; var grossSales, grossIncome, costOfGoodsSold, expenses, netIncome :real;

119 Passing Variable Parameters: Putting It All Together (3)
begin getIncomeInformation(grossSales, costOfGoodsSold, expenses); tabulateIncome(grossSales,costOfGoodsSold,grossIncome,expenses,netIncome); displayIncomeStatement (grossSales,costOfGoodsSold,grossIncome,expenses,netIncome); end; (* Begin main program *) writeln; writeln('This program will produce an income statement based upon your'); writeln('gross sales figures, the cost of the goods that you sold and'); writeln('your expenses.'); produceIncomeStatement; writeln('Thank you, come again!'); end. (* End of main program *)

120 POINTERS Types Of Variables
Pascal Variables 1.Data 2. Addresses (pointers) a. Simple (atomic) b. Aggregate (composite) integer char boolean real Homogenous(arrays) Heterogeneous(records)

121 Declaration Of Pointer Variables
Syntax: type type name = ^ type pointed to1; var pointer name : type name; Example: IntegerPointer = ^integer; numPtr1, numPtr2 : integerPointer; num : integer; 1 You can also use the instead of the “up-arrow” ^ to declare a pointer variable

122 Allocating Memory For Pointers
Static vs. dynamic memory e.g., array Allocating memory Deallocating memory Syntax Syntax new (pointer name); dispose (pointer name); Example Example new (numPtr1); dispose (numPtr1);

123 Allocating Memory For Pointers
Static vs. dynamic memory e.g., array Allocating memory Deallocating memory Syntax Syntax new (pointer name); dispose (pointer name); Example Example new (numPtr1); dispose (numPtr1); Syntax: pointer name := NIL; Example numPtr1 := NIL;

124 Using Pointers : Assignment
Syntax: (Pointer) pointer name := pointer name; (Memory pointed to) pointer name ^ := expression; Example: numPtr1 := numPtr2; numPtr1^ := 100;

125 Using Pointers : Allowable Operations (Equity)
Syntax: (Pointer) if (pointer name 1 = pointer name 2) then (Memory pointed to) if (pointer name 1 ^ = pointer name 2 ^) then Example: if (numPtr1 := numPtr2) then if (numPtr1 ^ := numPtr2 ^) then

126 Using Pointers : Allowable Operations (Inequity)
Syntax: (Pointer) if (pointer name 1 <> pointer name 2) then (Memory pointed to) if (pointer name 1 ^ <> pointer name 2 ^) then Example: if (numPtr1 <> numPtr2) then if (numPtr1 ^ <> numPtr2 ^) then

127 Accessing Pointers Syntax: Example: (Pointer) pointer name
(Memory pointed to) pointer name ^ Example: numPtr1 := numPtr 2; writeln(numPtr1^);

128 Pointers : First Example
A full version of this example can be found in Unix under: /home/231/examples/pointers/pointer1.p program pointer1 (output); type IntegerPointer = ^integer; var num, temp : integer; numPtr1, numPtr2 : integerPointer; begin writeln('Example One'); num := 10; new(numPtr1); new(numPtr2); numPtr1^ := 100; numPtr2^ := 100;

129 Pointers : First Example (2)
writeln('num = ':11, num:3); writeln('numPtr1^ = ':11, numPtr1^:3); writeln('numPtr2^ = ':11, numPtr2^:3); if (numPtr1 = numPtr2) then writeln('numPtr1 and numPtr2 point to the same location in memory') else writeln('numPtr1 and numPtr2 point to two separate locations'); if (numPtr1 ^= numPtr2^) then writeln('Value of what numPtr1 and numPtr2 point to are equal.') writeln('Value of what numPtr1 and numPtr2 point to are equal.'); writeln('Example two'); temp := num; num := numPtr1^;

130 Pointers: First Example (3)
writeln('Example three'); numPtr1^ := num; num := 2; writeln('num = ':11, num:3); writeln('numPtr1^ = ':11, numPtr1^:3); writeln('Example four'); numPtr2 ^ := 66; numPtr1 := numPtr2; if (numPtr1 = numPtr2) then writeln('numPtr1 and numPtr2 point to the same location in memory') else writeln('numPtr1 and numPtr2 point to two separate locations'); numPtr2^ := 33; writeln('numPtr1^ = ':11, numPtr1^); writeln('numPtr2^ = ':11, numPtr2^);

131 Pointers: First Example (4)
dispose(numPtr1); dispose(numPtr2); numPtr1 := NIL; numPtr2 := NIL;

132 Pointers As Value Parameters
Need to define a type for the pointer first! E.g., type CharPointer = ^char; Syntax: procedure procedure name (pointer name (1) : type of pointer (1); pointer name (2) : type of pointer (1); : : pointer name (n) : type of pointer (n)); function function name (pointer name (1) : type of pointer (1); Example: procedure proc1 (charPtr : CharPointer);

133 Pointers As Variable Parameters
Need to define a type for the pointer first! E.g., type CharPointer = ^char; Syntax: procedure procedure name (var pointer name (1) : type of pointer (1); var pointer name (2) : type of pointer (1); : : var pointer name (n) : type of pointer (n)); Example: procedure proc2 (var charPtr : CharPointer);

134 Returning Pointers From Functions
Need to define a type for the pointer first E.g., type CharPointer = ^char; Syntax: function function name: function return type; begin function name := expression; end;

135 Returning Pointers From Functions (2)
Example: function fun: CharPointer; var temp : CharPointer; begin new(temp); temp^ := '#'; fun := temp; end;

136 Pointers: Second Example
A full version of this program can be found in Unix under: /home/231/examples/pointers/pointer2.p program pointer2 (output); type CharPointer = ^char; procedure proc1 (charPtr : CharPointer); var temp : CharPointer; begin writeln; writeln('In procedure proc1'); new(temp); temp^ := 'A'; charPtr := temp; writeln('temp^ = ', temp^); writeln('charPtr^ = ', charPtr^); end;

137 Pointers: Second Example (2)
procedure proc2 (var charPtr : CharPointer); var temp : CharPointer; begin writeln; writeln('In procedure proc2'); new(temp); temp^ := 'A'; charPtr := temp; writeln('temp^ = ', temp^); writeln('charPtr^ = ', charPtr^); end;

138 Pointers: Second Example (3)
function fun: CharPointer; var temp : CharPointer; begin new(temp); temp^ := '#'; fun := temp; end;

139 Pointers: Second Example (4)
begin (* Main program *) var charPtr : CharPointer; new (charPtr); charPtr^ := 'a'; writeln; writeln('In the main program.'); writeln('charPtr^ = ', charPtr^); proc1(charPtr); writeln('After proc1'); proc2(charPtr); writeln('After proc2'); charPtr := fun; writeln('After fun'); end. (* End of main program *)

140 LINKED LISTS More complex coding may be required
Some list management functions are more elegant (and faster) Data Ptr Data Ptr Node Link List

141 Some Link List Functions
Declaring a link list Creating a new list Traversing the list Adding a node to the list Searching the list Deleting a node from the list Note: These list functions will be illustrated by portions of an example program. This program is the investors program but implemented as a link list rather than as array. The complete program can be found in Unix under: /home/231/examples/link_lists/investors.p

142 Declaring A Link List Syntax: type
Name of the list data = Type of the list data; Name of the list pointer = ^ Node; Node = Record data : Name of the list data; nextPointer : Name of the list pointer; Name of link list = Name of list pointer;

143 Declaring A Link List (2)
Example: type Client = record firstName : array [1..NAMELENGTH] of char; lastName : array [1..NAMELENGTH] of char; income : real; array [1.. LENGTH] of char; end; (* Declaration of record Client *) ListData = Client; ListPointer = ^ Node; Node = record data : ListData; nextPointer : ListPointer; end; (* Declaration of record Node *) ClientList = ListPointer;

144 Creating A New List Algorithm: Example:
The pointer to the beginning of the list is passed into the procedure as a variable parameter and initialized to NIL signifying that the new list is empty. Example: procedure createNewList (var tamjClientList : ClientList); begin tamjClientList := NIL; end; (* Procedure *)

145 Traversing The List Algorithm: Steps
1. Start by initializing a pointer to the beginning of the list. 2. If the pointer is NIL then show message indicating that there are no nodes to display and stop. 3. Process the node. 4. Move on to the next node by following the node's nextPointer (set pointer to point to the next node). 5. Repeat 3 – 4 until the end of the list is reached (pointer is NIL).

146 Traversing The List (2) Example:
procedure displayList ( tamjClientList : ClientList); var currentNode : ListPointer; begin currentNode := tamjClientList; writeln('CLIENT LIST':20); if (currentNode = NIL) then writeln; writeln('List is empty, no clients to display'); end; (* if-then *)

147 Traversing The List (3) while (currentNode <> NIL) do begin
writeln('First name: ':20, currentNode^.data.firstName); writeln('Last Name: ':20, currentNode^.data.lastName); writeln('Income $':20, currentNode^.data.income:0:2); writeln(' ':20, currentNode^.data. ); writeln; currentNode := currentNode^.nextPointer; end; (* while *) end; (* displayList *)

148 Adding A Node To The The List
Algorithm: Steps 1. Assign a pointer to the front of the list. 2. If the pointer is NIL then the list is empty and add the node to the front of the list and stop. 3. Otherwise traverse the list with two pointers, one pointer (current pointer) goes to the end of the list, the other stays one node behind it (previous pointer). 4. Attach the new node to the last node in the list (the one reached by the previous pointer). 5. The next pointer of the new node becomes NIL (indicating that this is the end of the list).

149 Adding A Node To The List (2)
Example: procedure addToList (var tamjClientList: ClientList; newNode : ListPointer); var currentNode : ListPointer; previousNode : ListPointer; begin (* Empty list add new node to front *) if (tamjClientList = NIL) then tamjClientList := newNode; newNode^.nextPointer := NIL; end

150 Adding A Node To The List (3)
else begin currentNode := tamjClientList; while (currentNode <> NIL) do previousNode := currentNode; currentNode := currentNode^.nextPointer; end; (* while *) previousNode^.nextPointer := newNode; newNode^.nextPointer := NIL; end; (* else *) end; (* Procedure *)

151 Searching The List Algorithm:
The procedure is run in order to find a node(s) that has a field which matches some desire value. Either the node or nodes will be found in the list or else the procedure will have searched every node in the list and have found no matches. A flag will be set to true or false indicating the success or failure of the search. Variables There are two pointers to the list: a. Current pointer – traverses the list from beginning to end b. Previous to first pointer – points to the node that occurs just prior to the first successful match. Note: The second pointer does not directly come into play when the user only wants to search the list. They are essential when the person wishes to erase a node from the list. Since the erase procedure calls the search procedure, it is is passed in but it's value is not used when the person just wishes to perform a search without performing a deletion. 2. A boolean that indicates the status of the search.

152 Searching The List (2) Steps
Current pointer starts at the beginning of the list. Since the search has not yet begin, previous is set to NIL and the flag is set to false. A check is performed to determine if the node is a match. If this is the case and the flag is still false (indicating that we haven't found a previous node that was a successful match) set the flag to true (since a match was found). Since the search function requires a list of all matches (and not just the first instance) don't stop searching the list. If the flag is set to false then set the previous pointer to point to the current node. If the flag is set to true then don't change the value of flag (the previous pointer tracks the node just prior to the node which first meets the search criteria). Move on to the next node (by setting the current pointer to the current node's next pointer). Continue step 2 – 4 until the end of the list is reached (current node is NIL).

153 Searching The List (3) Example:
procedure search ( tamjClientList : ClientList; desiredName : NameArray; var isFound : boolean; var previousFirst : ListPointer ); var currentNode : ListPointer; begin currentNode := tamjClientList; previousFirst := NIL; isFound := False;

154 Searching The List (4) while (currentNode <> NIL) do begin
if (desiredName = currentNode^.data.lastName) then writeln('Found contact':20); writeln('First name :':20, currentNode^.data.firstName); writeln('Last name :':20, currentNode^.data.lastName); writeln('Income $':20, currentNode^.data.income:0:2); writeln(' ':20, currentNode^.data. ); writeln; if (isFound = False) then isFound := True; end; (* if-then *)

155 Searching The List (5) if (isFound = False) then
previousFirst := currentNode; currentNode := currentNode^.nextPointer; end; (* while *) writeln('Contact not found in list'); end; (* search *)

156 Deleting A Node From The List
Algorithm: Steps Search the list (by calling the search procedure) to determine if there exists a node that matches the necessary criteria for deletion. Check the flag to determine if the search was successful or not. If the flag is false then there is no matching node in the list. Stop. There is no matching node to delete. Check to see if the node to be deleted is the first node in the list or not by determining if the previous node is NIL. If the node to be deleted is the first node then have a temporary pointer point to the first element and make the front of the list the second element. If the node to be deleted is not the first node then have a temporary pointer point to the node to be deleted. Set the next pointer of the previous node point to the node after the node to be deleted (bypassing this node) For steps 4 & 5 free up the memory allocated by the node to be deleted.

157 Deleting A Node From The List (2)
Example: procedure erase (var tamjClientList : ClientList ); var desiredName : NameArray; previousFirst : ListPointer; temp : ListPointer; isFound : boolean; begin write('Enter last name of client to delete: '); readln(desiredName); search (tamjClientList, desiredName, isFound, previousFirst); if (isFound = True) then writeln('Deleting first instance of ', desiredName); if (previousFirst = NIL) then

158 Deleting A Node From The List (3)
begin writeln('Deleting first instance of ', desiredName); if (previousFirst = NIL) then temp := tamjClientList; tamjClientList := tamjClientList^.nextPointer; end (* if-then *) else temp := previousFirst^.nextPointer; previousFirst^.nextPointer := temp^.nextPointer; end; (* else *) dispose(temp); end; (* if-then *) end; (* Procedure *)


Download ppt "History of Computing – Pascal"

Similar presentations


Ads by Google