Pascal Prof. Steven A. Demurjian

Slides:



Advertisements
Similar presentations
James Tam Linked Lists in Pascal Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
Advertisements

Introduction to Programming CSCE 110 Drawn from James Tam’s material.
J. Michael Moore Text Files CSCE 110 From James Tam’s material.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
James Tam Repetition In Pascal In this section of notes you will learn how to have a section of code repeated without duplicating the code.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
James Tam Breaking Problems Down This section of notes shows you how to break down a large programming problem into smaller modules that are easier to.
James Tam Getting Started With Pascal Programming How are computer programs created What is the basic structure of a Pascal Program Variables in Pascal.
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Arrays In this section of notes you will be introduced to a homogeneous composite type arrays.
James Tam Arrays In this section of notes you will be introduced to a composite type where all elements must be of the same type (homogeneous): arrays.
James Tam Repetition In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in your Pascal programs.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
J. Michael Moore Structured Programming CPSC 110 Drawn from James Tam's material.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
J. Michael Moore Other Control Structures CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
J. Michael Moore Modules: Getting information out CPSC 110 Influenced by material developed by James Tam & Jennifer Welch.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Getting Started With Pascal Programming How are computer programs created What is the basic structure of a Pascal Program Variables and constants.
James Tam Getting Started With Pascal Programming How are computer programs created What is the basic structure of a Pascal Program Variables and constants.
James Tam Getting Started With Pascal Programming What is the basic structure of a Pascal Program Variables in Pascal Performing input and output with.
J. Michael Moore Structured Programming CSCE 110 Drawn from James Tam's material.
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
James Tam Breaking Problems Down This section of notes shows you how to break down a large programming problem into smaller modules that are easier to.
J. Michael Moore Input and Output (IO) CSCE 110 Drawn from James Tam's material.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate your code.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
Getting Started With Pascal Programming
J. Michael Moore From James Tam's material Records CSCE 110.
J. Michael Moore Other Control Structures CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.
James Tam Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
James Tam Making Decisions In Pascal In this section of notes you will learn how to have your Pascal programs choose between alternative courses of action.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
James Tam Breaking Problems Down This section of notes shows you how to break down a large programming problem into smaller modules that are easier to.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Getting Started With Pascal Programming How are computer programs created What is the basic structure of a Pascal Program Variables and constants.
J. Michael Moore Modules – the Basics CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.
James Tam Linked Lists In this section of notes you will learn how to create and manage a dynamic list.
Link Lists In this section of notes you will learn how to create and manage a dynamic list. Link Lists in Pascal.
James Tam Introduction To Files In Pascal You will learn how to read from and write to text files in Pascal.
James Tam Records You will learn in this section of notes what is a record and how to use them in Pascal.
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
Input and Output (IO) CSCE 110 Drawn from James Tam's material.
James Tam Pointers In this section of notes you will learn about a third type of variable that stores addresses rather than data.
James Tam Getting Started With Pascal Programming How are computer programs created What is the basic structure of a Pascal Program Variables and constants.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to files in Pascal.
James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.
James Tam Pointers In this section of notes you will learn about another type of variable that stores addresses rather than data.
James Tam Introduction To Files In Pascal In this section of notes you will learn how to read from and write to text files in Pascal.
J. Michael Moore Modules – the Basics CSCE 110 Influenced by material developed by James Tam & Jennifer Welch.
James Tam Breaking Problems Down This section of notes shows you how to break down a large problem into smaller modules that are easier to implement and.
James Tam Breaking Problems Down This section of notes shows you how to break down a large programming problem into smaller modules that are easier to.
James Tam Multi-Dimensional Arrays In Pascal In this section of notes you will learn about how and when to use multi- dimensional arrays.
History of Computing – Pascal
Loops In Pascal In this section of notes you will learn how to rerun parts of your program without having to duplicate the code. Repetition in Pascal:
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Arrays In this section of notes you will be introduced to a composite type where all elements must be of the same type (homogeneous): arrays Homogeneous.
Breaking Problems Down
Presentation transcript:

Pascal Prof. Steven A. Demurjian Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Box U-255 Storrs, CT 06269-3255 Steven.Demurjian@uconn.edu http://www.engr.uconn.edu/~steve (860) 486–4818 (Office) (860) 486-3719 (CSE Office)

Getting Started With Pascal Programming http://pages.cpsc.ucalgary.ca/~tamj/2002/231P/notes/starting_programming/starting_pascal_programming.ppt http://pages.cpsc.ucalgary.ca/~tamj/2002/231P/notes/pascal/ Getting Started With Pascal Programming

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.

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);

The Smallest Pascal Program (* * Smallest.p: * The smallest Pascal program that will still compile written by James Tam * v1.0. *) program smallest; begin end.

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

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;

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;

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

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'…);

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

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

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

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 := 123456; 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., 123456 Eg2., 123 Eg3.,---123 Eg4.,---123 Getting Started With Pascal Programming

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 := 123.4567 writeln (num1:6:2); Set number of decimal places greater than the actual number of decimal places – number will be padded with zeros. num1 := 123.4567; writeln(num1:6:6); e.g1., 123.46 e.g2., 123.456700 Getting Started With Pascal Programming

Formatting Output: A Larger Example program out1; var num1 : integer; num2 : real; begin num1 := 123; num2 := 123.456; 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 Pascal123 1.234560000000000e+02 Manual format123123.456 Manual not en123123.456 Manual too much 123123.4560 Getting Started With Pascal Programming

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…);

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

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

Input: Read Vs. Readln (An example) write( some integers making sure to separate each one with a space '); write('or a new line: '); read (num1, num2); write('Input some integers making sure to separate each one with a space '); write('or a newline: '); read(num3, num4); 1 2 3 4 Getting Started With Pascal Programming

Input: Read Vs. Readln (An example (2)) write('Input some integers making sure to separate each one with a space '); write('or a newline: '); readln (num1, num2); readln(num3, num4); 1 2 3 4 5 6 Getting Started With Pascal Programming

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

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

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

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, '%');

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!)

If-Then-Else (Simple Body(2)) if (x = 1) then writeln('body of if') else writeln('body of else'); writeln('after if-then-else');

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!)

If-Then (Compound Body(2)) 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');

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

Case Statements: Integer Example 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 *)

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

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 *)

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 i: = 1; while (i <= 10) do begin writeln('i = ', i); i := i + 1; end; (* while *) Initialize control Test condition Execute body Update control

First For Loop Example 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

Second For Loop Example 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.

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);

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

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

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) for i := 1 to 2 do for j := 1 to 3 do writeln('i = ':9, i, 'j = ':9, j); writeln('All done!');

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

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

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

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

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 *)

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 *)

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);

Writing To A File: Putting It All Together 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

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.

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

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

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"

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"

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"

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);

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)

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

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

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

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]);

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;

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] := '|';

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 *)

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);

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')

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.

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;

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

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

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

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.

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 *)

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;

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!

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 [1..30000] of StudentRecord; var universityOfCalgaryStudentRecords : StudentRecordList;

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 [1..30000] of StudentRecord; var universityOfCalgaryStudentRecords : StudentRecordList; Declaring Record Declaring a new type Declaring a new instance of type "StudentRecordList"

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 *)

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)

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;

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;

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);

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 *)

Putting This All Together 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;

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 *)

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 *)

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;

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);

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);

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.

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 *)

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 *)

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

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 *)

Procedures: Putting Together The Case With Parameters 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 *)

Procedures: Putting Together The Case With Parameters 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

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 *)

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

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; ☼

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

Functions: Putting It All Together K 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

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

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 *)

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

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;

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);

Passing Variable Parameters: Putting It All Together 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 *)

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);

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;

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 *)

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)

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 “at-sign” @ instead of the “up-arrow” ^ to declare a pointer variable

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);

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;

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

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

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

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

Pointers : First Example 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;

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^;

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^);

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

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);

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);

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;

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

Pointers: Second Example 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;

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;

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

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 *)

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

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.

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;

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

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 *)

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

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 *)

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('Email: ':20, currentNode^.data.email); writeln; currentNode := currentNode^.nextPointer; end; (* while *) end; (* displayList *)

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

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

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 *)

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.

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

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;

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('Email :':20, currentNode^.data.email); writeln; if (isFound = False) then isFound := True; end; (* if-then *)

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

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.

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

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 *)