Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 11, Lecture 2 (Wed)

Similar presentations


Presentation on theme: "CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 11, Lecture 2 (Wed)"— Presentation transcript:

1 CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 11, Lecture 2 (Wed)

2 THIS WEEK Today –Programming with text files –Quiz results & going over.. Thursday: LAB 01 – More work on homework #5

3 NEXT WEEK Quiz #4 –Wednesday May 30th No make-up session I don’t feel a need for more class time but… I can possibly start classes 15 minutes early and end 15 minutes late (since you have ½ hour breaks). –Let me know if you want me to do that!

4 Topics Definitions Advantages of data files Text file operations –Declare –Initialize –Use –Close & characters eof & eoln functions Reading/Writing characters Reading/Writing numeric data

5 Definitions Interactive program: –Reads all input data from the keyboard and displays output on the screen (terminal I/O) Batch processing: –Input and output are from data files Pure batch processing: –Input and output are strictly from data files, no interaction with user Examples are the pipe and filter processing in Unix, Linux and MSDOS Mixed interactive and batch processing: –Have both terminal I/O and file I/O

6 Definitions [cont.] Data file (input file): –A general definition –A file containing input data for a program –In Pascal, it could be a binary file (not readable by a human) or a text file. Output file: –A file containing program results Text file: –A disk file containing a collection of characters –Text files can be viewed or created using a text editor –Can be used for input or output

7 Advantages of Using Data Files Entering data interactively –Is ok, if you only have a few data items –If you have lots of data, you want to do it ONCE and then store the data –It is easy to make errors If you do, it ’ s hard to fix them You need to start all over again … lots of extra work Entering data with a data file –We can run the program as many times a you wish without reentering the data. If program output is written to a file, a permanent copy will be available. The output file generated by one program can be used as input data to another file.

8 Advantages of Using Text Files Created with a text editor or similar tool that can write text files Easy to check & edit. You can establish your own format, e.g. –Have several fields per line –Fields are separated by tab characters, blanks, comma, or other special character

9 A File, Conceptually Is dataitem separator dataitem … dataitem separator dataitem … dataitem separator dataitem … dataitem separator dataitem

10 Text Files In General A collection of characters stored under some name in secondary memory. Consist of multiple lines of character type Each character occupies one byte, including the & Have no fixed size marks an end-of-file The last character is followed by the character in the file Both the keyboard & screen are considered as text files Some systems represent the on the keyboard by ctrl/Z

11 Special File Characters –Indicates the end-of-line –Inserted each time the keyboard's Enter key is pressed –Similar to end-of-line in terminal input stream –Indicates the end-of-file –Inserted automatically after the last character of a text file when the file is saved –Ctrl-D (Unix and related) or Ctrl-Z (MS DOS) are equivalents for terminal streams

12 Reading Text Files readln: –Read data and skip the rest of input line and go to the start of the next data line. –Any additional characters remaining on the current data line are not processed. –Example: If the file contains on each line: number1 number2 number3 … numberN and you read with the statement: readln(Value1, Value2); number3 … numberN will be thrown away read: –Read data from the same data line during successive calls. –When you get to the end of the line, use readln without arguments to go to the next line

13 Writing Text Files Use writeln, and write These work like when you are writing to standard output You can use formatting directives

14 Reading a Line of Characters Input data will be stored in the variables specified in the input list. The order of the data must correspond to the order of the variables in the input list. One or more blank character must be inserted between numeric data. No blanks required between character data items. readln without an input list will skip over any characters on the current data line. All of this is the same as reading from the keyboard (input)

15 Testing for End-of-Line eoln function –Pascal defined function (standard function) –Returns true when the next data character is the symbol; otherwise false –Usually used as a sentinel –Form: eoln(filename) Input is a filename Output is a boolean –If filename is omitted, keyboard is assumed (input)

16 Processing A Text File Line Example: Counting nonblank characters in a line {Process each input character up to eoln} Count := 0; WHILE NOT eoln(infile) DO BEGIN read ( infile, Next ); {Get next character.} IF Next <> Blank THEN Count := Count + 1; END; readln(infile);{Skip the.} The last readln statement skips the, not the character at the start of the next data line. An attempt to read beyond the character results in run-time error. Safer to use WHILE than REPEAT

17 Testing for End-of-File eof function –Pascal defined function (standard function) –Returns true if the next character is the character –Form: eof(filename) Input is a filename Output is a boolean –If filename is omitted, screen is assumed (input)

18 Using Text Files To use Text files in your program, you must: 1. Create a text file variable 2. Associate the variable with a physical disk file 3. Open the file for reading or writing 4. Read and write to the file 5. Close the file

19 Declaring Text Files Pascal's predefined data type text is used to declare text files. Syntax: VAR file-name : text; Example: VARInData,OutData : text;

20 Text File Variables, Logical Files, and Physical Files It is possible to read data from more than one input file or to write result to more than one output file in a single program. A file variable represents a logical file A logical file is explicitly associated with a physical file by stating the drive, the path, and the physical file name (next slide) The same file variable (logical file) can be associated with different physical files in the same program but not at the same time. –If you have to keep accessing several different input and/or output files at the same time, use different file variables

21 Opening/Preparing Input Files: assign, reset First, associate a file variable (logical file) with a physical file: assign(input file logical name, physical file name); Then, prepare the file for reading: reset ( input file logical name ); Example: VAR InFile: text; assign(InFile, 'InData.Dat' ); reset (InFile);

22 Opening/Preparing Input Files [cont.] reset: –Moves the file position pointer to the beginning of the file –The file position pointer points to the file buffer and selects the next character to be processed in the file –Must be done before any characters are read from the input file –An error is generated if the input file was not previously saved on disk dataitem dataitem … dataitem dataitem dataitem … dataitem dataitem dataitem … dataitem … file position pointer

23 Opening/Preparing Output Files: assign, rewrite First, associate a file variable (logical file) with a physical file: assign(output file logical name, physical file name); Then, prepare the file for writing: rewrite (output file logical name ); Example: VAR OutFile: text; assign(OutFile, ‘OutData.dat' ); rewrite (OutFile);

24 Opening/Preparing Output Files [cont.] rewrite: –Prepares the file for output –If the file doesn ’ t exist, an empty file is created –If the file exists, file position pointer is put to the beginning of the file. –All old data are lost! file position pointer

25 Closing Input & Output Files When you are done processing the file, close it: close (input/output logical file name) Example: VAR MyFile: text; assign(MyFile, ‘MyData.txt' ); … {process data/file} close(MyFile); Closing essentially makes sure the entire file is saved correctly.

26 Self-Check 1 What is wrong with this program? assign(‘MyData.txt’, InFile); rewrite(Infile);/* ?? */ reset(Infile); WHILE NOT eoln DO/* ?? */ BEGIN read(InFile, Next); write(Next) END; {while}

27 Example: Copying a file PROGRAM CopyFile; {Copies InData file to OutData file} VARInData, {input file} OutData : text; {output file} PROCEDURE CopyLine (VAR InData, OutData : text); {Copies a line of file InData to file OutData. BEGIN... END { see next slide } BEGIN {CopyFile} assign (InData, ‘C:\TP\TEST\InFile.dat’); assign (OutData, ‘C:\TP\TEST\OutFile.dat’); reset (InData); rewrite (OutData); WHILE NOT eof(InData) DO CopyLine (InData, OutData); writeln (OutPut, 'Input file copied to output file.'); close (InData); close (OutData) end. {CopyFile}

28 Example: Copying a file [cont.] PROCEDURE CopyLine (VAR InData, OutData : text); {Copies a line of file InData to file OutData.} VAR Ch : char; BEGIN WHILE NOT eoln(InData) DO BEGIN read(InData,Ch); write(OutData,Ch); END; readln(InData); writeln(OutData); END; {CopyLine}

29 Example: Copying a file [alternative] BEGIN {CopyFile} assign (InData, ‘C:\TP\TEST\InFile.dat’); assign (OutData, ‘C:\TP\TEST\OutFile.dat’); reset (InData); rewrite (OutData); WHILE NOT eof(InData) DO BEGIN WHILE NOT eoln(InData) DO BEGIN read(InData,Ch); write(OutData,Ch); END; readln(InData); writeln(OutData); END; writeln (OutPut, 'Input file copied to output file.'); close (InData); close (OutData) END. {CopyFile} Need to add Ch: char; to VAR declarations

30 Reading/Writing Numeric Data When reading numeric data, the computer skips over any leading blanks or character. until it encounters a sign or digit If several variables are listed in the parameter list for Read or ReadLn, the computer reads data into each variable in the order in which the variables appear The file position pointer advances after each value is entered Writing a numeric value to a file is similar to writing to the screen

31 Reading/Writing Numeric Data Example: If the following variables are declared: X : real; N : Integer; C: Char; For the sequence: 1234.56 789 A345.67 W Variables values StatementXNC 1.Read (InData, X, N, C)1234.56789‘ ‘ 2.Read (InData, X, N, C, C)1234.56789‘A’ 3.ReadLn (InData, X, N, C)1234.56789‘ ‘ 4.Read (InData, X, C, N)1234.56789‘ ‘ 5.ReadLn (InData, X, C, N)1234.56789‘ ‘ 6.Read (InData, C, X, N)234.56789‘1‘ 7.ReadLn (InData, C, X, N)234.56789‘1‘ 8.ReadLn(InData,X,N); Read(InData,C) 1234.56 789‘W‘ 9.ReadLn (InData,X) ReadLn(InData,C) 1234.56 ---‘W‘

32 Reading/Writing with Text Files Syntax: read (infile, input-list) readln (infile, input-list) write (outfile, output-list) writeLn (outfile, output-list) If infile or outfile are omitted, the standard default input (keyboard) or output (Screen) will be assumed

33 Recursion

34 Looping/Iteration vs. Recursion Looping/iteration is repetition of the same piece of code with slightly different values of –the index variable (for FOR loops) –the control variable/expression (for WHILE and REPEAT loops) With each repetition, the index variable approaches the maximum (FOR.-. TO…) or minimum limit (FOR … DOWNTO …) During some repetition, the control variable will cause the loop entrance condition to become false (WHILE loop) or true (REPEAT loop).

35 Iteration vs. Recursion Recursion is an alternative to iteration The idea is to –Do a little bit of work towards a problem so that you can then –Perform a similar operation on a “smaller” version of the same problem Requires the use of procedures or functions A recursive function / procedure calls itself

36 Conceptual Example You have a list of ordered (sorted) numbers: 1 3 7 15 22 23 28 30 31 45 60 71 72 83 90 You want to know whether it contains a specific number: 45 You can search through the list starting at the beginning or at the end You can “bisect” the list recursively

37 1. Look at the middle number: 1 3 7 15 22 23 28 30 31 45 60 71 72 83 90 45 > 30, so look above 30: 2. Look at the middle number: 31 45 60 71 72 83 90 45 < 71 so look below 71: 3. Look at the middle number: 31 45 60 Success! (If you had wanted 47, you would have continued looking at 60 and decided that it wasn’t there). NOTE: Each time we are looking at a smaller set of numbers!!!

38 Example: Exponentiation Exponentiation = powers of a number There is no standard Pascal function for it So we make one: Power –A program with iteration –A function with iteration –A function with recursion

39 A Program that Computes Powers PROGRAM Power; VAR Num, NumExp: real; I, Pow :integer; BEGIN write('Enter Number (real) and Power (integer): '); readln(Num,Pow); NumExp := 1; FOR I := 1 TO Pow DO NumExp := NumExp * Num; writeln(Num:5:2, ' raised to the power ', Pow, ' is ', NumExp:10:2); readln END.

40 An Iterative Function that Computes Powers FUNCTION Exponentiate (Num : real; Pow : integer) : real; VAR NumExp: real; I : integer; BEGIN NumExp := 1; FOR I := 1 TO Pow DO NumExp := NumExp * Num; Exponentiate := NumExp END; {Exponentiate}

41 How the Function is Used PROGRAM Power; VAR TheNumber, NumToPower: real; ThePower :integer; FUNCTION Exponentiate (Num : real; Pow : integer) : real; … END; {Exponentiate} BEGIN write('Enter Number (real) and Power (integer): '); readln(TheNumber, ThePower); NumToPower := Exponentiate(TheNumber, ThePower); writeln(TheNumber:5:2, ' raised to the power ', ThePower, ' is ', NumToPower:10:2); readln END.

42 A Recursive Function that Computes Powers FUNCTION Exponentiate (Num : real; Pow : integer) : real; BEGIN IF Pow = 0 THEN Exponentiate := 1 ELSE Exponentiate := Num * Exponentiate(Num, Pow -1) END; {Exponentiate}

43 A Recursive Function that Computes Powers FUNCTION Exponentiate (Num : real; Pow : integer) : real; BEGIN IF Pow = 0 THEN Exponentiate := 1 ELSE Exponentiate := Num * Exponentiate(Num, Pow -1) END; {Exponentiate}

44 How Does it Work? FUNCTION Exponentiate (Num : real; Pow : integer) : real; VAR Result : real; BEGIN IF Pow = 0 THEN Result := 1 ELSE Result := Num * Exponentiate(Num, Pow -1) writeln('Num is ', Num:5:2, ' Pow is ', Pow:5, ' Result is ', Result:10:2); Exponentiate := Result; END; {Exponentiate}

45 Enter Number (real) and Power (integer): 3.00 4 Num is 3.00, Pow is 0, Result is 1.00 Num is 3.00, Pow is 1, Result is 3.00 Num is 3.00, Pow is 2, Result is 9.00 Num is 3.00, Pow is 3, Result is 27.00 Num is 3.00, Pow is 4, Result is 81.00

46 Why Recursion? Some problems lend themselves recursion Mathematically very elegant Computationally: –More expensive –But can be efficient in special cases

47 THE END!


Download ppt "CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 11, Lecture 2 (Wed)"

Similar presentations


Ads by Google