Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pascal Prof. Steven A. Demurjian

Similar presentations


Presentation on theme: "Pascal Prof. Steven A. Demurjian"— Presentation transcript:

1 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 Getting Started With Pascal Programming
Getting Started With Pascal Programming

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

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

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

6 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

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

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

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

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

11 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

12 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

13 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

14 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

15 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

16 Formatting Output: A Larger Example
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

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

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

19 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

20 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); Getting Started With Pascal Programming

21 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); 5 6 Getting Started With Pascal Programming

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

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

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

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

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

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

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

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

30 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

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

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

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

34 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

35 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

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

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

38 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

39 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

40 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!');

41 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

42 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

43 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

44 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

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

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

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

48 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

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

50 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

51 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

52 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"

53 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"

54 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"

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

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

57 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

58 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

59 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

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

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

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

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

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

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

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

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

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

69 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

70 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

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

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

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

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

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

76 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"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

92 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

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

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

95 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

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

97 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

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

99 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

100 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

101 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

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

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

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

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

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

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

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

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

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

111 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

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

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

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

115 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

116 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

139 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

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

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

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

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

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

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

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

147 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

148 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 "Pascal Prof. Steven A. Demurjian"

Similar presentations


Ads by Google