1 / 148

Pascal

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

gwalters
Download Presentation

Pascal

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

  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

  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., • var • height, weight: real; • age: integer;

  8. Not allowed! 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) 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); • or • writeln (name of variable or constant); • write('message', name of variable, 'message'…); • or • 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);

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

  13. Formatting Output (2) • Examples • var • num : real; • begin • num := 12.34; • writeln(num); • writeln(num:5:2);

  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 := 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). • Examples: num := 123; writeln(num:6); Writeln('123':6);

  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 := 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. • Example: num1 := 123.4567; writeln(num1:6:6);

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

  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…); • or • readln (nv2, nv3…);

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

  19. Input: Read Vs. Readln • Both: • 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);

  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); • write('Input some integers making sure to separate each one with a space '); • write('or a newline: '); • readln(num3, num4);

  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 • Files • 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, '%'); • for i := 1 to CLASSSIZE do • writeln('Grade for student no. ', i, ' is ', classGrades[i]:6:2, '%');

  26. No semi-colon (indicates end of decision-making!) 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;

  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. No semi-colon (marks end of decision-making!) If-Then-Else (Compound Body) • Body of if-then-else consists of multiple statements • Format: • if (Boolean Expression) then • begin • s1; • : • sn; • end • else • begin • sn+1; • : • sn + m; • end; • Sn + m + 1;

  29. If-Then (Compound Body(2)) • if (x = 1) then • begin • writeln('Body of if 1'); • writeln('Body of if 2'); • end • else • begin • 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: • body; • : • in: • body; • otherwise: • body; • 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: • begin • writeln(‘You got a ‘B’); • end; (* GPA of 3 *) • 2: • begin • writeln(‘You got a C’); • end; (* GPA of 2 *) • 1: • begin • writeln(‘You got a D’); • end; (* GPA of 1 *) • 0: • begin • writeln(‘You got an F’); • end; (* GPA of 0 *) • end; (* case *)

  32. Case Statements: Characters • Format (char): • Case (expression) of • ‘c1’: • body; • ‘c2’: • body; • : • ‘cn’: • body; • otherwise • body; • 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’: • begin • writeln(‘GPA = 3’); • end; (* GPA of 3 *) • ‘C’: • begin • writeln(‘GPA = 2’); • end; (* GPA of 2 *) • ‘D’: • begin • writeln(‘GPA = 1’); • end; (* GPA of 1 *) • ‘F’: • begin • writeln(‘GPA = 0’); • end; (* GPA of 0 *) • end; (* case *)

  34. Initialize control Test condition Execute body Update control 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 *)

  35. Initialize control Update control Test condition Execute body First For Loop Example • var • i, total : integer; • begin • total := 0; • for i := 1 to 10 do • begin • total := total + i; • writeln('i = ':4, i:2, 'total = ':13, total:2); • end; (* for *) • end.

  36. Second For Loop Example • var • i, total : integer; • begin • total := 0; • for i := 5 downto 1 do • begin • 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. Test condition Execute body Initialize control Update control Repeat-Until: An Example (2) • repeat • 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');

  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: • 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 • begin • 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 • begin • 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 • begin

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

More Related