Digital PDFs
Documents
Guest
Register
Log In
AA-L314A-TM
May 1983
134 pages
Original
4.8MB
view
download
Document:
TOPS-20 PASCAL Primer Sep83
Order Number:
AA-L314A-TM
Revision:
0
Pages:
134
Original Filename:
AA-L314A-TM_TOPS-20_PASCAL_Primer_Sep83.pdf
OCR Text
TOPS-20 PASCAL Prinler AA-L314A-TM September 1983 This document introduces the TOPS-20 PASCAL language. It is intended to be used by programmers who are new to TOPS-20 PASCAL. OPERATING SYSTEM: SOFTWARE: TOPS-20 V5.1 (2040,2060) TOPS-20 V4.1 (2020) PASCAL V1.0 LINK V5 . 1 RMS V1 ..2 Software and manuals should be ordered by title and order number. In the United States. send orders to the nearest distribution center. Outside the United States. orders should be directed to the nearest DIGIT AL Field Sales Office or representative. Nt)rtheast/Mid-Atlantic Region Central Flegion Digital Equipment Co(poration PO Box CS2008 Nashua. New Hampshire 03061 TE'lephone:(603)884-6660 Western Region Digital Equipment Corporation Digital Equipment Corporation Accessories and Supplies Center Accessories and Supplies Center 1050 Easi Remington Road 632 Caribbean Drive Schaumburg, Illinois 60195 Sunnyvale. California 94086 T elephontl :(312)640-5612 Telephone:( 408) 734-4915 digital equipment corporation. marlboro. massachusetts First Printing, September 1983 c. Digital Equipment Corporation 1983. All Rights Reserved. The information in this document is subject to change without notice and should not be construed as a commitment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors that may appear in this document. The software described in this document is furnished under a license and may only be used or copied in accordance with the terms of such license. No responsibility is assumed for the use or reliability of software on equipment that is not supplied by DIGITAL or its affiliated companies. The following are trademarks of Digital Equipment Corporation: ~D~DD~D1M DEC DECmate DE Csystem-1 0 DECSYSTEM-20 DECUS DECwriter DIBOL MASS BUS PDP prOS Professional Rainbow RSTS RSX UNIBUS VAX VMS VT Work Processor The postage-prepaid READER'S COMMENTS form on the last page of this document requests the user's critical evaluation to assist us in preparing future documentation. CONTENTS PREFACE CHAPTER 1 1 .1 1 .1. 1 1. 1•2 1.1.3 1. 2 1 • 2. 1 1.2.2 1 .2.3 1.2.4 1. 3 CHAPTER 2 2.1 2.2 2.2.1 2.2.2 2.2.3 2.2.4 2.2.5 2.3 2.4 2.5 2.5.1 2.5.2 2.5.3 2.5.4 CHAPTER 3 3.1 3.1.1 3. 1 . 2 3.2 3.3 3.4 3.5 3.5.1 3.5.2 CHAPTER 4 4.1 4.2 4.2.1 4.2.2 4.3 4.3.1 4.3.2 4.4 4.4.1 4.4.2 INTRODUCTJON THE STRUCTURE OF A PASCAL PROGRAM The Program Heading The Declaration Section The Executable Section . PROGRAM DEVELOPMENT Creating a Program . . . Compiling a Program Loading an Object File. Executing a Program A PASCAL PROGRAM EXAMPLE . · . · . · . 1-2 1-4 . 1-4 • l-5 · 1-7 · 1-9 1-10 1-11 1-11 1-12 DA.TA CONCEPTS DATA AND DATA TYPES SCALAR DATA TYPES The Type TNTEGER • The Type REAL The Type BOOLEAN . · The Type CHAR User-Defined Scalar Types . . • . STRUCTURED DATA TYPES • • • . VARIABLES . • . . . . . • • • . EXPRESSIONS • . • . • • . Arithmetic Expressions • . •••• Relational Expressions • ..•. Logical Expressions ..•.. Precedence Rules for Operators • . • . . · . · . · . · . . . . • 2-1 2-2 · 2-3 . 2-3 . 2-5 . 2-5 · 2-() 2-6 • • 2-6 2-7 · . 2-8 2-10 2-11 2-12 DECLARATIONS AND DEFINITIONS SYMBOLIC NAMES • Reserved Words, Semi reserved Words, and Predeclared Identifiers •.•. User Identifiers. CONSTANT DEFINITIONS . TYPE DEFINITIONS • • • · VARIABLE DECLARATIONS · USER-DEFINED SCALAR TYPES • • . • • Enumerated Types . • . • • Subrange Types • . • . . · · . • • • . . • · . • · 3-1 . • • . · • . 3-2 3-3 3-4 3- 5 3-6 3-7 3-8 3-9 READING AND WRITING DATA THE PREDECLARED TEXT FILES INPUT AND OUTPUT READING DATA • • • • . • The READ Procedure . •••• . • The READLN Procedure • WRITING DATA . . . . • . • • • The WRITE Procedure • • • . The WRITELN Procedure • • • • . THE PREDECLARED FUNCTIONS EOLN AND EOF • The EOLN Function The EOF Function • • • • • • iii . 4-1 . • • 4-3 • . . 4-3 . . 4-5 . • 4-6 • 4-7 4-11 4-12 4-12 4-13 CONT ENTS CHAPTER 5 5.1 5.1 .1 5.1 • 2 5.2 CHAPTER h ~ • 1 (-).2 f) • 3 5. '3 • 1 6.3.2 6 •3•3 h .4 6 .4 • 1 6.4.2 fi.4.3 CHAPTER 7 7 .1 7 •1 •1 7 •1 •2 7 .1 • 3 7.2 7.2.1 7.2.2 7 •3 7 .3 • 1 7 .3.2 7.4 7 .4 • 1 7.4.2 7.4.3 APPENDIX A A.1 A.2 A.3 (CONT.) STRUCTURED TYPES: THE ARRAY AND THE RECORD ARRAYS . • Multidimensional Arrays Character Strings RECORDS .•.... . . . • • • • ')-2 • • • • • • 5-8 5-(.) 5-10 PASCAL STATEMENTS THE ASSIGNMENT STATEMENT • THE COMPOUND STATEMENT . REPETITIVE STATEMENTS The FOR Statement . . . . . . . The REPEAT Statement • The WHILE Statement CONDITIONAL STATEMENTS • . . . • • The IF-THEN Statement The IF-THEN-ELSE StQtement • The CASE Statement • • • • • • fi-2 • • • • • 1)-3 • • • • • • • • • • • • • • • • • • 6- 3 fi-4 fi - 5 fi - 8 1)-10 fi-l0 fi-ll fi-13 PROCEDURES AND FUNCTIONS SUBPROGRAMS Format of a Subprogram Local and Global Variables. Scope of Identifiers in Subprograms DECLARING A PROCEDURE . • • • • • Calling a Procedure ••••. Procedure Example DECLARING A FUNCTION • Calling a Function. Function Example . PARAMETERS • • • • • • Actual and Formal Parameters. Value and Variable Parameters Examples • . . • . . • • • • • . · . . . . • 7-1 · 7-2 . 7-2 · · · • • • • • • . . • • 7-3 . 7-3 • 7-3 . • • . . . . 7-4 · • • • • • 7-5 · 7-6 · 7-6 • • • • • • '. · • • • • • • • • • 7-7 • 7-8 7 - c::, 7-11 PASCAL DEFINED NAMES RESERVED WORDS SEMIRESERVED WORDS . PREDECLARED IDENTIFIERS '. • • • • A-I • • • • • A-I • A-I APPENDIX B ASCII CHARACTER SET APPENDIX C SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS GLOSSl\RY INDEX iv CONTENTS (CONT.) FIGURES FIGURE 1-1 4-1 4-2 5-1 5-2 Program Development Process The End of a Text File. File position pointer at End of File. The Two-Dimensional Array Class Scores • The Three--Dimensional Array Hotel Vacancies . 1-7 4-14 4-14 · . 5-6 • • 5-8 TABLES TABLE 2-1 2-2 2-3 2-4 2-5 4-1 B-1 C-1 C-2 • • Arithmetic Operators. • •••• Result Types for Arithmetic Expressions • Relational Operators • • • • • . • . . Logical Operators Precedence of Operators • • • • . Default Value for Field width •••• . . • • • The ASCII Character Set Predeclared Procedures • Predeclared Functions • • • • v • 2-8 . 2-9 2-10 2-11 2-12 • 4-8 • B-1 C-l • C- 5 --------------------------------------------------------------------------------,------------------------------- PREF/I.CE PRIMER OBJECTIVES This primer introduces the PASCAL language for the TOPS-20 operating system. It is designed to provide sufficient information about the language so that you can begin writing PASCAL programs. PASCAL-20 is an extended implementation of the standard proposed for the PASCAL language by the International Standardization organization (ISO). This manual describes a subset of PASCAL-20, omitting some advanced features of the language. Once you have mastered the concepts in this primer, you should consult the TOPS-20 PASCAL Language Manual for full reference information on--the-PASCAL-20 language. INTENDED AUDIENCE This manual does not attempt to teach programming concepts. It is assumed that you have experience programming in a high-level language or that you are taking an introductory programming course. However, prior knowledge of the PASCAL language is not necessary. You need not have a detailed understanding of the TOPS-~O operating system, but some familiarity with TOPS-20 is helpful. Also, you should know how to use a text editor to create a file. If you are new to TOPS-20, see the manual Getting Started with TOPS-20 for introductory material. HOW TO USE THIS DOCUMENT This manual contains seven chapters. Each chapter (except the first) introduces new concepts in PASCAL that build on material presented in previous chapters. It is recommended that you read the chapters sequentially to take advantage of this structure. Chapter 1 explains how to develop PASCAL programs on TOPS-20. You will find sample programs throughout this manual. You can enter, compile, link, and run these sample programs on TOPS-20 using the tools for program development introduced in Chapter 1. Chapter 2 describes the data types used in PASCAL, as well as the of variables and expressions. use Chapter 3 describes how to define data types and identifiers prog rams. your vii in Chapter 4 describes how to read and write Chapter 5 describes two structured data record. dat~. types: the array and the Chapter ~ describes PASCAL statements, including the assignment statement, the compound statement, and repetitive st~tements. In particular, it describes the FOR st~tement, the REPEAT statement, the WHILE statement, the IF statement, the IF-THEN statement, the IF-THEN-ELSE statement, and the CASE statement. Chapter 7 describes the use of procedures and functions. A glossary is presented at the end of this primer. defines many of the terms presented in the text. The glossary FOR MORE INFORMATION For reference information on the PASCAL-20 language, consult the TOPS-20 PASCAL Language Manual. It provides additional information on using ~ASCAL under the TOPS-20 operating system. viii CONVENTIONS USED IN THIS DOCUMENT This document uses the following conventions: Convention Meaning 11. horizontal ellipsis means that the preced ing :i tem can be repeated one or more times. A vertical ellipsis means that not all of the statements in a figure or example are shown. [ n Double brackets in format descriptions enclose items that are optional, for example: WRITE ( [OUTPUT, n print list) Do not type the double square brackets. WRITE r ] (OUTPUT, 'Enter an integer') Square brackets mean that the syntax requires the square bracket characters. This notation is used with arrays, for example: ARRAY r index] Braces enclose lists from which choose one item, for example: you must This symbol RETURN key. press the indicates where you <CTRL/x> The notation <CTRL/x> indicates that you must press the key labeled CTRL while simultaneously pressing another key, for example, <CTRL/Z>. Simple_procedure In programming examples, all names created by the programmer are printed in lowercase letters with initial uppercase letters. UPPERCASE LETTERS Uppercase letters in indicate fixed (literal) must enter as shown. lowercase letters Lowercase letters in a command string indicate variable information you supply. Contrasting Colors Or~nge a command string information that you - where examples contain both user input and computer output, the characters you type are in orange; the characters printed on the terminal are in black. ix CHAPTEH 1 INTRODUCTION for PASCAL is a computer language invented by Niklaus Wirth and named Blaise Pascal, a French mathematician and philosopher. It is one of several programming languages used to translate symbolic language programs into machine language. Because the PASCAL language contains features suitable for many different programming applications, it has gained popularity as a general purpose language. PASCAL is used widely in educational institutions because its design lends itself toward teaching structured programming techniques. PASCAL's English-like statements ease the process of creating a logical flow of control. Thus, you can create code that is descriptive of what the program actually does. PASCAL and its data-structuring facilities encourage modular programming. In modular programming, you divide a problem into individual parts. These parts can be handled easily as subprograms within the main program. Because you must declare all the data you are going to use at the beginning of the program, you must do some initial planning and organization. All the data structures in your program become readily apparent, making programs easy to read and modify. Some of the commonly used language features of PASCAL include: • FOR, REPEAT, WHILE statements • CASE, IF-THEN, • INTEGER, REAL, CHAR, BOOLEAN, enumerated, and subrange scalar data types • ARRAY, RECORD, SET, and FILE structured data types • READ, READLN, WRITE, WRITELN input and output procedures • Functions sine, cosine, square root, round, predecessor, successor IF-THEN-ELSE statements and PASCAL-20 is an outgrowth of the standard proposed for the PASCAL programming language by the International Standardization organization (ISO). It contains all the elements of the proposed standard for PASCAL plus extensions to the language that allo~ you more flexibility. These extensions, which are described here in this primer and in the TOPS-20 PASCAL ~,uage Manual, include: • Exponentiation operator • Double-precision real data type 1-1 TNTRODUC.TION the dollar • Variable names of up to 31 characters sign ($) anrl the unnerscore ( ) • OTHERWISE clause in the CASE statement • Character string and enumerated type parameters for the and READLN procerlures • Enumerated procedures type p~rameters for the including WRITE Throughout this document, PASCAL-20 is referred to otherwise specified. as READ and WRITELN PASCAL unless This chapter introduces the PASC.AL language. Section 1.1 describes the structure of a PASCAL program. Section 1.2 explains how to develop a PASCAL program on the TOPS-20 operating system. Section 1.3 presents a PASCAL program example. For more information on all aspects of the PASCAL language implemented for TOPS-20, see the TOPS-20 PASCAL Languag~ Manual. 1.1 as THE STRUCTURE OF A PASCAL PROGRAM The structure of a PASCAL program consists of the following parts: 1. A program heading 2. A declaration section 3. An executable section 4. A period (.) The program heading contains the name of the program and any external files the program may use for input and output. The declaration section is the place for all the definitions and data declarations that will be used in the program. The executable section contains all the statements that PASCAL will compile for execution. The period (.) marks the end of the program. The declaration section and the executable section together are considered a block. A block can be the main borly of a program, a function, or a procedure. Functions and procedures are described in Chapter 7. PASCAL allows free formatting of program text. With free formatting, you can place statements anywhere on a line, divid~ one statement across more than one line, or place multiple statements on one line. However, you cannot split a name or number between Jines or with a space. To make a program easier to read, you can indent parts of the program according to the program flow. You can also place comments anywhere in a PASCAL program. You enclose comments either within braces { } or within a left-parenthesis/asterisk asterisk/right-parenthesis 20mbination (* *) • PASCAL ignores the text between the comment indicators. The following are examples of comments: {This is a comment.} (* So is this. *) 1-2 INTRODUCTION PASCAL provides the following delimiters for you to use when a program: • The reserved word BEGIN • The reserved word END • A semicolon (i) • A pe r i od creating (.) The reserved words BEGIN and END are used to separate functional parts of a PASCAL program. A reserved word is a word already defined in the PASCAL languagei you cannot redefine it to denote anything other than its special meaning. BEGIN and END specify the beginning and end of an executable section. They also delimit a compound statement (See Section fi.2). Generally, each BEGIN must be associated with an END. Therefore, it is good practice to count the number of BEGINs in your program and make sure you have at least the same number of ENDs. The END delimiter is also associated with the RECORD declaration (Section 5.2) and the CASE statement (Section G.4.3) No BEGINs are necessary in these two instances where ENDs occur. The semicolon (i) and the period (.) are also delimiters in the PASCAL language. The semicolon separates successive PASCAL statements. It also terminates the program heading and items in the declaration section. You need not place a semicolon directly after the word BEGIN or before the word END, because BEGIN and END are not statementsi they are delimiters. The period marks the end of the PASCAL program. The following sections explain the various parts of a PASCAL program while building a program called Grocery_Bill. The program Grocery Bill is an interactive program prompting you for the data it needs, performing calculations, and printing the results. Specifically, it performs the following steps: • Print instructions for entering prices of grocery items • Read each price and sum the prices to obtain a subtotal • Prompt for a yes or no answer to the question any coupons?' • Read and sum the total value of the coupons that are entered • Subtract the value of the coupons from the subtotal to obtain a total • Print a total The entire program Grocery_Bill 'Do is li.sted in Section 1.3. 1-3 you have INTRODUCTION 1.1.1 The Program Heading PASCAL programs always begin with a heading. • The reserved word PROGRAM • The program's name • The program's input and output files parentheses • The semicolon delimiter The following F:' F< Cl c.; F< At1 is the heading for G roc E' r ':! .... B i .1 1. (I NF' Ur~· The heading consists of: (if any), enclosed in the program Grocery_Bill: [) l.J T PUT ) ; This heading tells you that the name of the program is Grocery Bill, and the files the program uses are INPUT and OUTPUT. INPU~ and OUTPUT are names known to PASCAL. ~hey specify predeclared (that is, declared by PASCAL) text files. When you run a program that requires user response, these n~mes indicate that the program uses your terminal for input and output. 1.1.2 The Declaration Section PASCAL requires that you declare all data items in the program. To declare a data item, you give it a name, otherwise known as an identifier, and indicate what it represents. All declarations in a program must appear in the declaration section. Any constants, variables, functions, or procedures used in the program must be declared in the declaration section before being used in the executable section. Declarations must appear in the following order ( if your prog ram uses them) : 1. LABEL declares labels for use by the GOTO statement 2. CONST defines symbolic constants 3. TYPE -- creates user-defined 4. VAR -- declares variables and their types 5. VALUE -- initializes variables 6. PROCEDURE and FUNCTION -- declare routines types CONST, TYPE, VAR, PROCEDURE, and FUNCTION are discussed in this manual. LABEL and VALUE are described in the TOPS-20 PASCAL Language Manual. --The program Grocery Bill TYPE- and definitions: definition: and of declarations contains two kinds these is the VAR. The first of TYPE This TYPE section defines a data type called Yes No and the constants, Yes and No, that constitute the values of-the type. ]-4 two INTRODUCTION The second declaration is the VAR declaration: VAR Item_Pricey Totalv Co UF'O n .... (I m01..1 n t.: F~ [ AI... y Subtotaly Coupons: REAI...:~O.O; Ans: ye';; .... No; This variable section declares five real vari~bles: Item Price, Total, Coupon Amount, Subtotal, and Coupons. In addition, sixth variable, Ans,-is declared to be of th~ user-defined type Yes No. The variable Ans can assume either of two values: Yes or No. a 1.1.3 The Executable Section The executable section contains the statements that, when executed, perform the actions of the program. The executable section follows the declaration section and is delimited by BEGIN and END (followed by a period). The following is the executable section of the program Grocery_Bill: (* Executable Section *) BEGIN C* Print instructions for enterin~ data. *) WRITELN('Enter cost of each ~rocer~ item. One item per line.'); WRITELNC'Enter the value 0.0 to terminate list of items.'); (* Read prices and add each to subtotal until 0.0 is read. *) f~EPEAT READLN(Item_Price); Subtotal := Subtotal + Item_Price UNTIL (Item_Price = 0.0); WRITElN('Subtotal e8uals -- $', Subtotal:7:2); WRITE('Do ~ou have an~ coupons? T~pe ~es or no and press <RET>. '); r:~EADLN (Ans) ; If (An~;; THEN BEGIN WRITElN(/T~pe value of each coupon. One per line.'); WRITELN(/T~pe <CTRl/Z) after enterins all coupons.'); (* Read and sum amount of each coupon until end of input. REPEAT READlN(Coupon_Amount); Coupons := Coupons + Coupons_Amount UNTIL.. [OF (INPUT) END; (* Subtract coupons from Subtotal to obtain Total, and print Total. Total := Subtotal - Coupons; WRITELN('Pa~ this amount $', Total:7:2) END. End of Pro~ram (* *) *) *) Between the words BEGIN and END are statements and procedures that read and write data, change the value of variables, and control execution. Specifically, they are: • The WRITE procedure, Section 4.3.1 • The WRITELN procedure, Section 4.3.2 • The READLN procedure, Section 4.2.2 1-5 INTRODUCTION • The EOF function, Section 4.4.2 • The REPEAT statement, Section 0.3.2 • The IF-THEN statement, Section 6.4.1 Several input and output procedures are used in the program Grocery_Bill. For example, the first two WRITELN procedures print instructions on your terminal for entering a list of prices. The text within the apostrophes is printed. The third WRITELN procedure prints text followed by the value of a variable. Again, the text within apostrophes is printeri. The integers th~t appe~r after the variable name Subtotal specify field width. The first integer specifies the total field width, that is, the number of columns occupied by the value being printed. The second integer specifies the number of places to the right of the decimal point in the printed value. The remaining output procedures in the program print either the text that is specifieri in apostrophes or text and the value of a variable, in the same manner as the output procedures explained above. The program Grocery Bill contains three input procedures. Each reads a value from the- terminal and assigns the value to the variable specified in parentheses, for instance: F~FAnI...N (Arl~:;) ; This READLN procedure reads a value and assigns it to the variable Ans. Because Ans is of type Yes_No, the value to be read must be either Yes or No. The READLN procedure accepts the answer Yes or No in either uppercase or lowercase characters. The executable section of Grocery Bill also illustrates the assignment statement. An assignment statement contains three parts - a variable, the assignment operator (:=), and an expression. Note the following fo rma t: variable -= expression; The assignment statement causes the variable to assume the expression, for example: Subtotal the value of Subtotal and := Subtotal + Item_Price; This assignment statement arids the current value Item price, then assigns the sum to Subtotal. of Grocery Bill contains two kinds of control statements: IF-THEN and REPEAT.- The IF-THEN statement is a conditional statement. If the expression CAns = Yes) is true, the statement following the reserved word THEN is executed. The statement following THEN is a compound statement: IF (Ans Ye~:; ) THEN BEGIN END; 1-6 INTRODUCTION A compound statement specifies that all the statements and END are executed sequentially as a group. within BEGIN Finally, there are two examples of the REPEAT statement. is: One example r~[F'EAT READLN(Item_F'rice); ~:) u b t (J tal : :~: G 1..11:.1 tot a ]. + I t em .... P r :i. C (,.~ UNTIL.. (IteITt ... Pr'ic<-:-~ :::: () (. (» !I The REPEAT statement specifies that the statements between REPEAT and UNTIL be executed in order and terminated when the value of the variable Item Price equals 0.0. You do not need a semicolon before UNTIL becaus; the UNTIL clause is not another statement; it is part of the REPEAT statement. The second example is: r~EPEAT UNTIL EOF (INPUT); This statement, like the previous REPEAT, performs the statements within the REPEAT and UNTIL repeatedly. However, in this example, execution terminates when the function EOF(INPUT) becomes true. EOF (end-of-file) is a predeclared PASCAL function that returns true at the end of an input file. The <CTRL/Z> that you type after entering the values of coupons indicates the end-of-file condition to PASCAL. (The PASCAL file INPUT is associated with your terminal.) 1.2 PROGRAM DEVELOPMENT This section explains the steps in developing a PASCAL Figure 1-1 illustrates the program development process. Commands p,o~---- Create a PASCAL program with a file type of PAS. C,eate a ,ou"e (aPASCAL G!D PASCAL>EXAMPL.PAS G!D PASCAL>/EXIT Compile the source program EXAMPL.PAS (ji EXAMPL.REL (jiLOAD EXAMPL The LOAD commancl assumes the file type Is REL. Link the object module (it'START The START command executes the curren1 program In memory. Run the executable ~ MR-S-3076·63 Figure 1-1: Pro9 ram DevE~lopmen t Process 1-7 program. INTRODUCTION Developing a PASCAL program involves these six steps: 1. Designing the program 2. Creating the source file with an editor 3. Compiling the source program to create an object module 4. Loading the object module to produce an executable image 5. Saving the executable image (optional) ~. Executing the program After you design the program and create a editor, do the following: 1. source file with a text file name Call the PASCAL compiler @PASCAL( RfT) 2. Specify the files to compile PASCAL>filename~) 3. Exit from the PASCAL compiler PASCAL>/EXITG£0 4. Load the relocatable binary file @LOAD f ilename(~ 5. Save the executable image of the file (optional) @SAVE filename~ 6. Execute the program @RUN f ilenameC~ Note the following example. The program specified as prints the letter M on the terminal. (~pascaL~D F'ASCAL>lett.E-.'r. pase Rfl) F'ASCAL..:>/e:d t CR~l) ~load If:~tter.relC~0 LINK: Loading EXIT @save 1 et te r. eNe eli;!) LETTER.EXE.l Saved @rl.Jn If.:'ttpr~ *** *** *** * * @ 1-8 the INTRODUCTION All the commands except t.he PASCAL comm~i1d include a file name, that is, a TOPS-20 file specification. The PASCAL command returns a prompt: PASCAl... > In addition, commands can include optional switches. Command switches modify a command by providing the system with additional information on how to execute the command. For complete information on switches, r e fe r to the TOPS_-20 .PASCAL Lang UAgE~ .Manua 1 . TOPS-20 PASCAL COMPILER On TOPS-20, you specify the file name of the program you want to compile. You can also call upon t.he recognition and prompt features to assist you when entering commands. With recognition, you type only enough of the command to identify the command, and then press the ~ key. For example, you can type EXE and press the ~ key for the EXECUTE commAnd. pressing the ~ key after typing enough to uniquely identify the command causes TOPS-20 to display the rest of the command. In addition, pressing tbe GD key causes TOPS-20 to display prompts that indicate t.he next step. FILE SPECIFICATIONS The file specification tells the operating system which file to process. A full file specification contains a lengthy string of information. However, because the system assigns appropriate default values to most of the elements in a file specification, you rarely need to specify more than the following two elements: filename.filetype PASCAL recognizes PAS as the default file type. If the file type is PAS, you can specify just the file nAme. However, if the file has another_type (for example, PROGRM.PRG), you must specify the type. The file name identifies the file by its name, and the file type describes what kind of data is in the file. On TOPS-20, the file name and file type of the source file can each contain up to 19 alphanumeric characters. However, the file name of the relocatable binary file must contain no more than 6 characters and its file type no more than 3 characters; otherwise, you cannot load the file with the LINK program. For more information about file specifications and commands, refer to the TOPS-20 User's Guide. For more information about switches that apply t~~SCAL, refer to the TOPS-20 PASCAL Language Manual. 1.2.1 Creating a Program When you write a program, you must create a file, called a source file, that contains the program source statements. You use a text editor to create a source file. For instance, to create a PASCAL program that has the file name EXAMPL and a file type of PAS, you can issue the TOPS-20 EDIT command as follows: @EDIT EXAMPL.PAS G~D XFile not found, Creatin~ New file Input: EXAMPL.PAS 00100 1-9 INTRODUCTION If the file is a new file, the editor displays an additional message indicating that a new file is being created. You must include a file type (for example PAS) with the EDIT command. The EDTT comm~nd invokes the TOPS-20 default editor EDIT. The line number (00100) prompt indicates that EDIT is ready to accept input. For information on how to use ED1T, see the rOPS--20 EDIT User's Guide. On TOPS-20 in addition to FDIT, you can use ~ny editor to which you have access, for example, the TV editor. For more information about the use of TV, refer to the TOPS-20 TV Editor Manual. 1.2.2 Compiling a Program After you have edited your file, the next step is to compile it. To compile a source file, issue the PASCAL command. When the PASCAL prompt is displayed, enter the file name, for example: (!W ?)~:;C{iL. Ciu-i) P{i~JCAl.. >C X{)MF'L. C~-ir-) F'{inCtiL.>/FXIT (R'-;-) (~ To return to the operating system, type the /EXIT switch to the PASCAL prompt. If the file type is PAS, you can omit the file type because the PASCAL command assumes PAS as the default. However, if you use a file type other than PAS, you must specify the file type. When you enter the PASCAL command from compiler does the following by default: the termina], the PASCAL • Produces an object module that has the same file name as the source file and a file type of REL, for example EXAMPL.REL. • Uses defaults when it creates the output files (switches the PASCAL command can override these defaul ts) . on If the compiler does not detect any syntax errors in the source file, the system displays the PASCAL prompt to indicate successful com p i 1 a t ion: P~)SCAL> If the program contains syntax errors, however, the PASCAL compiler displays error messages on your terminal. It is then necessary to edit your source program with a text editor to correct the errors. TOPS-20 LISTING FILE On TOPS-20, the /LISTING switch on the PASCAL command requests the compiler to create a program listing. PASCAL does not produce a listing file unless you request one with the /LISTING switch. A program listing includes the program's source statements, line numbers, any error messages or warnings that are reported, and other information related to the compilation. For instance, to create a program listing of EXAMPL on TOPS-20, issue the command: F'ASCAL>EXAMF'L. IL. I ST I NG G0 This command causes the compiler to create a file called EXAMPL.LST in addition to the object module EXAMPL.REL. The /LTSTING switch does not direct EXAMPL.LST to the line printer. 1-10 IN'I'RODUCTION To obtain a printed copy of the program listing, use the PRINT command as follows: (~r'l, J NT EXAMF'L.. L..ST (~ A program can be successfully compiled, but still generate warning-level diagnostic messages on your terminal. For example, a number of warning-level diagnostic messages point out the use of nonstandard PASCAL features (that is PASCAL-20 extensions). These messages do not affect the compilation of a program in any way; they are reported only to flag the use of PASCAL-20 extensions. You can suppress the display of diagnostic messages for nonstandard PASCAL features by appending the /NOFLAG-NON-STANDARD switch to the PASCAL command as follows: (~F'ASCAL PAS CAL:> [: X I~ MF' I... / N nF l.. f~ G ... N() N.... !; TAN It (.1 H D ~ Many of the sample programs in this primer use nonstandard syntax. 1.2.3 Loading an Object File An object module (for instance, EXAMPL.REL) is not executable. To generate a file that can be executed by the system, you must use the TOPS-20 program LINK. To call LINK, use the LOAD command as follows: @L.OAD [XAMF'L. C~ You can omit the file type because the LOAD command assumes the type REL by default. The LOAD command loads the object file. file To create an EXE file, use the SAVE command. @~)AVE EXAMF'L C~ This creates a file named EXAMPL.EXE. image, that is, a file containing format. 1.2.4 EXAMPL.EXE is an executable your program in an executable Executing a Program To execute the program EXAMPL, use the RUN command or the EXECUTE command. When you issue the RUN command, you provide the name of an executable image; the RUN command assumes a file type (or extension) of EXE by default. Thus, to run the program EXAMPL for which you have created the executable image, issue the RUN command as follows: @I:;:UN EXAMPL ~~D The first time you run a program, it may not execute properly. If it has a bug, or a programming error, you may be able to determine the cause of the error by examining the output from the program or the listing file. When you have determined the cause of the error, you can correct your source program and repeat the compiling, loading, and running steps to test the result. You can use PASDDT, the PASCAL debugger, to debug your program. For more information about PASDDT, refer to the TOPS-:~ PASC~..!!. Language Manual. 1-11 INTRODUCTION 1.3 A PASCAL PROGRAM EXAMPLE This section presents the complete PASCAL program Grocery Bill. that the characters (* *) mnrk comments in the program. PH () Gf~ AMGT' 0 C f..~ T' ~~ .... n :i. 1 I (I NPUT ~ 0 UTF' l.J T ); (* Pro ~.:.! Y" a f1I h c! a (J e r Declaration section (* Note *') *) TYPE (* Dp f :i. n (~! (Yes, No); Yes .... No w :i t h ';; c~ a t i:~ t ~:i F' P Ye ',; .... No v a llJ (.:.~ ~:; Yc! ~,; d rid No *) VAF< Item_Price, Totaly Co U P 0 n .... Am 0 1..11"1 t : f< c·~ a 1 ; An s ! YE~ !:; _. N() ; (* (* Sub tot a I , C() U F' 0 n 5: f< EAl.. ! :": 0 • 0 ; (* *) Declares three real variables Declares a variable, Ansy of t~pe yes .... No *) I nit. i a liz ('::' s t ~I 0 T' pal va r :i. a bIt:,' s *) (* E;-:ecutabl(·:~ ~:;ection *) BEGIN (* Print instructions for enterin~ data. *) WRITELN('[nter cost of each ~rocer~ item. One itpm per line.'); WRITELN('[nter the value 0.0 to tprminate list of items.'); (* ~~ f~ a d P T' ice san d a (j d f? a d'l t. 0 ~:; IJ tit, 0 tal un til O. 0 i ~:; T' f? ad. *) F,EPEAT READLN(Item_Price); S IJ b tot a 1 !:::: Sub tot a I + :r t e ITI .... P T' icE' UNTIl.. (Item_Price = 0.0); WFn TEL N ( , Sub tot a I e CH.I a Is.... .... ~~ ~; 1..1 b tot a 1 ! 7 : 2 ) ; WR I TE ( 1 D0 ~:l 0 IJ h i3 V pan ~l co U 1''' 0 n s ? T~J F' P ~:l C~ s; 0 T' no and p Y" E' ~,; S <: I:;: E T:>. '); F<EADLN (Ans ) ; I , I F (A n <..; == Y€~ 5 ) THEN BEGIN value of each coupon. One per line.'); <:CTRL/Z> after entering all coupons.'); Rea dan d ~:; u m a IT! 0 I.J n t () f (0 a c h co IJ F' () nun til f~' n d () fin put. WRITEl..N(/T~pe WRITELN('T~pp (* *) f~EPEAT READLN(Coupon_AlT!ount); Coupons := Coupons + Coupon_Amount UNTIL EOF(INPUT) END; Subtract Coupons frolT! Subtotal to obtain Total, and print Total. Total := Subtotal - Coupons; WRITELN('Pa~ this amount $', Total:7:2) END. (* End of Pro~ram *) (* *) You can run the sample program by following the steps outlined in Section 1.2. The source file you create need not have the same name as the PASCAL program. For instance, you can create a file called GROC.PAS to contain the program. The name Grocery Bill is an identifier known only within the PASCAL program. If you do not include the /NOFLAG-NON-STANDARD switch on the PASCAL command, the compiler reports warning-level error messages for each nonstandard feature used in the program. For example, the use of underscore ( ) characters in Grocery_Bill is a nonstandard feature. 1-12 INTRODUCTION The following is a sample run of the program Grocery_Bill. (~F' a ~:; cal P.~!:)CAL>~~! Y'OC. I:,.a~j/nof:l. d~:.! PASCAL>/f?:< :i. t (~l Dad <.~ T'OC • T'C·;:I. l...oar:.l:i.r.£l LINK: EXIT (!~<:; a v f? GF~()C t~ T' U n <.:f T' (J C • (.:.~){ t:' • EXE • 2 !;)Clvecl g l' 0 C • P >: f! cost of €~ach ~.=.lT'oc(·:~r~:J :it,f.:~ITr. Onf:~ itt:'1Tr F'f:~r l:i.ne. Enter the value 0.0 to term:i.nate list of items. :J .25 Ent,~?T' o. ::-)7 3.42 1 • 1 ~.:; 0.89 0.0 Subt,otal [10 T~pe T~pe e~uals -- $ 9.63 T~:lp(,? !:If.''S 0 T' no and p rf?SS <F<ET>. value of each coupon. One per line <CTRL/Z> after entering all coupons. ~<'1U hav(~' an!:J coupon~:;? ~es 0.10 0.25 o. :1.7 0.30 ~Z a~ this amount -- $ 8.81 @ The program Grocery Bill illustrates a small subset of the PASCAL-20 language. It is d;signed to give you a feel for the way the parts of a PASCAL program work together. The following chapters describe the PASCAL-20 language in more detail. 1-13 CHAPTER 2 DATA CONCEPTS This chapter presents an overview of the data concepts used in PASCAL. Section 2.1 briefly describes the PASCAL concepts of data and types. Section 2.2 describes PASCAL's predefined and user-defined scalar types. Section 2.3 describes structured data types, and Section 2.4 describes variables. Finally, Section 2.5 describes how identifiers and expressions are used in a PASCAL program. 2.1 DATA AND DATA TYPES Data is a general term for what the computer uses. Within a PASCAL program, you represent d~ta with identifiers; and, in turn, these identifiers represent certain PASCAL constructions. In a PASCAL program, you must assign each identifier a type. The type defines the set or range of values that is associated with the identifier. The following identifiers can be associated with data types: • Constants • Variables • Functions • Expressions A constant is a quantity that remains the same throughout the execution of a program. A constant's type is the data type associated with that constant. For example, a value of 3.14 can be associated with the identifier pi, which is defined to be constant. Because the value 3.14 is a real number, the identifier pi is evaluated as a real number. A variable is a quantity that can change during program execution. A variable's type is the data type associated with the set of values the variable can assume. In the program Grocery Bill in Chapter 1, the identifier Item Price is an example of a variable; the variable can assume different-values in the program. Because Item Price is defined as an integer, it can be assigned only integer values. A function is a computation that is associated with a name and that returns a value. A function's type is the same as that of the value it returns. Functions are described in more detail in Chapter 7. An expression can be a constant, a variable, a combination of these items separated by operators. is associated with a type. 2-1 function, or a Every expression DATA CONCEP'l'S PASCAL has three categories of data types: • Scalar • Structured • Pointer The scalar data types represent ordered groups of values. PASCAL provides two groups of scalar types: standard (or predefined) and user defined. Integers, real numbers, and a subrange of an integer range are examples of scalar data types. A structured data type consists of a collection of a specific data type. Structured data types are characterized by the types of data that are used, and by their organization. Examples of structured data types are arrays and records. Pointer data types provide access to dynamic data structures. Dynamic data structures are those in which data is stored nonsequentially. Because pointer types maintain pointers to (that is, addresses of) data, information that is nonsequential can be accessed. Scalar and structured data types are described in more detail in the following sections. Pointer data types are described in the TOPS-20 PASCA1~ Language Manual. 2.2 SCALAR DATA TYPES Scalar data types consist of an identifier that is associated with an ardered set of values. A scalar value is used as an individual item; no part of it can be accessed separately. The number 4 is an example of a scalar value. No part of the number 4 can be accessed; the number 4 is treated as a single entity. PASCAL has two categories of scalar data types: standard and user defined. Standard scalar types are those already defined within PASCAL. User-defined scalar types are data types that you can define within your PASCAL program. Associated with each data type is a set of operations that can be performed on those values. For example, addition can be done on integers by using the addition operator (+). The values of a scalar type are ordered; that greater than or less than another value of the can compare scalar data type values of the same among the integers, 2 is greater than 1 but less is, each is either same type. Thus, you type. For example, than 3. PASCAL provides the ORD function which returns the ordinal value of a character. The ordinal value is the numeric value of the ASCII representation of the character. The format is: ORD(x) The ORD function can be used on any scalar type (including user-defined types) except real numbers. The following example shows the use of the ORD function: Expression Returned Value ORD ( ~ A ~ ) 65 ORD(~a') 97 51 ORD ( ~ 3 ~ ) 2-2 DATA CONCEPTS The term ordinal is used to encompass all scalar values other than those of type REAL; that is, the term ordinal covers integer, character, and Boolean values. The standard scalar types are: • INTEGER • REAL • CHAR • BOOLEAN The type INTEGER is used to represent integers. The type REAL is used to represent real numbers. In addition to the type REAL, PASCAL provides the types SINGLE and DOUBLE representing values that are singleand double-precision real numbers, respectively. The type SINGLE is identical to the type REAL. (Throughout this manual, the term "real type" refers to the REAL, SINGLE, and DOUBLE types collectively.) The type CHAR is used to represent character data. Character data consists of the set of 128 ASCII characters. The ASCII character set is shown in Appendix B. The type BOOLEAN consists of truth values: FALSE and TRUE. 2.2.1 The Type INTEGER The type INTEGER represents whole number values ranging from (-2**35) to (+2**35)-1 or -343597383h8 to +34159738367. You write an integer constant as a sequence of decimal digits; no commas or decimal points are allowed. A minus sign (-) before the number specifies a negative integer. A plus sign (+) can precede a positive integer, but is not required. Some examples of valid PASCAL integers are: 452822 o -17 +102 -24824 PASCAL also accepts integers in binary, octal, or hexadecimal notation. To use binary, octal, or hexadecimal notation, refer to the TOPS-20 PASCAL Lan9uage Manual for an explanation of the syntax. 2.2.2 The Type REAL The type REAL represents decimal numbers. The real numbers are decimal numbers that range from approximately 0.14 * 10**-38 through 3.4 * 10**38, with a typical precision of 8 decimal digits. You can express real constants in two ways in PASCAL: • Decimal notation • Floating-point notation 2-3 DATA CONCEPTS In decimal notation, a constant of the REAL type consists of a ninus sign (-) if the number is negative, an integer part, a decimal point, and a fractional part. A plus sign (+) can precede a positive real number, but is not required. At least one digit must appear on each side of the decimal point. Examples of real constants in decimal notation are: 48.25 0.5 -0.8 52.0 0.0 422.004 A zero must precede the decimal point of a fractional quantity, and zero must follow the decimal point of a whole number quantity. a Floating-point notation is used to represent very large or very small real numbers. In floating-point notation, a constant of the REAL type includes a positive or negative decimal number followed by a positive or negative decimal integer exponent written in exponential notation. For example, the following real constants are written in both floating-point and decimal notation: Flo at i ng- po in t Decimal 2.3E2 0.00023E6 10.4E-4 3.l4l5927EO 4.5E9 -0.4E2 230.0 230.0 0.0010 3.1415927 4500000000 -40.0 The exponent consists of the letter E, which can be read as "times 10 to the power of", followed by a positive or negative whole number. PASCAL prints real numbers in floating-point notation by default. In floating-point notation, the position of the decimal point "floats" or moves, depending on the value of the exponent. For example, each of the following numbers is equal to 430.0: 4.3E2 4300E-l 430EO Note that, if the decimal part of a floating-point number is number, you can omit the decimal point (for example, 430EO). a whole You can express double-precision real numbers in floating-point notation, replacing the letter E with the letter D. Refer to the TOPS-20 PASCAL Language Manual for details and examples of the type DOUBLE. 2-4 DATA CONCEPTS 2.2.3 The Type BOOLEAN The type BOOLEAN represents the truth values: FALSE and TRUE. PASCAL orders these values so that FALSE is less than TRUE. Thus, ORD(FALSE) equals a and ORD(TRUE) equals 1. Two kinds of operators combine to form Boolean expressions: • Relational • Logical Sections 2.5.2 and 2.5.3 explain how to form Boolean expressions include relational and logical operators. 2.2.4 that The Type CHAR The type CHAR is used to manipulate character data. A value of type CHAR is a single element of the ASCII character set. The ASCII character set consists of uppercase and lowercase letters, the digits a through 9, an<3 various special symbols, such as the ampersand (&). The full ASCII character set is listed in Appendix B. Appendix B also lists the integer value or ordinal value that corresponds to each element of the ASCII character set. These integers determine how the elements of type CHAR are ordered. For example, the integer 6fi corresponds to the uppercase 'B', and 98 corresponds to the lowercase 'b'. Thus, the character 'B' IS less than the character 'b'. (All uppercase letters have a lower ordinal value than lowercase letters.) The ORD function returns character, for example: the ordinal value for any given ASCII DHD( 'K') This function returns the value 75. To specify a character value with the ORD function, enclose the value in apostrophes; to specify the apostrophe character, type it twice within apostrophes. Examples of constants of type CHAR are: 'A' '* ' '3' ,b' I , , , (the blank character) ( the a po s t r 0 ph e ) The elements of type CHAR are always single characters. A sequence of characters within apostrophes is called a character string (for example, 'John Doe' or 'Memorandum'); character strings are explained in Section 5.1.2. 2-5 DATA CONCEPTS 2.2.5 User-Defined Scalar Types User-defined scalar types are those types that you define within a PASCAL program. A user-defined scalar type can be either an enumerated type or a subrange of any scalar type except real numbers. An enumerated type is an ordered set of values that you define by naming an identifier and the values represented by the identifier. The sample program Grocery_Bill in Chapter 1 defines the type Yes No. TYPE The type Yes No has two values Yes and No. types are presented in Section 3.5. Details on user-defined A subrange type is a specified part of another defined type. The subrange is defined by specifying the lower and upper bounds of the subrange. For example, a subrange of integers could be defined: TYPE 2.3 Ran9f? :;;: 0 •• 100; STRUCTURED DATA TYPES A structured type represents a collection of related data components. Individual components of a structured data type can be accessed and manipulated. PASCAL includes four structured data types: arrays, records, sets, and files. An array is a group of components of the same type. A record consists of one or more fields, each of which contains one or more data items. Records can include fields of different data types. A set is a collection of data items of the same scalar type, the base type. You can access a set as an entity, but you cannot access the set components as individual components or variables. A file is a sequence of data components that are of the same type; each component can be individually accessed. A fiJe can be of variable length. Chapter 5 presents two structured types: the array and the record. For information about sets and files, refer to the TOPS-20 PASCAL Langu~ Manual. 2.4 VARIABLES A variable is an entity that can assume a value during program execution. This value can change any number of times during program execution. In PASCAL, every variable has a name, a type, and a value. The value of a variable is undefined until a value is assigned in either the declaration or the executable section of a program. You establish a variable's name and type in the variable declaration section of a program. The name and type are permanent characteristics during the program execution and therefore cannot be changed. A sample variable declaration section is: VAR Miles, Distance : INTEGER; Gallons, MPG, Liters : REAL; Measure : CHAR; FIBS : BOOLEAN; 2-6 DATA CONCEPTS The word VAR si~nifies the variable declaration part of the declaration section. This variable section declares Miles and Distance as identifiers of the type INTEGER; Gallons, MPG, Qnd Liters as identifiers of the type REAL; Measure as an identifier of the type CHAR; and Flag as an identifier of the type BOOLEAN. One way to assign statement: Distance Mil f~ S ::::; a value to a variable is with an assignment := 1043; [I i ~:; t d n c p ; statement assigns the value of Because Distance is defined, this The value of Miles is then defined. Distance to the identifier Miles. In addition to assignment statements, you can use variable initializations in the declaration section or input procedures in the executable section to assign values to variables. A value can be assigned VAR M:i.lps in the VAR section: I NTEGEF, : ::: A value can also be assigned the following example: 0, shown in This example uses the READLN statement to assign a value to Miles. this example, P~SCAL is waiting for input from the terminal. In H[ADL..N 2.5 in the executable section, as (Mile~;); EXPRESSIONS An expression is an identifier or group of ioentifiers and operators that PASCAL can evaluate. The identifiers can represent individual constants, variables, or functions, for example: subtotal The variable name subtotal current value of subtotal. is an expression that is equal to the Expressions can also be combinations of constants, variables, and functions, separated by operators. For example, the sample program in Chapter 1 includes the following expression: Total := Subtotal - Coupons This expression is equal to the result of Coupons from the value of Subtotal. subtracting the value of PASCAL uses the following types of operators for forming expressions: I, **) 1. Arithmetic operators (such as +, - 2. Relational operators (such as <, >, =) 3. Logical operators (AND, OR, NOT) used in type. Arithmetic operators are Every expression has a Boolean to produce integer or real values. arithmetic expressions results. 2-7 DATA CONCEPTS 2.5.1 Arithmetic Expressions An arithmetic expression calculates an integer or real value. (For the purposes of this section, the term "real" refers to the REAL type. The rules for using values of type DOUBLE in arithmetic expressions differ from those for type REAL. See the TOPS-20 PASCAL Language Manuc~ for information on using the type DOUBLE in expressions.) An expression can be an integer or real constant, variable, or function. Alternatively, it can be formed by combining numeric constants, variables, and functions with one or more arithmetic operators (shown in Table 2-1). For example, the following expression consists of two identifier names and the division operator (I): Miles / Gallons This expression equals the value of dividing Miles by Gallons. Table 2-1: Arithmetic Operators Operator Example Meaning + A+B Add A and B A-B Subtract B from A * A*B Multiply A by B ** A**B Raise A to the power of B I AlB Divide A by B DIV A DIV B Divide result MOD A MOD B Produce the remainder after dividing A by B; B must be greater than 0 REM A REM B Produce the remainder after dividing A by B (can be used when B is <= 0) A by B and truncate the The addition, subtraction, multiplication, and exponentiation operators (+, , *, and **) work on both integer and real values. They produce real results when applied to real values, and integer results when applied to integer values. If the expression contains values of both types, the result is a real number. The division operator (I) can be used on both real and integer values, but it always produces a real result. The DIV operator can be used only with integer values and always produces integer results. DIV divides one integer by another and it drops any remainder. 2-8 DATA CONCEPTS The MOD and REM operators return the remainder after dividing one operand by another. Both operators can be used only with integer values and always produce integer results. The MOD operator can be used only when the divisor is greater than 0; it always returns a positive result. The REM operator can be used whether the integers are equal to, less than, or greater than o. The REM operator also retains the sign of the djvidend. Table 2-2 shows possible combinations operators and the type of the result. Table 2-2: arithmetic operands and Result Types for Arithmetic Expressions Operator Group +, - , of * , ** Operand Types Result Type (1 ) (1 ) Result I op I I 4 + 5 9 op I R 4 • /. • ** 2 1.7114E+01 4 1.800EOl (addition, subtraction, multiplication, exponen t i a t ion) R I op R R (2 ) R op R / (division) DIV, MOD, REM Example R * 4.5 2.2 - 40.12 -3.792E+Ol I op I R 4/2 2.000E+00 R op I R 3.2/2 1.I)OOE+OO I op R R 4/2.14 1.869E+OO R op R R 3.2/2.2 1.455E+00 I op I I 42 DIV 5 8 4 DIV 5 0 32 MOD 5 2 -4 REM 3 -1 (division with truncation, remainder) (1) The symbols "I" and "H" stand for INTEGER and REAL, the symbol "op" stands for "operator." respectively; (2) When you raise an integer to the power of a negative integer you can get unexpected results. Refer to the TOPS-20 PASCAL Language Manual for the rules of how PASCAL evaluates expressions containing negative integer exponentiation. 2-9 DATA CONCEPTS 2.5.2 Relational Expressions A relational expression tests whether a specified relationship between two values is valid. It returns TRUE if the relationship holds and FALSE otherwise. For example, to test whether the variable MAX is greater than the value 100, you can use the following expression: ~1AX :> 100 A relational expression consists of two scalar or character string variables or expressions (such as MAX and 100 above), separated by one of the relational operators listed in Table 2-3. The operands must be of the same type; you compare characters with characters (single or strings) and numeric values with numeric values (integer or real). Table 2-3: Operator Relational Operators Example Meaning A = B TRUE if A is equal to B <> A <> B TRUE if A is not equFlI to B > A > B TRUE if A is greater than B >= A >= B TRUE if < A < B TRUE if A is less than B <= A <= B A is greater than or equal to B TRUE if A is less than or equal to B With character comparisons, the relationship is determined ordinal values in the ASCII character set (Appendix B). by the Note that in the 2-character operators «>, >= and <=) the operators must appear in the specified order and cannot be separated by a space. Relational expressions are often used as tests in PASCAL's conditional and re~etitive statements (see Sections ~.1 and ~.4, for example: IF Measure = '~' THEN BEGIN END; The statements within BEGIN and END are expression (Measure = 'g') evaluates to TRUE. executed only if the As another example, suppose you want to compare the values of two integer variables. To determine whether a variable named New Int is greater than or equal to a variable named Large_Int, you can use the following expression: If Large Int holds the value evaluates to TRUE. ~4 and 2-10 New Int is 72, the expression DATA CONCEPTS Because the elements of scalar types are ordered, you can relational expressions using scalar constants as operands. example, the following expressions are valid: Expression Result 'e' < 't\' TRUE TF~UE :> FAI... f;[ form For TRUE FALSE 5 :::: 4 Any expression that contains relational operators or logical operators is called a Boolean expression because it produces a Boolean result. 2.5.3 Logical Expressions You can form logical expressions by combining Boolean values and the logical operators listed in Table 2-4. Logical expressions return a value of type BOOLEAN. Table 2-4: Logical Operators Operator Ex,ample Result AND A ,Z\ND B TRUE if both A and B are TRUE OR A 'JR B TRUE if either A or B is TRUE, both are TRUE or if NOT NOT A TRUE if A is FALSE, and FALSE if A TRUE is The AND and OR operators combine two Boolean values to form a logical expression. The NOT operator reverses the truth value of an expression; so that if A is true, NOT A is false, and vice versa. The following examples show results. logical expressions Expression > 3) AND (18 = 3 * 6) TRUE (3 > 4) = 3 * 6) TRUE NOT (4 their Boolean in logical Result (4 OR (18 and <> 5) FALSE Boolean variables and functions expressions, for example: can be operands Fla!'J AND ODD(l) Suppose Flag is a Boolean variable. ODD (I) is a function that returns TRUE if the specified integer is odd and FALSE if the integer is even. Both operands, Flag and ODD (I) , must be true for the expression to return a value of TRUE. 2-11 DATA CONCEPTS Another example using a Boolean expression is: (Ints_Read = 10) OR EOF(INPUT) The EOF(INPUT) function returns TRUE if the end of the file INPUT has been encountered. If either or both of the operands in this expression are true, the expression returns a value of TRUE. Precedence Rules for Operators 2.5.4 When evaluating expressions containing more than one operator, PASCAL follows rules of precedence to determine the order in which operations are to be performed. An operation with higher precedence is evaluated before an operation with lower precedence. Consider the following expression: The division operation is performed first; the multiplication operation is performed second; and the addition operation is performed third. For example, if A equals 4 and B equals 2, AlB is evaluated to return 2.0. Then, 3 is multiplied by 4 to return 12. Finally, the results of these calculations are added together to obtain 14.0. You can combine operators to form complicated expressions. For example, if all of the operands are integer, the following expression is valid: A + 5 DIV 2 *4 - C *3 If the current values of A and C are 3 and 8, respectively, this expression evaluates to -13. That is, it is evaluated as if it were written: A t «5 DIV 2) * 4) - (C * 3) Table 2-5 lists the order of precedence of arithmetic, relational, and logical operators, from highest down to lowest. Those o~erators on the same line in the table have equal precedence. Table 2-5: precedence of Operators Operators Precedence NOT Highest ** * I, DIV, MOD, REM, AND +, - OR <>, <, <=, >, >= Lowest 2-12 DATA CONCEPTS In addition, the f~llowing rules apply: 1. Expressions enclosed in parentheses are regardless of the precedence of operators. evaluated 2. Two operators of equal precedence (such as evaluated from left to right. DIV first and *) are The following expressions are evaluated differently, because second expression parentheses enclose an addition operation. in the Expression Result 4 + 8 ** 2 DIV 7 13 (4 + 8) ** 2 DIV 7 20 In the first expression, PASCAL performs the exponentiation (**) and integer division (DIV) operations before the addition operation (+). In the second expression, the parentheses force PASCAL to add 4 and 8 first; then the result (which is 12) is squared to obtain 144; and finally the DIV operation is performed to obtain 20. You should use parentheses when you combine relational and logical operators because the logical operators have higher precedence than the relational operators. For example, in the following expression, the logical operator AND has the highest precedence: A < X AND B <~ Y + 1 PASCAL attempts to evaluate this expression as if it were written: A < (X AND B) <~ Y + 1 An error occurs because X and B are not of type BOOLEAN. To insure that the expression is evaluated as you intended, you must enclose the relational expressions in parentheses as follows: (A < X) AND (8 <= Y +1) Similarly, you must include parentheses in the following expression: NOT (4 <> 5) Without the parentheses, the expression is evaluated as: (NOT 4) <> 5 Because 4 is not a Boolean value, PASCAL generates an error. Parentheses also help to clarify an expression. A long expression is easier to read if it contains parentheses indicating which operations are to be performed first, for example: A + «5 DIV 2) * 4) - (C * 3) The parentheses eliminate any confusion about how the expression is to be evaluated. 2-13 CHAPTER 3 DECLARATIONS AND DEFINITIONS Every data item used in a PASCAL program must either be declared in the program or already be defined by PASCAL. All declarations and definitions must appear in the declaration section. The declaration section can contain the following parts or sections: 1. LABEL declares labels for use by the GOTO statement 2. CONST defines symbolic constants 3. TYPE -- creates user-defined types 4. VAR -- declares variables and their types 5. VALUE -- initializes variables 6. PROCEDURE and FUNCTION -- declare routines These sections are optional in a program. However, when they are included, they must appear in the order listed above. Furthermore, each section (except PROCEDURE and FUNCTION) can appear only once in a declaration section. Thus, each block uses the following reserved words only once: LABEL, CONST, TYPE, and VAR. A block can be a program, a function, or a procedure. All of these sections introduce symbolic names that represent data items. Section 3.1 describes the use of symbolic names and identifiers; Section 3.2 explains the CONST section; Section 3.3 describes the TYPE section; Section 3.4 describes the VAR section; and Section 3.5 describes how to create user-defined scalar types. The LABEL and VALUE sections, along with the GOTO statement, are described in the 1~PS-20 PASCAL Langl~ Manual. 3.1 SYMBOLIC NAMES Symbolic names are the words used in a PASCAL program: some symbolic names are already defined within thE! PASCAL language; other symbolic names can be created by the user. For example, the following line of a PASCAL program contains three symbolic names: VAR Ans The name VAR is defined by PASCAL; the variable name Ans and the type name Yes No are created by the programmer. 3-1 DECLARATIONS AND DEFINITIONS There are three classes of symbolic names in PASCAL: 1. Reserved words 2. Predeclared identifiers 3. User identifiers Section 3.1.1 describes reserved words and predeclared Section 3.1.2 describes how to form user identifiers. 3.1.1 identifiers. Reserved Words, Semireserved Words, and Predeclared Identifiers Reserved words, semireserved words, and predeclared identifiers defined by PASCAL and have a special meaning for the compiler. PASCAL sets aside certain reserved words Some of the reserved words are: AND ARRAY BEGIN CONST DIV ELSE END FILE FUNCTION IF NOT OR PROCEDURE PROGRAM RECORD REPEAT that cannot be are redefined. THEN TYPE UNTIL VAR WHILE Appendix A contains a complete list of the PASCAL reserved Reserved words in this text are printed in uppercase letters. words. In PASCAL, the following words are considered semi reserved words: MODULE OTHERWISE REM VALUE Like reserved words, PASCAL also predefines these semireserved words. However, unlike reserved words, you can redefine these words for your own purposes. If you redefine them, they can no longer be used for their original purpose within the scope of the block in which they are defined. PASCAL declares certain identifiers to name types, constants, procedures, and functions. In contrast to reserved words, you can, if necessary, redefine predeclared identifiers for another purpose. If you choose to redefine these identifiers, you should do so with caution. Once a predeclared identifier is used to denote another item, it can no longer be used for its original purpose within the same program. For example, it is valid to create an identifier named COS within a program. However, once COS is redefined, it would no longer perform the cosine function within the program. 3-2 DECLARATIONS AND DEFINITIONS The predeclared identifiers that have been mentioned so text include: BOOLEAN CHAR COS DOUBLE EOF FALSE INPUT INTEGER OUTPUT READ READLN far in this REAL SINGLE TRUE WRITE WRITELN Appendix A presents a complete list of PASCAL predeclared identifiers. 3.1.2 User Identifiers User identifiers are the names you create to represent programs, constants, variables, procedures, functions, and user-defined types. User identifiers are all the names in a PASCAL program that are not reserved words, semireserved words, or predeclared identifiers. When forming an identifier, you must follow PASCAL syntax rules. An identifier can be a combination of uppercase and lowercase letters, digits, dollar sign ($) characters, and underscore () characters, with the following restrictions: 1. Every identifier must start with a letter, an underscore, or a dollar sign; that is, with any printing character other than a digit. 2. Every identifier characters. 3. An identifier must not contain any blanks. 4. Uppercase and lowercase letters are considered equivalent. must be unique within its first 31 Although identifiers can be any length, PASCAL only recognizes the first 31 characters. Therefore, two different identifiers that have the same first 31 characters are interpreted as the same identifier. Because you can use any letter or digit in identifiers, you can easily create names that indicate what the data item represents. This tends to make your programs easier to read and understand. For example, although the word Slug is a valid identifier, it would not be clear if it were used to represent the result of a square root calculation. An identifier like Square Root, on the other hand, indicates what kind of data that identifier holds. Some examples of valid identifiers in PASCAL are: Miles Liters Math_Scores FICA_ Ta~{ Examples of invalid identifiers are: ARRAY lulore f'ackafJet (a reserved word) (begins with a digit) (contains the special character t) 3-3 DECLARATIONS AND DEFINITIONS The following two identifi~rs are valid according to the syntax of PASCAL. However, they will be treated as the same identifier because they are not unique within their first 31 characters: New_Incorporated_S~stem_Mana~er_Functions New_Incorporated_S~steffi_Mana~er_Re50urces 3.2 CONSTANT DEFINITIONS You can define identifiers to represent constant values in the CONST part of the declaration section. Defining constants up front makes your program easier to read and to modify. These identifiers and their corresponding values are ca] led symbolic constants. For instance, suppose a program that adds apples to oranges uses the number 100 to indicate the maximum number of fruit that can be summed. Instead of using the number 100 in the program, you can define an identifier that represents 100 as follows: CONST . Ma~·: J· ru :i. t :::: 100; The identifier Max Fruit is more descriptive of the constant's use in the program than- the number 100, thus making the program easier to read. You can define any number of symbolic constants in the CONST but the reserved word CONST can appear only once. section, The format of the CONST definition is: CONST constant name IT constant name value; value; ... ] The constant name can be any valid user identifier. The value can be an integer, a real number, a character, a character string (see Section 5.1.2), a Boolean constant, or another symbolic constant. Successive constant definitions must be separated with semicolons. The type of a symbolic constant is the type of its corresponding value. For example, Max Fruit shown above is of type INTEGER because 100 is an integer. Once you define a symbolic constant, the constant identifier can be used in place of the value later in the program. You can change the value of a symbolic constant simply by changing the declaration in the CONST section. However, the identifier represents a constant value that cannot be changed with subsequent assignment statements or input procedures. For example, to define a number of students in definition: constant with the value of 25 as the class, you can use the following constant s~1bolic a You can now use the identifier Class Size to represent the anywhere in your program. 3-4 number 25 DECLARATIONS AND DEFINITIONS The use of symbolic constants generally makes a program easier to read, understand, and modify. If, in the example above, the size of the class is 28 the next term, you can simply modify the CONST definition as follows: Using a constant this way is easier than changing every occurrence the value in the program. of Another example of a constant definition section is: CONST Rain = TRUE; Yea r :::: 20 () 1 ; Pi :::: 3.141!,:j92/; COlTlma =~ C()untr!~ I, I ; ~ I Uni tied Citizenship Sti3t€.~s I = Country; ; This CONST section defines six constant identifiers. The identifier Rain is equal to the Boolean value TRUE. The identifier Year represents the integer 2001, and the identifier pi represents the real number 3.14]5927. The identifier Comma represents the character',', and the identifier Country represents the string United States. Characters and strings must be enclosed in apostrophes in the CONST section. The identifier Citizenship represents the symbolic constant Country and thus represents a character string. Note that, since Citizenship represents a symbolic value and not a string, apostrophes are not used. 3.3 TYPE DEFINITIONS You can define types in the TYPE section of a PASCAL program. The TYPE section associates an identifier with a specified set of values. If a data type is used more than once within the program, it is useful to define the data type within the TYPE section, rather than in the VAR section. This allows you to create a structure that can be accessed by more than one identifier. For example, if a program uses an array structure three times, you can define the array structure in the TYPE section, and declare three variables of that array type in the VAR section. The format is: TYPE type name [type name type definition; type definition; ..• ] Each type name is a user identifier that denotes a type. The type definition specifies any valid PASCAL type. The type definition can be either an enumerated type or a subrange type. An enumerated type lists each of the values associated with the type. The following example declares an enumerated type in the TYPE section: TYPE Da~s = (Sun, Mon, Tue, Wed, Thu, Fri, Sat); In this example, the type Days includes the identifiers Sun through Sat. These are ordered from left to right; that is, the value on the left is less than the value to its right. Enumerated types are ordered starting at zero. In this example, Sun < Mon. 3-5 DECLARATIONS AND DEF~NTTIONS A subrange type uses a subs(?t of a type that is already defined, either by PASCAL or within your program. The subrange type is defined by specifying the lower and upper limits of the subrange. The example below shows a subrange type: TYPE Scores W() Y' k = 0 •• 100; ;::: t1 0 n • • F Y' i ; In this example, Scores includes the values of 0 through 100, and Work includes the values Mon through Fri. 3.4 VARIABLE DECLARATIONS Every variable in a PASCAL program must be declared before it is used. A variable declaration creates a variable and associates it with an identifier and a type. A variable's value is undefined until a value is assigned in the declaration section or in the executable section. The format of the VAR section is: VAR variable name [variable name [,variable name ••• ] [ ,variable name ••. ] [:=value] : type type; .•• ] The variable name can be any valid user identifier. The type can be any of the predefined scalar types (REAL, SINGLE, DOUBLE, INTEGER, CHAR, or BOOLEAN), an identifier previously defined in the TYPE section, or a type definition as outlined in Section 3.1. You also have the option of initializing a variable in the VAR section. Note the last portion of the format. You declare variables in the VAR section of a program, for example: VAR Miles: INTEGER; Gallons, MPG, Liters Mf::'asure : CHAR; Ans: Yes_No; REAL..; This VAR section declares one variable (Miles) of the INTEGER type; three variables (Gallons, MPG, and Liters) of the REAL type; one variable (Measure) of the CHAR type; and one variable (Ans) of type Yes No. Note that you can declare multiple variables in the VAR section, but the reserved word VAR can appear only once. More examples of variable declarations are: VAR Test : BOOLEAN; Initial : CHAR; Cost, Retail_Pr : REAL; Count, Iterations, I, J : INTEGER; Error_Fla~, This VAR section declares the variables Error_Flag and Test of type BOOLEAN; the variable Initial of type CHAR; the variables Cost and Retail Pr of type REAL; and finally, the variables Count, Iterations, I, and J of type INTEGER. Section 3.5 describes how to declare variables of user-defined types. Chapter 5 shows how to declare array and record variables. 3-6 DECLARATIONS AND DEFINITIONS 3.5 USER-DEFINED SCALAR TYPES SINGLE, PASCAL provides the predefined scalar types -- INTEGER, REAL, DOUBLE, CHAR, and BOOLEAN. tn addition, PASCAL allows you to create user-defined scalar types, for example: T Y F' F Y p S .... N (J :: : (y p ~:; ~ No); This user-defined scalar type called Yes No has two values, Yes and No. In this way, it is similar to the-predefined type BOOLEAN which has two values, FALSE and TRUE. There are two classes of user-defined scalar types: 1. En urn era t E~ d 2. Subrange To define an enumerated type, you list th~ type's values, separated by commas, in parentheses. For example, the type definition for Yes No is: (YP~:iY No) To define a subrange type, you specify the bounds of an interval of an existing ordinal type. For example, the following is a subrange of the type INTEGER: (). + tOO This definition specifies a type consisting of the integers from 0 100. to You can define a user-defined scalar type in either of two sections of the declaration section: 1. The TYPE section 2. The VAR section When you define an identifier in the TYPE section, you associate a type name with a set of values. In the example above, the identifier Yes No is the name of a type in the same way that the identifier CHAR is -the name of a type. You must still use the VAR section to declare a variable of the type defined in the TYPE section, for example: Because Yes No is a type that was defined in the TYPE section, you can define more-than one variable of the type, as follows: When you define a type in the VAR section, you associate one or more Thus, the variable names with the set of values of the type. following defines a variable of a subrange type: VAR Pe rcenta~ie o •• 100; The variable Percentage can Percentage is not a type name; take on the values a it is a variable name. 3-7 through 100. DECLARATIONS AND DEFINITIONS Some ex~mples are shown below: Exampl e 1 T Y P E D a ~:~ ;:; .... [} f .... Y p a (' ::" :l.,:-3 6 I.> ; Alphabet ~ IA' •• ' I ' ; Di~its ~ '0' •• '9'; January_Temps ~ -20 •• t60~ I) Ar~ II a ~:I ':; .... nf f ! Da ':~ s .. [} f ... Ye d r 9 Initial : Alphabet; F~ a tin ':.l ! II :i. <J :i. t ~:; ~ A veT' d ~.:.l f.~ .... Jan 1..1 a l' ~:I : ... 1d n u a l' ~:! .... T f' IT! F' ':; Y The TYPE section defines four subrange types: Days_Of_Year, Alphabet, Digits, and January Temps. Note that, for an integer subrange type, the limits can include a leading minus sign (-) or plus sign (+). The VAR section declares the variable Days Off, which can assume the integer values 1 through lr,6; Initial, which can assume the character values 'A' through '2'; Rating, which can assume the character values '0' through '9'; and Average January, which can assume the integer values -20 through +~O. Example 2 TYPE VAl:;: IIa~s ~ (Sunf Man, Tuey Wed, Thu, Fri, Sat); Colors ~ (Red, Yellowy Bluey Oran~ey Purpley Green); Primary_Colors ~ Red •• Blue; Wf~f.~v.. ! Da~~s; Spectrum : Colors; Paints ! Primar~_Colors~ WOT'v.._Da~s : Mon •• Fri; Final_Grade! 'A/ •• 'E'; The TYPE section defines the types Days, Colors, and primary Colors. The type primary Colors is a subrange of the enumerated type-Colors. The VAR section declares variables of the types Days, Colors, and Primary Colors. In addition, the variable Work Days is declared to be of the -subrange type Mon •. Fri, and the variable Final Grade is declared to be of the subrange type 'A' .. 'E'. 3-10 CHAPTER 4 READING AND WRITING DATA To enter data into a program, the program must perform input operations. To display the results of a program's actions, the program must perform output operations. This chapter describes TOPS-20 PASCAL terminal input and output (I/O); that is, how to read and write data interactively from a terminal. The TOPS-20 PASCP~~ Langu~~ Manual conta ins add i tional info rma tion on PASCAL I/O. Specifically, it explains the use of input and output procedures on files other than the predeclared files INPUT and OUTPUT. This chapter covers the following topics: • • • • 4.1 The preeleclared text files INPUT and OUTPUT The predeclared READ and READLN proced ures fo r data input The pr eel ec I a red WRITE and \,IRITELN procedures for data output The predeclared functions EOF and EOLN THE PREDECLllRED TEXT FILES INPUT AND OUTPUT Text files are the basis of input and output, and are passed as program parameters to a PASCAL program. Text files represent an input/output device, such as a terminal or a line printer. You perform I/O operations on file variables. A variable of the structured type FILE is a sequence of data items, called components, that have the same type. The structured type FILE is described in more detail in the TOPS-20 PASCAL Language Manual. PASCAL predeclares two standard file variables as text files: INPUT and OUTPUT. A text file is a file that has components of type CHAR and that is divided into lines. The I/O procedures and functions explained in this chapter perform operations on either INPUT or OUTPUT, by default. PASCAL associates the predeclared file variables INPUT and OUTPUT with your terminal, by default. That is, your terminal is treated as the file INPUT (for reading data) and the file OUTPUT (for writing data). The use of INPUT and OUTPUT is necessary to make your program interactive. 4-1 READING AND WRITING DATA Because INPUT and OUTPUT are predeclared by PASCAL, you must not declare them in the declaration section; however, you must specify them in the heading of each program that uses them. For example, for an interactive program that accepts input data and writes output data (such as the example in Chapter 1), you must specify both files, as follows: F' h' 0 Gf( A M C! roc f~ r- ~:! .... D i. :I.], (I NF'l.J T ~ 0 l.I T P l.I T ) ? You can specify the files in either order. Some programs require no input from the terminal. For instance, a program that prints a table of the ASCII characters needs only the output capability. Its heading might be: p n 0 GF< At1 F' r i n t .... A~:) C I I (0 l.J T r' UT ) ~ This program heading indicates that the name of the Print ASCII and that the program uses the file OUTPUT. program is You can access only one component of a file at a time. Associated with every file is a file position that determines which component can be currently accessed. You can imagine a file's position as a window that moves, through which you can see only one component at a time. A file's current position is the position immediately following the file component that was last read or written. On TOPS-20, you can alter the search path for the INPUT and OUTPUT files without rewriting your programs. You may want PASCAL to obtain input from a file in your disk area (or some other place) rather than from the terminal. Or, you may want PASCAL to write the data to a disk file rather than to the terminal. You have two options: you can rewrite the PROGRAM heading, or you can use the TOPS-20 DEFINE command. The TOPS-20 DEFINE command defines a logical name. A logical name is a descriptive word used to establish a search route for locating files in other directories or on other structures. When you define a logical name, you tell the system where, and in which order, to search for a file. The two logical names you use are PASIN: for INPUT and PASOUT: for OUTPUT. To define a logical name, type the following to the TOPS-20 system: operating (~~DEF I NE PAS IN: f i 1 enalTlf? C~ Because PASCAL associates the logical name PASIN: with the INPUT in your program, PASCAL wil] search for input from the file you specify. Likewise, you can direct PASCAL to output data to some location than your terminal by specifying the following: other @DEFINE PASOUT: f i], enalTle(=-~ To remove a logical name you have defined, give the DEFINE command but do not type any definition. After the DEFINE command, type only the logical name, and press RETURN, for example: @DEFINE PASIN:~ For more information on logical names and the DEFINE command, refer to the TOPS-20 Users Guide. 4-2 READING AND WRITING DATA 4.2 READING DATA To submit data for a program to process, you need procedures that perform input operations. The use of input procedures allows a program to process different sets of data each time it runs. PASCAL provides the READ and READLN procedures for data input. the By default, the READ and READLN procedures get dAta from predeclared file variable INPUT. The READ procedure reads values from a file and assigns them to the variables that are specified as read parameters. The READLN procedure performs a READ operation, then moves to the beginning of the next line of the input file. 4.2.1 The READ Procedure The READ procedure reads data items from the file variable INPUT and assigns the values that are read to specified variables. Thus, you can use a READ procedure to give values to variables, as shown in the following example: F~ E A D (N E~ :< t .... C h C! T' ) v This procedure call causes a character to be read and assigned to the character variable Next Char. from the terminal The general format of the READ procedure, when using the default variable INPUT, is: READ ( [INPUT,] variable file [,variable ... ] ) ; Because the file variable INPUT is the default, you can omit its from a procedure call to READ. name The variable(s) are the parameters of the READ procedure into which values will be read. At least one variable must be specified. The parameters of the READ procedure can be variables of any of the scalar types, including enumerated types. As described in Section 5.1.2, the READ procedure also accepts character string variables as parameters. a The READ procedure reads values from the terminal until it finds value for each variable that is specified as a parameter. The first value found is assigned to the first variable in the list; the second value is assigned to the second variable, and so on. Each variable must have the same type as the corresponding value being read, with the exception that an integer value can be read into a real variable. In the example of the READ procedure below, the variables could be of the types REAL, INTEGER, and INTEGER, respectively: The following values could be read into the specified variables: 9B.6 11 75 The variable Temp is assigned the value 98.6, value 11, and Weight is assigned the value 75. Age is assigned the Note that, in the READ procedure shown above, each input value is separated from the next by a space. Numeric data items, typed at the terminal, must be separated by one or more spaces or tabs, or put on new lines. Because the space and tab are values of type CHAR, this 4-3 READING AND WRITING DATA rule does not apply to character data. If a READ procedure specifies a character variable and encounters a space or a tab, the space or tab is read and assigned to the character variable. As the result of a read operation, the value of the component in the current file position is assigned to a variable; then the file position is advanced one component. Example 1 Statements r<EAD (X~Y); ~;:EAD (A,B); :I. 234 These two READ procedures read the values on the input line into the variables X, Y, A, and B. After they are executed, the variable X equals 1; Y equals 2; A equals 3; and B equClls 4. The file position is advanced to the position that immediately follows the value 4. Example 7. READ (Month, Datev Year); If each of these variables is of type INTEGER, the following are valid input values: 14 1904 After the READ procedure is executed, Month equClls 2; Date equals 14; and Year equals 1984. Note again that you can separate values to be input with any number of spaces. The values also can appear on different lines as follows: 2 14 19B4 In this example, Month is assigned the value of 2; Date is assigned the value of 14; and Year is assigned the value of 1984. The READ statement reads past the EOLN mark and assigns the next input values to the next variables. Exampl e 3 READ (Char_Var); IF Char_Var <> I Count I THEN := Count + 1; Assume that Char Var is a variable of type CHAR and that this segment of code is withi~ a repetitive loop. This program fragment counts the number of characters other than the space character on a line. The READ procedure reads a character and assigns it to Char Yare If the c h a rae t e r i s not a spa c e (' '), the va ria b lee 0 un t i s inc r em e n ted by one. If the character is a space, the assignment statement (Count := Co un t + 1;) iss k i pped • When reading text files into string variables, spaces are assigned to the string variables when the EOLN mark is encountered. EOLN is then TRUE. A READLN statement must be used in this case to pass the EOLN. 4-4 READING AND WRITING DATA 4.2.2 The READLN Procedure An alternative form of the READ procedure is the READLN procedure. The READLN procedure performs ~ READ, and then positions the file position pointer at the beginning of the next line, for example: F<EADL..N (M:i.le~:» Y This READLN procedure reads a value into the variable Miles, then positions the file position pointer at the beginning of the next line. Thus, any remaining data on the input line is ignored. In contrast to the READ advanced to the first READLN procedure. procedure, the file position pointer is component of the next line at the end of the The format of the READLN procedure using the default file INPUT is: READLN ( [INPUT,] [variable] [,variable] .•. ); After a value is read for each variable that is specified as a parameter, the rest of the current line is discarded; and the file position is set to the first component of the next line. As shown in the format description, the variable list in the READLN procedure is optional. Therefore, you can use READLN as follows: This statement advances the file position pointer to the beginning the line after the current line without reading any values. of Exampl e 1 Input Statements F~EADL.N (X, Y ) ; 123 4 "7 22 18 12 I=i:E.ADLN (A, II) ; The values assigned in this example are: X A 1 y "7 B - 22 ,.) A- The first READLN procedure reads the values 1 and 2 and assigns them to X and Y, respectively. Then, the file position pointer is advanced to the beginning of the next line, and the remaining numbers on the first line are ignored. The second READLN procedure starts reading data from the second line of the input file and assigns the value 7 to A and the value 22 to B. If these READLN procedures were both READ procedures, only the first line of input would be read. Example 2 Input Statement 1 100<EOLN> 1000 1001<EOLN> READLN (X,Y,Z) The values assigned in this example are: X Y Z 1 100 1000 4-5 READING AND WRITING DATA This procedure call assigns 1 to X, 100 to Y, and 1000 to Z. Then, the file position pointer is advanced to the beginning of the line following the values 1000 and 1001. Note that the READLN procedure reads across lines until a value is found for each specified variable, and moves to the next line only after those values are assigned to the variables. Thus, in this example, when there are no more values on the line containing 1 and 100, the value 1000 from the next line is read and assigned to the variable Z. Exampl e 3 AD (C h a r .... (,,1 a Y' ) Y IF [OI ... N THEN f~EADl..N Y I F C h a r' .... VaT' <::> ,. / T HF N Count.. !"" COl..lrd__ + 1 y f~ [ The following shows the value of Char Var input: after reading the sample Value of Char Var t. h i ~:; <: E 0 I... N :> 4 thi.s i~; 11 a t f= ~:; t <EOI...N> <: E () L.. N :> This example shows a code fragment similar to the one used in Example 3 in Section 4.2.1. Included also in this example is a READLN statement. This program fragment counts the number of characters other than the space character in a file. The READ procedure reads a character and assigns it to Char Var. If the character read is the EOLN, then the file position pointer is moved past the EOLN mark and positioned at the beginning of the next line. If the character is not a space, the variable Count is incremented by one. If the character is a space, the assignment statement (Count := Count + I;) is skipped. 4.3 WRITING DATA To display the results of a program's actions, the program must perform output operations. PASCAL provides the WRITE and WRITELN procedures for data output. By default, the WRITE procedure writes data onto the file OUTPUT, which is associated with your terminal. The WRITELN procedure performs the WRITE procedure, then positions the file position pointer at the beginning of a new line. 4-f) -----------------------------------------------------,.-------------------------- ,------------------------- READING AND WRITING DATA 4.3.1 The WRITE Procedure By default, the WRITE procedure writes data OUTPUT. It has the general form: into the file variable WRITE ( [OUTPUT,] print list); Because OUTPUT is the default, you can include or omit the name OUTPUT in the WRITE procedure call. The print list specifies write parameters, that is, the values to be written. It can contain: o~ • Expressions any scalar type • Character strings enclosed in apostrophes Multiple parameters in the print list must be separated by commas. To pr int the val ue of a symbol ic constant or a variable, you need to specify only the variable name. You can print the result of an arithmetic, relational, or logical expression by specifying the expression in the print list. In addition, you can use the WRITE procedure to print a character string to explain the output. Examples of WRITE procedures with variable, Boolean expression, and string parameters are shown below. For each output line, a blank sign () indicates that the corresponding WRITE procedure prints a space. Statements l,JF\JTE Output 12 (IntVar), FAI...!:;[ l.,lF~ITE ( I IntVar pC~l..Ials' ~ IntVar) ~ I n t VaT' p C~ U a :I. ~:; 12 Each output line is shown above as PASCAL would print it. PASCAL automatically provides spacing for various kinds of output. Thus, in the first two examples, the output values (that is, the value 12 and the value FALSE) are printed with a default number of leading spaces. You can control the spacing by specifying the field width as explained below. The third example shows how to print a character string and a value. A character string is a sequence of characters enclosed in apostrophes (in this example, 'IntVar equals') and separated by commas. The value 12 is printed with a default number of leading blanks. After a WRITE procedure is executed, the file position pointer is positioned immediately after the last value that was written. Thus, if the three WRITE procedures shown above appeared in three successive program statements, all of the output would appear on the same line. Field Width The field width is the minimum number of characters that will be written to the terminal. You can specify a minimum field width for each possible write parameter in the print list. However, without the field width specification, PASCAL uses the default values listed in Table 4-1. 4-7 READING AND WRITING DATA Table 4-1: Default Value for Field Width Type of Variable Number of Characters Printed INTEGER 10 REAL l~ DOUBLE 24 BOOLEAN CHAR 1 enumerated string Length of string For example, the default field width for a real value is 16 characters. If the value of a real variable called Average is 5.5, the value is printed as follows: Statement Output WRITE 5+500000000[+00 (Avera~e); Note that real values are printed in floating-point format, by default. The value of Average is written in a field of l~ characters (which includes a leading blank). You can override the default fo~ a particular value by specifying a field width in the print list. The following is the general form of the field-width specification: write parameter minimum [: fractionD Minimum and fraction must be positive integers. Minimum indicates the minimum number of characters, including padding spaces, that are to be written. Fraction, which is used only with real values, indicates the number of characters to the right of the decimal point. For example, you may prefer to print the real value of Average in the more readable decimal format. You can include field-width parameters in the WRITE procedure call to do this: WRITE ('The avera~e is',Average:4:1); This statement produces the following output: The average is 5+5 The integer 4 indicates that at least four characters will be printed. This count includes -the decimal point and a minus sign (-) if the value is negative. If the value is positive, as above, this minimum includes a leading blank. The integer 1 specifies that one digit will appear to the right of the decimal point. Thus, the WRITE procedure above specifies a field at least four characters wide, with one character to the right of the decimal point. 4-8 READING AND WRITING DATA The following rules apply to output procedures: designating field-width parameters value, in 1. If the fraction parameter is omitted from a real value is printed in floating-poi~t format. 2. If the print field is wider than necessary, PASCAL prints the value with the appropriate number of leading blanks. 3. If the print field is too narrow, PASCAL treats the different kinds of write parameters as follows: values on the • Truncates strings and nonnumeric scalar right to the specified field width. the • Prints integers and real numbers in decimal format using the full number of characters needed for the value, thus overriding the field-width specification. • Prints real and double values in floating-point format in a field of at least eight characters (for example, -l.OE+OO). All real values in either format are printed with a leading blank if they are positive and a leading minus sign if they are negative. Example 1 Statement WRITE ('First number -- ',Number:9); Output F i Y' ~:> t n IJ III b E~ Y' 1 If Number is an integer variable whose value is 1, this statement prints the text ('First number -- ') followed by eight spaces and the numeraL 1. That is, 1 is right-justified in the field of nine characters. Example 2 Statement WRITE ('This is a test strinS':12); Output This is a te The text in this example is truncated on the right into the field of 12 characters. 4-9 so that it fits READ1NG AND WRITING DATA Example 3 Statement BEGIN Av f~ l' a !J E' : "" ::.';. ~.:; ¥ WI:~ J T F (N u In tl e r : 4 y I V d 11 .I f.~ ~:; a vel' a '.'.l C~ d t 0 I YA v C-:-~ r· a !.:.! (.:.~ : 3 : 1 ) ; END; One WRITE procedure can contain several values and strings as in this example. If Number equals 5 and Average is 5.5, the output shown is printed. Three leading blanks are included before the number 5 to fill the print field, which is 4. Note that the value of Average is printed in a field of four characters, including the leading blank, even though the procedure specifies a field of three characters, thus overriding the field-width specification of 3. Example 4 Statement BEGIN Nurnl :~-:: 7:1..1.; N 1..1 III 2 ::" 2 9 • 9 , N u m3 : :::: 1 O:J. • 0 ; WF, T T F (N UITI 1 : :::.; : 1. , I END;: a n c.1 I y Nu m2 : ::.:; : 1 y I SUIT! t (] I , (N um 1 +N U m2 ) : (.) : 1 ) ;: 7:L.1 anc.i 29.9 sum to lOt.O This example shows an arithmetic expression as a write parameter. The values of Numl and Num2 (71.1 and 29.9, respectjvely) are each written in a field of five characters. The expression (Numl + Num2) is evaluated, and the value (101.0) is printed in a field of six characters. Example 5 Statements WRITE ( 'F iT's t co lU1l1 n h P d din g WRITE('Second column headin~':35); I Fi1'st column ) ; Spcond column headin~ headin~ Remember that, after a WRITE procedure is executed, the file pointer is positioned after the last character printed. Therefore, two consecutive WRITE procedures print data on the same line. The first procedure call to WRITE prints the text, leaving the file position after "heading". The second procedure call right-justifies its text in a field of 35 characters. 4-10 READING AND WRITING DATA Example () If you specify a variable of an enumerated type as a write parameter, PASCAL prints the constant variable that names its value in uppercase letters. For example, suppose the variable Color is defined as: V A f~ Col C) r (B 11..1 f~ ~ Y p:l 1 01,,1 Y B :I. a c k y ~::; 1 :i. ~.:.l h t 1 ~:! .... F' a 1 i-:-~ .... F' (.:~ a c h .... ~:) 1..1 HI III C~ T' .... ~:; 1..11"1 !:; (C.I t ) Y : Assume that the value of Color is Yellow. call: tJ r~ I TE (I ~1 ~:! f i~: V 0 l' :i.·t f~ co:l. () Y' :i.!:; Then this WRITE procedure I ~ Co :I. 0 r : 33 ) : produces the following output: M~ YEI...I...Ol,,1 favur:i.te color is Note that yellow is printed right-justified and uppercase, preceded by 27 blank spaces. When the value of Color is Slightly_Pale_peach_Summer_Sunset, however, the following appears: M,::! f avo l" :i. tf~ co:l. 0 1" :i. !:; ~:; I... I GH T I... Y .... PAL E ... P E () CH.... ~:; l.J MM[ F;: .. _~:; l.J N ~:; PASCAL only recognizes the first 31 characters in a variable name. Thus, although the field width specified is wide enough for all 33 characters, only the first 31 characters are printed; and they are right-justified in the print field. 4.3.2 The WRITELN Procedure An alternative form of the WRITE procedure is the WRITELN procedure. The WRITELN procedure performs the WRITE procedure, then positions the file position pointer at the beginning of a new line. It has the general form: WRITELN [ ( [OUTPUT,] print list)] Write parameters are specified in the print list in the same manner as in the WRITE procedure. Furthermore, the field-width rules described in that section also apply to the WRITELN procedure. the WRITELN If you have multiple parameters in the print list, procedure prints all of the values on one line, and then starts a new line. Alternatively, you can omit the print list altogether. This is useful when you want to start a new line or write a blank line to the output file. Exampl e 1 Statements WRITEI...N(/The value of X is ',X); WRITEI...N('The value of Y is I,y); OutEut ThE~ value of X is The value of Y is 10 15 4-11 READING AND WRITING DATA In the output, the write parameters from each WRITELN procedure appear on different lines. After both WRITELN procedures are executed, the file position pointer is positioned at the beginning of a new line following the output. In contrast, if you use WRITE procedures instead of WRITELN procedures, the output from both of the print lists appears on one line, as follows~ The value of X IS lOThe value of Y is 1.5 The file position pointer is positioned immediately 15. after the value Example 2 Statements 21.) ) ; WiH I TEL.N ( I Name: I ~ .' A!.:H:~: I : 1 cl y I Soc. !:;f.-~c. t.,IF,ITELN; W' F( I TEL. N ( I n() C T' a t f.~ ~:; I y I [ ) J d I : :1. ~.:j , .' Un k now n I : 2 -4 ) ; : I : Output Soc. Old Hf~C. Unknown This example illustrates how multiple parameters in the print list of a WRITELN procedure are printed. All the items in the print list are printed on one line. Then, the file position pointer is advanced to the beginning of a new line. This example also shows how to print a blank line by omitting the print list. The second WRITELN procedure call prints no characters, but creates a new line. 4.4 THE PREDECLARED FUNCTIONS EOLN AND EOF The EOLN and EOF functions are predeclared PASCAL functions that operate on file variables and yield Boolean results. The EOLN function tests the end-of-line condition. The EOF function tests the end-of-file condition. 4.4.1 The EOLN Function Text files are divided into lines. Each line line-separator mark indicating the end of a line. this end-of-line mark with the EOLN function. ends with a You can test for The format of the end-of-line function is: E:OLN [ (file variable) ] i The file variable must be a variable of type TEXT. The file variable is the default file INPUT. You can either specify the name INPUT or omit the file variable altogether, because INPUT is the default. The function EOLN is true when the file position pointer is at the end of a line, or after the last component on a line has been read. Otherwise, EOLN is false. After a READ procedure reads the last component on a position pointer is on the EOLN mark. 4-12 line, the file READING AND WRITING DATA In contrast, after a READLN procedure reads the last component on a line, the file position pointer is at the beginning of the next line, that is, past the EOLN mark. Thus, after a READLN is performed, the EOLN function IS not true unless the next line is empty. For this reason, the input procedure before an EOLN test is usually a READ, not a READLN. If a READ procedure specifying a character variable as a parameter encounters the EOLN mark, a space (' ') is assigned to the variable. To specify the end of a line when typing input at the terminal, you press ~, thE~ RETURN key. Aftl=r a READ procedure reads the last character that was typed before the RETURN key, EOLN becomes true. The following loop shows the use of the EOLN function: WHILE NOT EOLN(INPUT) DO BEGIN I:~EAD (Ch); NUffi_Chars EN[lv := NUffi_Chars t 1 The variable Ch is of typE! CHAR, and Num_Chars is of type INTEGER. This loop counts the number of characters on a line. The WHILE statement causes the loop body to execute repetitively as long as NOT EOLN(INPUT) is true. When the last character on the line is read, EOLN becomes true. The WHILE statement tests for NOT EOLN(INPUT), which is now false. Therefore, the loop is not executed again. The WHILE statement is described in Section 6.3.3. 4.4.2 The EOF Function Every file ends with an end-of-file mark that you can test with the EOF function. The EOF function is true when the file position pointer is on this end-of-file mark. The EOF mark follows the last EOLN mark in a file. The format of the EOF function is: EOF [ (file variable) ] ; The file variable can be a variable of any file type. the file variable INPUT is the default. As with As soon as the last line in a file is read, EOF becomes true. other times, EOF is false. EOLN, At all You usually use the READLN procedure before an EOF test. If you use a READ procedure, the last component in the file is read; and the file position pointer is on the EOLN mark. EOF is false because the file position pointer has not been advanced to the EOF mark. When a value is being read into a character variable, EOF is false after a READ procedure. In this case, after the last component in a file is read, the file position pointer is at the EOLN mark. EOF is still false. As a result of one more READ operation, a space (' ') is assigned to the character variable; however, the file position pointer remains at the EOLN mark. It is necessary to use a READLN procedure to position the file position pointer at the EOF mark. Until a READLN procedure is used, spaces continue to be assigned to the character variable. 4-13 READING AND WRITING DATA The diagram in Figure 4-1 represents the characters and the EOF marks in a text file. EOLN EOLN and EOF MR S-3077-8~l Figure 4-1 The End of a Text File text file. Suppose The symbol X represents the last component of a by X into a the following procedure reads the component denoted variable: READLN(variable); The variable is assigned the value in X. The READLN procedure advances the file position pointer past the EOLN mark (that is, to the EOF mark). Thus, the file position pointer appears as shown in Figure 4-2. Beginning of File I I L· · · ~--~- EOLN EOF I ---------~--~ File Position MR-S-3078-83 FigurE~ 4-2: File position Pointer at End of File When you are typing input at the terminal, you can indicate the end of the file by typing a <CTRL/Z>. The <CTRL/Z> generates an EOLN mark and an EOF mark. When a READLN procedure reads the last component typed before <CTRL/Z>, EOF becomes true. The READLN procedure reads past the EOLN mark and causes the file position pointer to be on the EOF mark. The following example shows the use of <CTRL/Z> to represent the EOF constl~uct: 'JAR Score, Total, Count: INTEGER; Av (-;:0 T'a~.=leSco rf:'~ : F~EAL; BEGIN Total :::;: 0; COI.Jnt : = 0; When done, WF~JTEI... N ('Ent(·:·~r ~Iour SCOT'es. WHILE NOT EOF DO BEGIN READLN (Seo T'e) ; Total := Score + Total; Count := Count + 1; END; Avera~eScore WRITELN ('The END. := Total/Count; avera~e score is: t~pe CTRL Z'); (*to produce real result*) ',Avera~eScore:4:1); 4-14 ----------------------------------------------,------------------,-------------------- READING AND WRITING DATA In Average Score, the first WRTTELN statement displays instructions for enterTng data items and terminating the list of items with a <CTRL/Z>. Each time the READLN procedure reads a value for the variable Score, it reads past the EOLN mark. On the last iteration, the READLN procedure encounters the end of the file, which was generated by the <CTRL/Z>. 4-15 ----------------------------------------------- CHAPTER 5 STRUCTURED TYPES: THE ARRAY AND THE RECORD This chapter describes the use of two structured data types: arrays and records. Structured data types are composed of scalar data types. The types presented in previous chapters of this primer are all scalar types. A variable of a scalar type is an indivisible unit of data. Scalar types cannot be divided into smaller, individually manipulated data items. A variable of a structured data type, on the other hand, is a collection of related data items that can be accessed and manipulated individually. You can refer to an entire structured variable with one identifier, or you can treat its data items as single variables. PASCAL provides the structures: • Arrays • Records • Files • Sets following structured types for building data An array is a collection of data items of the same type, called components. A record is a collection of data items, called fields, that can be of different types. A file is a sequence of data items, called components, of the same type. A set is a collection of ordinal scalar components or members. This chapter presents the array (Section 5.1) and the record (Section 5.2) types. A special case of the file type -- that is, the text file -- was introduced in Chapter 4. A detailed presentation of the file and set types, however, is beyond the scope of this primer. The TOPS-20 PASCAL Language Manual describes sets and files in more detail. ------ 5-1 STRUCTURED TYPES: THE ARRAY AND THE RECORD 5.1 ARRAYS An array is a group of data items of the same data type. Each data item in the group is called a component of the array. You refer to the whole array with one identifier. You refer to each component with the array identifier and an index that is enclosed in square brackets. The indices need not be integers; they can be values of any scalar type except a real type. The format of the type definition for an array is: ARRAY [ index type [ ,index type •.. D 1 OF component type; The index type can be a subrange of any ordinal type. It can also be the full range of the CHAR type, the BOOLEAN type, or an enumerated type. For example, you can specify the index type in the type definition with the identifier CHAR. However, the index type cannot be the full range of the type INTEGER. The components of an array can be of any type, including structured types. For example, you can define an array of integers, an array of records, or an array of real numbers. An array of arrays is a multidimensional array, as explained in Section 5.1.1. The following VAR WOT'd is an example of an array declaration: ARRAY[1 •• 20J OF CHAR; An array declaration establishes three properties: Tn the 1. The identifier that names the whole array. above, th~ name of the array is Word. 2. The range and type of the indices. In the array indices are a subrange -- 1 .• 20 -- of integers. 3. The type of the components. type CHAR. The compon~nts of example Word, Word are the of You refer to an array component with the array identifier and a bracketed index. The index can be any expression of the index type. Thus, in the array Word, the first component is Wordrl]; the second is W~rd[21; and so forth. You can use array components in the same way that you use any component of the same type. For example, if Word is defined to be of the CHAR data type, you can use Word[2] as a variable of the CHAR data type. Thus, Word[2] could appear on the left-hand side of an assignment statement or as a parameter of the ORD function. 5-2 - STRUCTURED TYPES: THE ARRAY AND THE RECORD The type definition shown ?bove can appear in the TYPE section or in the VAR section. Where the type definition appears depends on whether you are defining a type or using a previously defined type. An example of defining an array type in the TYPE section is: TYPE P l' i. C(·:·)S ::: AF~RAY I:: :t. •• 100 J OF I:;:EAI...; This TYPE section defines the type Prices whose index type is the subrange 1 .. 100, and whose component type is REAL. You can declare a variable of type Prices as follows: VAR Items: Prices; item Suppose a store has up to 100 kinds of items for sale, and each The is associated with a stock number in the range of 1 to 100. identifier Items represents the price for each item. Thus, for example, the price for item number 20 is stored in Itemsf201. The following declarations show variable in the VAR section. T YP E 11 a ~:J~:; ::~ W0 r'k Da ~:I (f:) 1..1 n, M0 n, T 1..1 (.:.) y an example lAJ f) d , T h u, of F r :i. y declaring ~:) an array at) ; () + + ::2 4 y VAR WorkWeek: ARRAY[Mon •• FriJ OF WorkDay; In the array WorkWeek, the index type Mon .• Fri is a subrange of the enumerated type Days. The component type WorkDay is a subrange (0 •• 24) of the integers. This declaration creates the variable WorkWeek in which each of the five components represents the hours worked in one day. Suppose you want to write a program to calculate the average score of a test of several students enrolled in a course. You can treat the group of test scores as an array, and thus keep each score recorded by a particular student. The following declarations create an array type and a variable of that type: TYPE Tests = 1 •• Max; TestScores = ARRAY[TestsJ OF INTEGER; VAR Score: TestScores; Note that you can use a type identifier (for example, Tests) as the index type in an array definition. If Max is equal to six, TestScores is an array of integers whose index can range from one to six. To use an individual score in an executable statement, specify the array identifier (Score) and an integer expression whose value is between one and Max. 5-3 STRUCTURED TYPES: THE ARRAY AND THE RECORD A program that calculates the average of the components in Score might be written as follows: PH()Gr<A~1 N(.;.~w .... AvpY' (INPUT y the array OUTPUT! y (* N !..Ill"! b f~ Y' 0 f ~;; cor (.:.~ ~;; C Cl N ~; T Md ;.: C": I.) ~ T Y F' E T €-~ ~:; t S :::; 1... Md;': y T est ~) COY' f! (;; :": A F< F.; A Y L T ~.~ ~;; t ~;; J 0 F J N TEn E F~ y V (:1 F< ~) C () }"' f:'~ ! r e ~;; t~) COT' t:-~ ~:; Y S 1..1111 ~ I y Av (.;.~ 1""" a ~.:.! €.~ ! TNT E GF F;: ; to tl (-;-' a v (.:~ l' d ~J p (1 *) BEGIN ~31.J HI : :::: FOR I 0; (* ACCf~~:;~:; each COITIF'onent of ~:;co re *) := 1 TO Max DO BEGIN ~J r~ I T [( I [n t e l' t f..~ ~:; t S COT' e ! READLNCSco1'eLIJ); ~:; U IT! !":: ~:; I..IITI .') v (* Read an inte~eT' into each cOIl"!Ponent *) + ~:; cor t:·~ r I :1 (* ~:; I.J III t h f·! C D ITI r:' n (.:.~ n t ~::. *;. <:) END; Av ~:~ r' a ~.~ f~ :::" ~3 u ITt D I V Ma;.; ; WF< I T F L.. N ( I T h (.:.~ f () :I. :I. 0 w :i. n ~J ~:; COT' f! <;; weT' f:.' en t e l' c·:·~ (".1: I ) ; FOR I := 1 TO Max DO (* F' r :i. n t e a c h C 0 HI F' 0 n f! n t 0 f WF< I T F I... N ( ~;; COT' c·~ r: I J : 4 ), Wr;: I T [ I... N ( I The a v C-~ T' a ~~ (.:! :i. ~:; : I, ~;; cor p *) A v f~ l' a ~:.~ e : 3 ) END. The program reads each score that is typed after the prompt Enter test score: and calculates a running sum. ~~e average of the scores is the result of the expression Sum DIV Max. Output procedures print each score that was entered and the average score. A sample run of this program is: En t C~ T' t est F n t C·? T' t e ~:; t E::rlt.(·~ r t,es t., 5 COT' e : ~:;c~c) r(-~: . ~I~j Ent(·:·~r te~:;t ~:;core! Ente l' te~:; t ~;;co 1'e: Eft t€·~ T' t€-)S t seo T'(':'): 'YO b3 74 ~;; cor (.:.~: 1 0 () 0n The follDwin~ SC01'es tOO were ente1'pdt 8B 7~j 90 63 94 The average is: 85 In an executable statement, you can specify a component an index that is an identifier. In both FOR loops New Aver, the current score is denoted by Score[I]. index can be any expression of the index type; example, refer to a component as Score(I+ll (as long as rang e 1 .. f)) • 5-4 of Scores with in the program In fact, the you could, for 1+1 is in the STRUCTURED TYPES: THE ARRAY AND THE RECORD The array component ScorerI] is used in the same manner as a variable in the READLN st,:=ttement, in the expression Sum + Score[Il, and in one of the WRITELN statements. 1n fact, ScorerI] is a variable of type INTEGER. You can use the assignment operator (:=) on two arrays of the same type. The following example creates two array variables, called Current Jan and Record Jan, that are both of type Month Temp. Month Temp is a type that represents the temperatures for each day in a month. The executable section in the example shows the assignment of one array to another. (* Declarations *) CONBT [ta~:t!:; :::: 31; (* nl.Jmt:.lf:~ r of da\:l~:; *) :i. n Jan (* TYPE Temp = -20++60; ran~e of temps occurrin~ in Jan *) Month_Temp = ARRAY[l.+[ta~s] OF Temp; (* Month_Temp has 31 components, for each da~ in Jan *) VAR Bum, I, Averase_Temp, Record_Ave_Temp : INTEGER; (* ave temp in current Jan *) (* ave temp in Jan with record lows *) CUT' r f:~ n t .... Jan, Re cor (i .... Jan ! M0 nth .... T E~ IT! F" ; (* Current_Jan and Record_Jan represent each da~/s temperature in this ~ear's Jan and the Jan with lowest averaSe temp, respectivel~, *) (* Executable Section *) Bum ::::: 0; FOR I := 1 TO Days DO Sum != Sum t Current_Jan[I); Avera~e_Temp != Sum DIV Da~s; (* if avera~e temp this ~ear is less than the record ~ear, assi~n this ~ear's temp arra~ to the record temp IF AveraSe_Temp < Record_Ave_Temp THEN Record_Jan != Current_Jan; The last line of the another. code shows the assignment of one arra~ *) array to This program fragment computes the average of the components of Current Jan to obtain the average temperature for the month, and assigns-that average to Average Temp. If the value of Average Temp is less than that of Record_Ave_Temp, the array Current Jan is assigned to Record Jan. 5-5 STRUCTURED TYPES: THE ARRAY AND THE RECORD 5.1.1 Multidim~nsional Arrays So far only one-dimensional arrays, that is, arrays with one index, have been discussed. An array whose components are themselves arrays is a multidimensional array. ~n array can have any number of dimensions. Each dimension has its own index, and each dimension can have a different index type. For example, the declarations below create a two-dimensional array: CONST ClassSize = is; N!..IITJ T€~ ~:; t ~;; :::: ~.:j; TYPE Class = 1 •• ClassSize; Tests = 1 •• N!..IffiTests; VAR ClassScores : ARRAY[Class] OF ARRAY[Tests] OF INTEGER; The variable Class Scores represents scores on a series of tests for a group of students. If Class Size is 15 and Num Tests is 5, these declarations create a two-dimensional array called Class Scores that can store the scores on 5 tests for each of 15 students. You can abbreviate the array declaration shown above by specifying all the index types in one pair of brackets as follows: VAR Class_Scores: ARRAY[Class, Tests] OF INTEGER; To refer to one component of a two-dimensional array, use the array identifier and two indices, one to specify each dimension. The first index corresponds to the first dimension declared, and the second index corresponds to the second dimension declared. The first dimension is the row, and the second dimension is the column. For example, Class Scores[I,3] indicates the first student's third test score, and Class_Scores(3,11 indicates the third student's first test score. The Class Scores array is illustrated in Figure 5-1. Tests (columns) , * r 10 0 DOD 20 0 000 Class (rows) • • • 14 15 0 0 0 0 0 0 0 0 0 0 MR·S·3079·83 Figure 5-1: The Two-Dimensional Array Class Scores 5-6 STRUCTURED TYPES: THE ARRAY AND THE RFCORD The index ranges in Class Scores that is, Class and Tests correspond to the rows ~nd columns, respectively, in the figure. In references to one component of Class Scores, the first index indicates the row, and the second indicates Ihe column. A particular score is found at the intersection of a row of Class and a column of Tests. For example, Class Scores[3,5], indicated in Figure 5-1 by an X, is at the intersection 07 the third row and the fifth column. To access successive components in a multidimensional array, you must use the proper control loop. Nested FOR loops are often used for this purpose. Refer to Section 6."3.] for a discussion of FOR loops. The following declaration creates a variable that holds each student's average score: ARRAY[Class] OF INTEGER; The following statements include nested FOR loops to compute the average for each student and to store that average in the appropriate component of Clas::;_AveragE~s. FOR I BEGIN ~31..11l1 := 1 to ClassSize DO : :~: FOR J (); := 1 TO NUITI_Tests DO S U ITI ::::: S!..IIT! + CIa ~:; ~:; !:) c () Y' f? S r: I y J] , C las s .... A v P l' a !.:l P ~:; £: J:1 : :::: S 1..1111 D I V N U Ill .... T (~! ~:; t~:; ; END, The inner FOR loop sums the components in one row (row I). The average of those components is assigned to Class Averages[Il. The outer FOR loop causes this operation to be performed-for each value of I, that is, the values] through Class_Size (15). For example, on the fourth iteration of the outer FOR loop, each component in the fourth row is processed. The components Class Scores [4 ,J], where a ranges from 1 to Num Tests (5), are summed. Class-Averagesr41 is assigned Sum DIV Num_Tests, where Num Tests equals 5. You can define arrays of three or more dimensions by appropriate number of index types in the array example: VAR HotE\l .... Vacanc:i.es :: ARI~AYr:l •• n, /A/ •• IHI 1I specifying the definition, for l •• lO] OF BOOLEAN; The variable Hotel Vacancies represents a hotel with 160 rooms. The hotel has eight stories, each denoted by a number from one to eight. Each story has 2 corridors, and each corridor has 10 rooms. The three dimensions of the array have index types 1 •• 8, 'A' •• 'B', and 1 •• 10, corresponding to the stories, corridors, and rooms in each corridor of the hotel. Thus, each component in Hotel Vacancies represents a room in the hotel. An individual component o~ Hotel Vacancies has the value TRUE if the room is vacant and FALSE if it is full. 5-7 STRUCTURED TYPES: THE ARRAY AND THE RECORD Components Name[l] through Name[12] contain the characters "Joshua Jones". The READ procedure automatically assigns spaces to components Name[13] through Namer20]. Note that, if there are additional characters on the line instead of the EOLN mark, these characters can be read into components of Name. Similarly, you can use for example: WRI~E or WRITELN to print a string variable, W':;: J T E ( Na ITI e ) P This WRITE procedure produces the following output: Joshua ,.lone!:; You can apply the relational operators «, <=, >, >=, =, and <» to character strings of the same length. The result of comparing two strings depends on the lexical ordering of the strings. Just as words in a dictionary are arranged according to an alphabetical ordering, character strings are ordered according to the ordinal value of corresponding characters in the string. (See Appendix B for the ordinal value of each component in the ASCII character set.) PASCAL evaluates string expressions by comparing characters that occupy corresponding positions in the two strings. When the first nonequal characters in the two strings are compared, the string that contains the character with the higher ordinal value is found to be greater than the other string. If all characters are the same, including spaces, the strings are equal. For example, the following relational expressions are true: 'Pekinese' < 'Saint Bernards' 'wine & roses ' ) 'wine & cheese' The first expression is true because the ordinal value of 'pi (80) is less than the ordinal value of'S' (83). When evaluating the second expressjon, PASCAL compares 'r' and 'c' because these are the first characters that are not the same in the two strings. The ordinal value of 'r' (114) is greater than the ordinal value of 'c' (99). You can form relational expressions with character string variables as well as with constants. Given the declaration of Section of type Title, that is, PACKED ARRAY[1 •• 20] OF CHAR, the following statement includes a valid relational expression: IF Section = 'Character Strings WRITELN('That"s all folks! '); 5.2 ' THEN RECORDS A record is a structured type consisting of related data items of potentially different types. A record is organized into fields; each field can have a different type. An example of a record variable declaration is as follows: VAR Person : RECORD Name: PACKED ARRAY[1 •• 20] OF CHAR; Age: 0 •• 150; Sex : (Female, Male> END; 5-10 STRUCTURED TYPES: THE ARRAY AND THE RECORD The record variable Person has three fields: the field Name is a character string; the field Age is a subrange of integers; and the field Sex is an enumerated type consisting of the values Female and Male. To refer to one field, specify the record variable name and the name of the field, separated by a period (.). Each field can be treated as a variable of the field type, as shown in the following example: Person.Age refers to the field Age contained in the record Person. Person.Age can be assigned a value as if it were an integer variable. The record type definition format is as follows: RECORD field name (s) : type; IT fieldname (s) : type ... n END; As shown, you can specify the names of one or more fields. If there are multiple fields of a particular type, you must separate their names with commas. The type specifies the type of its corresponding field (or fields) and can be any valid PASCAL type. You cannot define more than one field with the same name within a given record. The reserved words RECORD and END enclose the fields in a record definition. Successive fields of different types must be separated by a semicolon(;). A semicolon is not required between RECORD and the first field name, or between the last field type and END. NOTE You do not need a BEGIN with the END a record definition. of Suppose you are shopping for a new home and you want to maintain information on the houses you see. The factors important in choosing a home might include cost, distance from place of work, number of rooms, method of heating, and location. The following TYPE section defines a record type named House: TYPE House = RECORD Cost, Distance : REAL; NUffi_Rooffis : 1 •• 20; Heat: (Gas, Oil, Electric, Solar, Coal); Location PACKED ARRAY(1 •• 20] OF CHAR; Suitable : BOOLEAN END; The record type House consists of six fields. Note that you can use a structured type as a field of a record (in the type House, the field Location is a structured type). To maintain information on a number of houses, you can declare an array of records. For example, if the constant Max Houses is defined as 10, you can declare an array of 10 House records ~s follows: VAR House_Choices ARF<AY[l •• Ma~·~_Houses] OF House; 5-11 STRUCTURED TYPES: THE ARRAY AND THE RECORD The variable House Choices stores multiple records in one array. To refer to one field of one record in this array, specify the variable name House Choices, an index enclosed in square brackets, a period, and the fi~ld variable. This is shown in the following example: H(JI..I~:;f::o .... Ch(Jices[ T J. H€·~at You use each field of a the field type is used. F 0 F~ I :::~ 1. record variable in the same way a variable Thus, the following are valid statements: of TOM i!l >: .... H01..1 ~:; p ':; DO BEGIN REA DI... N( H0 1..1 ~; e .... Ch 0 :i. c P ~:; I:: I ::I • CD::; t ) , r~ EADL.. N ( H[) IJ ~:; p .... C h 0 :i. C (,, .;; I:: I ::I < D :i. ~;; tan c (.:~ ) ; r,EADL.N (Hol..I<;;e .... Ch(J :i. cc~~:; I:: J::I < NUlYlr~oom~::.) ;; or F (H Cl U S f..~ .... Choi C:' e ~:; [ I J • C (] ~:; t <: lO 0 0 0 • 0) AND ( H0 U S f? ._ C hoi c e ~; [ I J • D i ~:; tan c f·~ <: 1. ::.:j • (» AN 1:1 ( H 0 U <;; P .... C hoi c (-:~ ~; [ :r ::I • N 1..111'1 .... F~ 0 0 ITI ~:; :> (.» THE N H 0 1..1 S P .... Ch () i c f~ !;; I:: J ::I • S 1..1 :i. t a ~J ], c-:.~ : :::: T F~ l.J E FALSE EL.SE HOl..Ise_ChoicesLIJ.Suitable := END; You can assign a record variable to another record variable of the same type. For example, the following VAR section declares two record variables of the same type: V'AR Nt'w_Hol.J~:;c,~ y Drc·~alTl .... Hol..I':;(·:·~ HO!..l':;e; If Dream House is defined (that is, if each field of Dream House has a value) , you can assign Dream__ Hollse to New House as follows: You can nest records in a record definition; that js, contain a field that is another record, for example: TYPE ElTlplo~ee a record can = RECORD NamE.' : PACKED Ar,r,AY [ 1 •• 20] OF CHAR; Adr:.l Y'(-:!~:;~:; : RECOHD HouseNo : INTEGER; St rpt't y Ci t~:1 : F'f~CI\ED Ar\F~AY I:: 1 •• 20J OF CHAr,; s tat f? : I:' A C I~; E D A F~ r, A Y [ :J. • • 2 J (] F C l'U':jf~ ; Zip: 0 •• 99999 END, (*end of Emplo~eeNo : INTEGER, Address record*) JobTitle : PACKED ARRAY[:J. •• l0::l OF CHAR; Sa 1. a T'~:I END, : F.:EAL (*end of ElTlplo~ee record*) EITIP 1 o~Jf.·~e; To refer to a field within the Address record, you must specify the identifier Employee N, a period, the identifier Address, a period, and the particular field identifier, as shown in the following example: This statement assigns the value of the string 'PA' of Employee_N.Address. 5-12 to the State field STRUCTURED TYPES: THE ARRAY AND THE RECORD You must read and write the information in records field by field when you are performing I/O operations on text files. PASCAL does not read or write an entire record, for example: This WRITELN procedure prints two Empl oyeeNo . fi.elds of Employee_N: Name and The WITH Statement When you refer to fields of the same record repeatedly, it is cumbersome to repeat the record name in each reference. The WITH statement allows you to specify the record name once, and refer to the fields directly in the subsequent statement. The format of the WITH statement is: WITH record variable [,record variable ••• ] DO statement; The record variable specifies the name of the record to which the statement refers. Within the statement, you can refer to a field of the record directly instead of using the record.fieldname format. For example, the FOR loop that used the record variable can be rewritten as follows: FOH I House Choices : :::: 1 TO Ma>: .... Hou!:;(·:·~!:; Do WIT H H 0 1..1 S (-;) .... C t I (] :i c (.:.) !:> I: I J BEGIN I:~ E A D I... N ( C 0 ~:; DO t ); READLN(Distance); F;:EADLN (NulTI ... F':oolTls) , IF (Cost < 70000.0) AND (Distance < 15.0) AND (NulTI_R(]olTls > 6) THEN Su:i tabl e : :::: TF.:UE ELSE Suitable := FALSE END; Each statement between the BEGIN and END delimiters uses the record name House_Choices(I]. Thus, the following statements are the same: READI...N(Cost), F.:EADLN (HOUSfL.Cho ices £: I J + Cos t) ; 5-13 STRUCTURED TYPES: THE ARRAY AND THE RECORD You can also use the WITH statement to refer directly to fields in nested records. You list the record names in the order in which they are nested, and after the reserved word WITH, for example: PACKED ARRAY[1 •• 20J OF CHAR; TYPE Nalll~:'~ Date F<ECOF<D M0 nth Da~:I : ("" an, F p b, MaT' c h, A F' Y' i :I. ~ Ma ~I' ..J U 1"1 (.:,' , Ju 1 ~~, Au~.:.!, ~;p~. . t, Oct, Nov, Dec); : Yc~ar 1 •• 3:1.; : INTEGEF~ ENIH VAf< Ho~:;p F,[COF<[I Pat i f2nt. : Name; BirthDate : Datf.'~ A!.~!e : I NTEGEI:;: END, WITH Hosp, BirthDate DO BEGIN Patient != 'Thomas Jefferson Month ! :~~ AI'" T' i 1 ; Day : :=: 1 :3 ; Y €.~ a r A~:H? , , A ::::: 1 743 ; ::::: 2:37 END; The record Hosp contains the field BirthDate, which is also a record (of type Date). The specification of Hosp in the WTTH statement allows you to refer to Patient and Age which are fields of Hosp. The specification of BirthDate allows you to access Month, Day, and Year, even though these fields are in a nested record. Thus, the WITH statement shown above is the same as the following: WI I TH Hosp DO WITH BirthDate Do BEGIN END; The record names in the WITH statement must be specified in the order in which they are nested. For instance, BirthDate is nested within the record Hosp in the declaration; therefore, Hosp must be specified before BirthDate in the WITH statement. 5-14 CHAPTER ~ PASCAL STATEMENTS The basic unit of a PASCAL program is the statement. A statement directs PASCAL to perform an action in a program. A statement consists of a systematic arrangement of reserved words, variables, operators, expressions, and other statements. This chapter describes the following types of statements: • Assignment statement • Compound statement • Repetitive statements • Conditional statements The assignment statement gives a value to a variable. The compound statement, delimited PASCAL statements together for statement. groups other END, by BEGIN and sequential execution as a sing Ie A repetitive statement causes a statement to be executed for a specified number of times or until a certain condition is reached. A conditional statement causes a statement to be executed if a certain value is true. Repetitive and conditional statements statements alter the sequence of specified conditions are met. In the PASCAL statements are executed in the the source program. are control statements. Control execution depending on whether absence of control statements, sequence in which they appear in As mentioned in Chapter 1, the semicolon (;) is a delimiter used to separate successive PASCAL statements. As such, it is not needed (although PASCAL does accept it) after a statement followed by a program element that is not a statement. For example, the use of a semicolon before the END delimiter is optional. In this manual, the semicolon is included as part of the statement format descriptions because it is usually necessary and is illegal in only one case. The exception occurs in the IF-THEN-ELSE statement as explained in Section 6.4.2. 6-1 PASCAL STATEMENTS 6.1 THE ASSIGNMENT STATEMENT The assignment statement assigns the value of an expression variable. The format of the assignment statement is: to a variable name := expression; The assignment statement replaces the current value of the variable with the value of the expression on the right-hand side of the assignment operator. The expression can be any expression having the same type as the variable, with a few exceptions: you can assign an expression of type INTEGER to a variable of type REAL or DOUBLE, and an expression of type REAL to a variable of type DOUBLE. You can also assign to a subrange variable a value of its base type. Note that this statement uses the assignment operator (:=), not the equal i ty ope r a to r ( =) • For example, if I is declared as an integer variable, statement assigns the value 100 to the variable I. the following I::::: 100; In addition to constant values, the right-hand side of the assignment statement can be any of the expressions described in Section 2.5. For example, suppose you have made the following declarations: C () N ~:; T Y e ~:; :~: I Y I ; No :::: I N I ; TYPE D(~~paT'tment (En~ineerin~, I... a n =j u a ~.~.~ s, Sciences, Math, English, F :i. f"I e .... Art s ) ; His tOT' ~~, VAR I, Increment: INTEGER; Answ(~~ T' : G T' a d f:') y Fa i 1. i n ~.:1 .. _G T' a d p M~~ .. _Ma ,jo T' Passed : CHAf~; : : REA L. ; D€:' f"a rtlTl(·:~nt ; BOOLEAN; Then, the following assignment statements are valid: I :~~: 1; Failing_Grade := 1.0; Grade := (4+5+2-1)/3; := I + 1; := Grade> Failing_Grade; AnsweT' ::::: Yes; M~_MaJor := Fine_Arts; Increment Passpd Note that, in the statement Answer .= Yes, the expression to be assigned to Answer is a symbolic constant. The value of the symbolic constant Yes is a single character and therefore can be assigned to the CHAR variable Answer. In each of the assignment statements shown above, the type of the expression is the same as that of its corresponding variable. 0-2 PASCAL STATEMENTS 6.2 THE COMPOUND STATEMENT You can use the BEGIN and END delimiters to group one or more statements into a compound statement. The statements are executed in sequential order. The format of the compound statement is: BEGIN s ta temen tl [; staternent2 ••• :0 END; [ n The statements within the BEGIN and END delimiters can be any PASCAL statements, including other compound statements. Each successive statement must be followed with a semicolon; however, the use of the semicolon between the last statement and the END delimiter is optional. PASCAL treats the compound statement as if it were a single statement. For example, the following contains a compound statement that is part of an IF-THEN statement: IF Measure = '~' THEN BEGIN WRITELN ('Enter the number of READLN (Ga lIon!:; ) ; ~allons.'); END [L~;E BEGIN WRITELN ('Enter the number of liters.'); READLN (Liters); Gallons := Liters / 3.785; <*converts liters to gallons*> END; If the Boolean expression (Measure = 'g') is true, every statement within the first BEGIN and END is executed. If the expression is false, flow of control transfers to the statement following the END and beginning with the ELSE. single This manual uses the term "statement" to mean either a statement or a compound statement. More examples of compound statements appear throughout this chapter. 6.3 REPETITIVE STATEMENTS specified Repetitive statements cause a statement to be executed a reached. The is number of times or until a certain condition repetitive statements are: • FOR • REPEAT • WHILE The FOR statement executes a statement a specified number of times. The REPEAT statement executes a statement and then evaluates a BOOLEAN expression after executing the statement. The statement continues to be executed until the BOOLEAN expression is true. The WHILE statement evaluates a BOOLE~N expression at the beginning of a st.atement. As long as the expression is true at the beginning of the loop, the statement is executed. Each of these statements is described in the following sections. 6-3 PASCAL STATEMENTS • Because the reserved words REPEAT and UNTIL enclose the statements to be executed, you do not need a compound statement to set off multiple statements. The statements can be delimited with BEGIN and END, but do not have to be. In addition, you need not use a semicolon immediately preceding UNTIL. The example below shows the use of a REPEAT loop to search for a value in a sorted array. This is an example of a binary search, one of the classic search algorithms. Assume that the program includes the following declarations: en N r:; T ~:; i ~.~ (.:.~ :;;: 20; TYPE Name ~ (* d i ITI f..' n <:> ion 0 faY' r' a ~:I *) PACKED ARRAY[1 •• 20J OF CHAR; VAR Name_List: ARRAY[l •• SizeJ OF Name; Name_ta_Find Name; I, J, Middle INTEGER, Found: BOOLEAN; Assume also that the array ~ame List contains an alphabetized list of names. The following program fragment prompts for a name, then searches the array for that name. BEGIN (* Input the name *) WRI1E ('Name to find READLN <Name_ta_Find); '); (* Initialize variables before I : :::: :l; ,..I ::::: ~:; :i. ~.~ e ; Faunc! executin~ loop *) ::= FALSE; 1;~EPFf:~T (* If Name_to_Find is in Name_List, it falls between the elements Name_List Ell and Name_List [ J ] *) Middle ::::: (ItJ) DIV 2; IF (Name_to_Find :::: Name_List [Middle]) THEN BEGIN (* Set Found fla~ and print a message *) Found :::;; TF<UE; WRITELN (Name_to_Find,' is element',Middle:3) END ELSE IF (Name_to_Find > Name_List [Middle]) THEN increase lower array bound to select top half I != Middle t 1 ELSE IF (Name_to_Find < Name_List [Middle]) THEN decrease upper array bound to select lower half J !:::: Middle ._. 1 UNTIL Found OR (1 > J); (* *) (* IF NOT Found THEN WRITELN (Name_to_Find,' is not in the list.'); END. 6-fi *) PASCAL STATEMENTS The REPEAT loop contains statements that partition the array and search the appropriate half. The vari~bles I and J initially represent the upper and lower bounds of the entire array Name_List, and are changed during execution to represent the bounds of the part of the array currently being searched. Execution of the loop terminates when Name to Find is found (in which case the variable Found is true) or when- tEe value of I exceeds the value of J, indicating that Name to Find is not in the array. For example, if Size is 20, the loop first compares Name to Find with Name List[lO]. If their values match, Found becomes TRUE; a message is printed; and the loop terminates .. I f Narne to Fin d i~; g rea t e r" t han Narne Lis t [ I 0], t hat is, i fit faI Is I ate r i nthe a J. ph abe t, the n I t a kE; son the val u e 11. Th e sea r chi s confined to the second half of the array, and the loop is repeated for elements Name_List[ll] through Name_List[20] . If Name to Find is ll~ss than Name List[IO], that is, if it falls earlier in the alphabet, then J ~akes on the value 9. The search is confined to the first half of the array, and the loop is repeated for elements Name_List[l] through Name_List[9] . On the second iteration, the value of Name to Find is compared with the middle element in the selected half- of the array, either Name List[15] or Name List[5]. If the names do not match, the array is 7urther partitio~ed. The search continues until Name to Find matches an element of Name List. If the name is not in the array, eventually the value of I exceeds the value of J, causing execution of the loop to terminate. Example 2 Assume that Count, Sum, Number, and integer variables. SUITt ::::: 0; Count ::::: 0; REPEAT READ (NulTtber); SUITt := Sum + Number; Count := Count + 1 UNTIL EOLN(INPUT) OR (Count Avera~e := SUITt DIV Count; Average have been declared as 10); This example reads and sums a list of I to 10 integers on a line and averages them. The integers must be entered on one line, and a <RET> must be entered after the last integer. The REPEAT loop reads in one integer, adds it to the sum, and increases Count by 1. The REPEAT loop terminates when EOLN (INPUT) is true, or when Count equals 10. EOLN (INPUT) becomes true as a result of the <RET> typed after the last integer entered. 6-7 PASCAL STATEMENTS Example 3 Suppose that the following declarations have been made in a declaration section: T YPEN a mf?~) t r i n <.'1 ~:: PAC K E II AH F~ A Y[ :L • • 20 :1 VAR Name : Namestrin~; Namelist : ARRAY[1 •• 30] of Namecount : INTEGER; program's 0 F C H Af~ ; Namestrin~; The REPEAT loop below uses these variables: Namf.~cC)unt ::::: 0; F~EPEAT (NalTle); Namecount := Namecount + 1; Namelist[NamecountJ != Name LINT I L. EOF OR (Namecount ::~ 30); F~EADLN This ex~mple reads character strings representing names and stores them in the array Namelist, which contains components of a packed array of characters. Namelist can contain up to 30 names. The REPEAT loop increases Namecount by 1, then reads one name and assigns it to one element of Namelist (that is, Namelist[Namecount]). The loop terminates when Namecount equals 30 or when EOF becomes true. Because the READLN statement reads one name and then skips to a new line, each name in the input file must be typed on a different line. 6.3.3 The WHILE Statement The WHILE statement is like the REPEAT statement in that it the repetitive execution of a statement. specifies The format is: WHILE Boolean expression DO statement; The loop is executed while the Boolean expression is true. expression becomes false, execution terminates. When the There are three important differences between the WHILE statement the REPEAT statement. and 1. WHILE tests the expression before executing the statement(s) in the loop; REPEAT tests the expression after executing the statement(s). Therefore, if the Boolean expression is false when WHILE is first encountered, the statement following DO is not executed. 2. WHILE controls the execution of only one statement. Hence, to execute a group of statements repeatedly, you must use a compound statement. REPEAT does not require a compound statement; BEGIN and END are optional. 3. WHILE terminates execution becomes false. REPEAT condition becomes true. 6-8 of the loop when a terminates execution cond i tion when the PASCAL STATEMENTS Example 1 in the preceding section can statement to produce the same results: ~:; U ITI : ::~ be rewritten using a WHILE 0; Count ! :::: 0; I.t.IHILE NOT EOLN(INPUT) AND (Count·( to) DO BEDIN I:~EAD (Nunlbp T') ; SUITt : ::" Count END, ~)um + Numb,(:~ Y' ; := Count + 1 Avera~e t= SUIll DIV Count; 8UIlt :::~ 0; Count : :::: (); I:~EF'EAT READ (Numbe T' ) ; SUIll := Sum + Number; Count := Count + 1 UNTIL EOLN(INF'UT) OR (Count AVEF~AGE : :::: SUITI DJ V Count; :LO), The differences between the two examples lie in the specification of the conditions for terminating the loop. The WHILE loop is different in these ways: • The test for EOLN(INPUT) must be written as NOT EOLN(INPUT) so that the loop is repeated as long as EOLN(INPUT) is false. • The condition determining that only 10 integers can be averaged must be rewritten as Count < 10 (instead of Count = 10). On the last iteration, the tenth integer is read, and Count becomes 10. Count < 10 is then FALSE, so the loop is not executed again. • The logical expression uses the operator AND instead of OR. The statements are executed as long as both conditions are true. Example 2 WHILE NOT Errorflag AND (Intcount < :LOO) DO BEGIN READ (Int); IF Int > 0 THEN Poscount := Poscount + 1 ELSE IF Int < 0 THEN Ne~count := Negcount + 1 ELSE Errorflas := TRUE, Intcount := Intcount + 1 END; This WHILE loop reads an integer; and, if the integer is positive, the variable Poscount is incremented. If the integer is negative, the variable Negcount is incremented. Up to 100 integers can be counted; the number of integers counted is accumulated in Intcount. If a zero is encountered in INPUT, Errorflag becomes TRUE; and the loop is terminated. 6-9 PASCAL STATEMENTS Suppose that, in the program surrounding the above program fragment, there is more than one way to obtain an error and thus assign the value TRUE to Errorflag. If Errorflag is true before the program encounters the WHILE statement, the statements within the loop are not executed. Similarily, if Intcount is greater than or equal to 100, the loop is not executed. 6.4 CONDITIONAL STATEMENTS Conditional statements control the flow of the the evaluation of an expression. Unlike the the conditional statements direct only the flow not directly control the number of times statements are executed. program depending on repetitive statements, of execution; they do that a statement or The conditional statements in PASCAL are: 6.4.1 • IF-THEN • IF-THEN-ELSE • CASE The IF-THEN Statement The IF-THEN statement executes a statement or statements expression is true. The format is: only if an IF Boolean expression THEN statement; If the expression is true, then the statement is executed. If the expression is false, program control passes to the statement following the IF-THEN statement. The reserved word THEN and the statement that directly follows it are called the THEN clause of the IF-THEN statement. The statement following THEN is called the object of the THEN clause, for example: IF A <: 0 THEN N(~!~L I n t s ::= Ne ~.L. I n t 5 + 1; The object of the THEN clause is If the value of A is less than zero, the value of Neg_Ints is increased by one. Note that you must not place a semicolon after the reserved word THEN. If you do, an empty statement becomes the object of the THEN clause. In the example above, if there had been a semicolon after THEN, the assignment statement would be executed regardless of the value of the Boolean expression. 6-10 PASCAL STATEMENTS Example 1 IF (Ans BEGIN Yes) THEN END; The object of the THEN clause can be a compound statement. The statements between BEGIN and END are executed if the Boolean expression is true. If it is not, execution continues with the statement following the END. Example 2 IF (Ch )= 'A') AND (Ch <= 'I') THEN BEGIN Letter := TRUE; LetterTotal := LetterTotal + 1 END; If both relational expressions are true, executed. the compound statement is Example 3 IF ErrorflaS THEN WRITELN ('Index number out of bounds'); The Boolean expression can be a single Boolean variable, as in this example. The WRITELN statement writes the message in apostrophes if the current value of Errorflag is TRUE. 6.4.2 The IF-THEN-ELSE Statement The IF-THEN-ELSE statement executes one statement if the expression is true, and another statement if the expression is false. The format of the IF-THEN-ELSE statement is: IF Boolean expression THEN statementl ELSE statement2; Statement1 and statement2 can be any PASCAL statements. Statement1 is executed only if the expression is true. If the expression is false, then statement2 is executed. The reserved word ELSE and statement2 are called the ELSE clause of the IF-THEN-ELSE statement. NOTE You must not place a semicolon after statement1 and before the word ELSE. The IF-THEN-ELSE statement is a single statement; the IF-THEN clause cannot be separated from the ELSE clause. Because ELSE does not denote an independent statement, you receive a compile-time error message if there is a semicolon directly before the word ELSE. 6-11 PASCAL STATEMENTS The ELSE clause is always statement, for example: associated with the closest IF-THEN IF A : -.: 1 THEN IF B <> 1 THEN C := 1 ELSE D :;::; 1, The ELSE clause is associated with the second IF-THEN statement. Therefore, if A and B are both equal to 1, 1 is assigned to the variable D. If A is not equal to 1, neither assignment statement is executed. If you want the ELSE clause to be associated with the first IF-THEN, you can write the sequence as follows: ~-.: 1 THEN BEGIN IF B <> 1 THEN C := 1 END [F A ELSE II :;~" 1, The object of the THEN clause consists of: of the outer IF-THEN-ELSE statement BEGIN IF B <> 1 THEN C := 1 END And the ELSE clause is: ELSE D:=1; Thus, if A is equal to 1, the THEN clause is executed, and the ELSE clause is ignored. If A is not equal to 1, 1 is assigned to D regardless of the value of B. Example 1 IF (LastInitial >= 'A') AND (LastInitial .. Billdate := 14 ELSE Billdate := 28, <= 'M') THEN This example determines billing dates depending on the initial of a last name. Bills are sent on the 14th of the month to each customer whose last name starts with A through M, and on the 28th to customers whose last name starts with N through Z. Example 2 IF (Card_Sum> 21) THEN Lose := TRUE ELSE IF (Card_Sum >=17) THEN Deal := FALSE ELSE BEGIN Deal := TRUE; Card_Sum := CardSum + Newcard END; 6-12 PASCAL STATEMENTS This example shows a simple strategy for the game Blackjack. Note the nested IF-THEN-ELSE statements that allow the program to select and execute one of a group of statements. In this example, if the cards add up to more than 21, the player loses. If the sum is between 17 and 21, inclusive, the player is not dealt any more cards. If the sum is less than 17, the player is dealt another card. The IF-THEN-ELSE construct can become awkward if there are more than a few selections to be made. A more elegant way to program this type of problem uses PASCAL's conditional CASE statement, which is explained in the following section. 6.4.3 The CASE Statement The CASE statement selects one of a group of statements for execution. Constant values or case labels are associated in a CASE statement with each possible statement or action to be performed. The format of the CASE statement is: CASE case selector OF case-label l i s t : statement [case-label l i s t : statement ... ;TI [OTHERWISE clause TI END; The case selector can be any expression (not only a variable) that evaluates to an ordinal type. The case-label list can consist of one or more values of the same type as the selector, separated by commas. Each label list is associated with the statement to its right. The label list and statement must be separated by a colon (:). You can include an optional OTHERWISE clause that contains a statement that is not associated with a label. CASE executes the statement labelled specified expression, for example: CASE Correct_Answers OF ... .... 9 , l O S C () Y' e ++ _. 8 Score + .-•.... 7 ScoT'e +6 Score ++ .". 0,1,2,3,4,5 SCOT'e +- .- by a value that equals a , I AI ; I BI CI ; I D I ; I F I I END; This CASE statement compares the value of the expression Correct Answers to the case labels (the numbers 0 through 10). If the value 07 Correct Answers is any of the numbers from a to la, the assignment statement to the right of that number is executed. NOTE No BEGIN is allowed with the CASE statement. END to a You can specify the labels in any order. The difference in the ordinal values of the largest and smallest labels must not exceed 1000. Each label can appear only once within a CASE statement. 6-13 PAS~AL STATEMENTS At run time, if the selector equals one of the specified labels, the statement to the right of that label is executed. If an OTHERWISE clause is included and the selector does not equal one of the labels, the statement next to OTHERWISE is executed. Setting the CHECK compile option controls whether an error occurs if there is no OTHERWISE clause and none of the case labels are selected. If the option is set, an error occurs at run time. If the option is not set, the statement following the CASF statement is executed. For more information about compile options, refer to the TOPS-20 PASCAL Language Manual. Exampl e 1 Suppose you have made the following declarations: VAR Month ~3 e a son Temp nnot-.,I: (Jan, Feb, Mar, Apr, May, June, Jul',:l, Au~.l, t)(-")F't" Oct, Nov, Dec); ( Win t e T', SF' r i. n ~1, S U fTIIM? T', F a 11 ) ; INTEGER, BOOLEAN; You can use the following CASE statement: CASE Month OF Jan, Ff"'b, Ma r' BEGIN Season := Winter; IF (Temp <= 30) THEN Snow ::::: T'~UE END; Apr, May, June : Season := Sprin~; July, Aug, Sept : Season := Summer; Oct, Nov, Dec: Season := Fall END; At run time, the current value of Month is evaluated. The statement associated with that value is executed; the rest of the statements are iqnored. For example, if Month equals May, then Spring is assigned to the variable Season. Exampl e 2 This example represents the relationship of combinations of genes to the occurrence of dominant versus recessive traits. Assume that Gene Combo and Trait are variables of enumerated types declared as follo,vs: VAR Gene_Combo : (Recessive_Recessive, Recessive_Dominant, Trait: Dominant_Recessive, Dominant_Dominant); (Recessive, Dominant); These variables are used in the following CASE statement: CASE Gene_Combo OF Recessive_Recessive : Trait := Recessive; OTHERWISE Trait:= Dominant lEND; If the value of Gene Combo is Recessive Recessive, the value Recessive is assigned to Trait~ If Gene Combo evaluates to any other value, the OTHERWISE clause is executed: -that is, Dominant is assigned to Trait. 6-14 CHAPTEE 7 PROCEDURES AND FUNCTIONS The statements described in the previous chapters provide the basic building blocks for writing PASCAL programs. This chapter describes the use of subprograms and the passing of data to and from subprograms. 7.1 SUBPROGRAMS A subprogram consists of several statements grouped together to perform a single part of a larger task. Subprograms are useful for solving large problems; you can divide the problem into many pieces and solve each piece individually. For example, if you are writing a program to maintain student records, the program will be easier to write if it is broken into subprograms. The larger task of maintaining records could be broken down into such segments as adding students, deleting students, listing available co u r s e s, and en tel" in g g r a des. Subprograms are also useful when the same code segment is used more than once within the program. Using a call to a subprogram is simpler and clearer than duplicating the same code segment several times within the main body of the program. To handle these subprog rams: • Procedures • Functions. types of problems, PASCAL uses two types of Both procedures and functions are declared in the declaration section (see Sections 7.2 and 7.3) and are called from the executable section. A procedure is a qroup of statements that perform a set of actions. A function is similar to a procedure in that: it is a set of statements associated with an identifier; and it is declared in the declaration section. However, a function has a type, and it returns a value of that type. Procedures and functions have similar structures and restrictions. This manual uses the term "subprogram" in descriptions that apply to both procedures and functions. You can use predeclared subprograms that are defined by PASCAL and denoted by predeclared variables; or you can create user-declared subprograms, as described in this chapter. Appendix C contains tables of all the predeclared procedures and functions in PASCAL. 7-1 PROCEDURES AND FUNCTIONS 7.1.1 Format of a Subprogram Subprograms are similar in format to main programs. A subprogram consists of a heading and a block; the block contains a declaration section and an executable section. The heading of a subprogram is slightly different from that of a program, because the subprogram heading can contain a formal parameter list. See Section 7.4.1 for a description of formal parameters. For a function, the heading also indicates the type of the value returned. The declaration section defines local data items that are used in the subprogram. The executable section contains the statements that perform the actions of the subprogram. All subprograms must be declared in the declaration section of the main program or of another subprogram. A subprogram is not executed when it is declared. It is executed as a result of a subprogram call, which can appear in the main program or in another subprogram. Subprograms are said to be nested within the main program. In addition, subprograms can be nested within other subprograms. A nested subprogram can be called only from inside the block that declares it. The general format of a subprogram heading includes one of the reserved words FUNCTION or PROCEDURE, followed by the subprogram identifier. An optional parameter list can be included. Functions must also include a result type as part of the heading. The use of variables is described in Section 7.1.2. Sections 7.2 and 7.3 explain the use of procedures and functions. Section 7.4 provides information about the use of parameters. 7.1.2 Local and Global Variables Local variables are variables that you define within the subprogram. PASCAL uses local variables only in the subprogram where they are defined. Global variables are those that are declared in the declaration section for the main block of the program. Although the global variable is declared outside a subprogram, it can be accessed by the subprogram. Thus, variables declared in the main program block are global to all subprograms. A variable declared in a subprogram is global to all its nested subprograms. In addition, predeclared variables are global to all parts of a PASCAL program. Global variables allow you to implicitly pass variables to and from a subprogram to the main body of the program. Global variables should be used with care in subprograms. When global variables are used, values are not explicitly passed to and from the subprogram. Therefore, debugging and modifying a program is more difficult than if values are explicitly passed. To avoid the problem of accidentally changing values in subprograms, it is suggested that parameters be used to explicitly pass values to and from subprograms. Parameters are described in Section 7.4. 7-2 PROCEDURES AND FUNCTIONS 7.1.3 Scope of Identifiers in Subprograms The scope of an identifier is the part of the program in which you have access to the identifier, that is, the block in which it is declared. Thus, the scope of a variable declared in the main program block is the full program. The scope of a variable declared in a subprogram block is that subprogram and all subprograms nested within it. In a subprogram, you can redeclare an identifier that has been declared in an outer block. When you use an identifier in a subprogram that is declared both in that subprogram and in an outer block, the identifier always refers to the declaration of most limited scope. The scope of a global variable does not include any block in which it is redeclared. Thus, the local variable can have attributes distinct from those of the global variable (for instance, type or value). You should use great care if you redeclare an identifier in a subprogram. It could easily be confusing if the program needs to be debugged or modified at a later point. Redeclaring an identifier within a subprogram should be avoided if possible. 7.2 DECLARING A PROCEDURE Procedures are declared in the declaration section of a program. To declare a procedure, you specify its heading and block. You can declare a procedure in the main program or in another subprogram. The format of a procedure declaration is: PROCEDURE procedure name r [formal parameters)] declaration section BEGIN statement [;statement ... ] END; The reserved word PROCEDURE is required. The procedure name specifies the identifier to be used as the name of the procedure. The formal parameters describe the parameters used in the procedure (see Section 7 .4) • The declaration section can contain local declarations and definitions. The statements between BEGIN and END can be any PASCAL statements. The block in the procedure is identical to the block in the main program, with the exception that the procedure block ends with a semicolon (;) rather than a period (.). You should not redeclare the formal-parameter names or the procedure name as local variables in the procedure. 7.2.1 Calling a Procedure A procedure is executed as a result of a procedure call. A procedure call consists of the procedure name and, when required, an actual parameter list. If the procedure declaration contains a formal parameter list, the procedure call must contain a corresponding actual parameter list. 7-3 PROCEDURES AND FUNCTIONS The following example shows a program that passes values to and from a procE~dure. F' f< 0 GHAM ---------_.----- ._----- (* t his F' T' 0 9 T' a m 0 Y' d f'~ T' !:; p a :i r!:; of numbers in ascending orciPY' *) S wa p (I Nf' UT y () UTf' UT ) ; VAR X, Y : INTEGER, PRDCEDl.mC Sw itch (VA~~ A, B :r NTEGEF<) , (* Switch swaps values C) f vaT' i a b 1 <-:.~~; *) VAR Temp: INTEGER, BEGIN Temp ::;:: B, B ::::: {'d A ::;:; Temp; END, BEGIN WRITELN ('This program will order a list of numbers for ~JF< I TELN (' WhE'n ~()u a re don(~~, t~lF'P <CTRI...:> Z.'); WRITEI...N ('Enter two nUlTlbers of an~ size.'), t,IHIL..E NOT ~ou.'); FDF DO BEGIN READL..N (X, Y), IF X > Y THEN Switch (X,Y); WI=<ITEL.N (' END, " X, Y), (* here is the procedure call *) IF EDF THEN WRITELN ('END OF LIST'), END. -------------------------- The procedure Switch is defined in the declaration section at the beginning of the program. The call to the procedure is in the main block of the program: IF X :> Y THEN Switch (X,Y); If the expression (X ) Y) returns a value of TRUE, the procedure Switch is called and executed. The actual parameter list names the variables (X and Y) that are passed to the subprogram. The formal parameter list in the procedure heading names the variables (A and B) to which the values from the main block are assigned. 7.2.2 Procedure Example The following example shows the program Simple Procedure. This program includes a procedure to perform a simple output operation. Execution begins in the main body of the program with the WRITELN statement. Execution continues to the evaluation of the IF-THEN statement. If the statement is true, that is, if Answer equals yes, then the procedure Read Fortune is called. The procedure is called by using the procedure name as a statement. 7-4 PROCEDURES AND FUNCTIONS When the procedure Read Fortune is called, the statements in the procedure are executed. BeCAuse no values are being passed to or from the procedure, it is not necessary to specify any parameters when the procedure is called or in the procedure definition. After the statements in the procedure have executed, the flow of the program returns to the statement following the call to the procedure. In this example the final WRITELN statement is executed following the procedure execution. PROGRAM Simple_Procedure (INPUT, OUTPUT); (* defines data tspe with values TYPE se~; and no *) (* defines one variable of user-defined tspe Yes_No and assi~ns value Yes *) VAF~ (* this procedure executes the WRITELN statements, when this procedure is called *) PROCEDURE Read_Fortune; BEGIN WRITELN ('You will be healths, wealths, and wise'); END; (* main bod~ of the proSram *) BEGIN WRITELN ('Would sou like to see ~our fortune?'); WRITELN ('Please answer ses or no.'); ~(EADLN (Answe T') ; IF Answer = Yes THEN Read_Fortune ELSE WRITELN ('If ~ou had t~ped ·~esn sou would have seen', '~our fortune.'); WRITELN ('This is the end of the prosram.') END. 7.3 DECLARING A FUNCTION A function is a group of statements that is associated with a name and that returns a value. PASCAL includes in the language such functions as SQR, SQRT, SIN, COS, and ARCTAN. In addition, in PASCAL you can define functions within your programs. Functions are similar in format to procedures. However, a function is associated with a type, and returns a value of that type. The type of the value returned is specified in the function heading. To declare a function, specify its heading and block in the procedure and function part of a declaration section. The format of a function declaration is identical to that of a procedure, except that the function heading begins with the reserved word FUNCTION instead of PROCEDURE, and the heading includes a result type. The format is: FUNCTION function name [(formal parameters)D declaration section BEGIN statement [;statement ••• D END; 7-5 : result type; PROCEDURES AND FUNCTIONS The function name is the identifier used as the name of the function. The formal parameter list must conform to the format described in Section 7.4. The result type must be a scalar or pointer type. The block of a function is the same as the block of a procedure. functions and procedures are terminated with a semicolon (;). Both Every function must include one or more statements that assign a value of the result type to the function nam~. In the function Divides ( Sec t ion 7. 3 . 2), i f the Boo 1 e a n ex pre s s ion - - ( D i v ide n d REM Di vis 0 r 0) is true, TRUE is assigned to the function name. Otherwise, FALSE is assigned to the function name. If a value is not assigned to the function name during execution of the function, the function result is undefined. 7.3.1 Calling a Function A function is executed as a result of a function call. A function call is an expression in which the function and the formal parameters are included. Because the function call is an expression, it can be used anywhere other expressions can be used. For example, a function reference can appear on the right-hand side of an assignment statement. Unlike a procedure call, a function reference is not a statement in itself. However, actual parameters in a function reference are used in exactly the same manner as in procedure calls; they are passed to the fun c t ion. 7.3.2 Function Example The following is a valid function declaration: FUNCTION Divides (Dividend, Divisor : INTEGER) BEGIN IF (Dividend REM Divisor = 0) THEN Divides ::::: TRUE ELSE Divides := FALSE END; BOOLEAN; Divides is a Boolean function that returns a Boolean value. If Divisor is a factor of Dividend (that is, it can be divided into Dividend with a zero remainder), the function Divides returns a value of TRUE. Otherwise, the function Divides returns a value of FALSE. 7.4 PARAMETERS You pass data (that is, values and/or identifiers) to a subprogram by means of parameters. Parameters can be either value parameters or variable parameters. Value parameters are those in which the value is passed only to the subprogram; another value is not passed back from the subprogram. Variable parameters are those in which the value is passed to the subprogram and a changed value is passed back to the block from which the subprogram is called. 7-6 - PROCEDURES AND FUNCTIONS Formal parameters and actual parameters are terms used to describe the assignment process of the variables. Formal parameters are those listed in the subprogram declaration. Actual parameters are those specified in the subprogram call. In the body of the subprogram, the formal parameters represent the actual parameters. 7.4.1 Actual and Formal Parameters A subprogram's formal parameters assume the values of the actual parameters when the subprogram is called. Formal parameters are listed in the heading of the subprogram. The formal parameters describe the parameters used within the subprogram and their types. The formal parameter list is the declaration for the parameters; they are not declared elsewhere. For example, the heading for the procedure Switcp is shown below: F'1:~()CF[ll.mE nW:L tch (VAf.: A, B : INTFGER)~ In the procedure, A and B are formal parameters, and they are both the type INTEGER. of The format of the formal variable parameters is: or parameter ( [VAR] identifier l i s t : type list for specifying value [; [VAR] identifier l i s t : type ... ] ) The reserved word VAR is used to define variable parameters. Variable parameters return a changed value to the main body of the program. The identifier list specifies one or more variables that denote formal parameters. The type specifies the type of the parameters in the preceding identifier list. The formal parameter list determines the nature of the actual parameter list. In the actual parameter list, you must include exactly one actual parameter for each formal parameter specified in the subprogram heading. All variables used in the actual parameter list must be declared or defined in the block surrounding the subprogram call. For example, the following parameter list: is a procedure heading with a formal This is a valid procedure call to the procedure Change: The actual parameter Number is associated with the formal parameter New Number and the actual parameter Letter is associated with the formal parameter New_Letter. Thus, each actual parameter corresponds to a formal parameter. This correspondence is established solely on the basis of position in the respective parameter lists. The type of an actual parameter must be the same as that of its corresponding formal parameter. You can call a subprogram several times with different actual parameters. For example, the same program that contains the procedure call to Change shown above can contain the following, if Old Letter and Old Number have been defined in the VAR section: 7-7 PROCEDURES ~ND FUNC~IONS As a result of this procedure call, when Change is called, the formal parameters New Number and New Letter assume the values of the actual parameters Old Number and Old Letter, respectively. See Section 7.4.3 for the program containing the procedure ChAnge. 7.4.2 Value and Variable Parameters You can specify two kinds of parameters in the formal parameter list of a subprogram: value parAmeters and variAble parameters. The kinrl of parameter specified in the subprogram heading determines how the parameter is passed to the subprogram. Value parameters pass the value of the actual parAmeter to the subprogram. The subprogrAm cannot change the actual parameter's value during execution. Variable parameters pass the address of the actual parameter variable to the subprogram, thus the subprogram can change the actual parameter's value. PASCAL passes value parameters to subprograms by default. When you use the VAR specifier, the memory address of the actual parameter is passed to the subprogram. Therefore, the formal parameter and the actual parameter with which it is associated represent the same variable. When the subprogram changes the value of the formal parameter, it really changes the value of the actual parameter. The following example shows the use parameters with a function: PROGRAM Dra~on of a program that uses value (INPUT,OUTPUT); lJAF~ Gold, Silver, Copper: INTEGER; (* The function Wealth calculates the wealth of the player, based on the ~old, silver, and copper the player has. *) INTEGEF..: ) F..:EAL; VAR Total._Weal th (* One ~old coin is worth $25, one silver coin is worth $2.50, and one copper coin is worth $.25 *) BEGIN END; * Total_Wealth := Gold_Coins 25.0; Total_Wealth != «Silver_Coins * 2.5) t Total_Wealth); Total_Wealth := «Copper_Coins * 0.25) t Total_Wealth); Wealth != Total_Wealth; (* Main pro~ram *) BEGIN WRITELN (~How many coins does your player have?'); WRITE ('Gold:'); READL.N (Gold); WRITE (~Silver:~); READLN (Silver); WRITE (~Copper:'); READL.N (Copper); WRITELN ('Total wealth is: $~,Wealth(Gold,Silver,Copper):8:2); END. 7-8 . PROCEDURES AND FUNCTIONS In the main block of this program, values are entered at the terminal. These values are assigned with the READLN statement to the variables Gold, Silver, and Copper. These values are passed to the function Wealth with the call: WRITELN ('Tolal wealth $ , ; Wealth (Gold, Silver¥ Copper):8:2); This statement calls the function Wealth, using Gold, Silver, and Copper as value parameters. The function Wealth calculates the Total Wealth, and then assigns that value to the function name. Contr~l is returned to the main block, and the WRITELN statement is executed, using the newly calculated value of Wealth. as value Because the values of Gold, Silver, and Copper are passed They are not changed by parameters, the values remain the same. execution of the Wealth subprogram. The following execution: is the output of the program Dragon, from compilation to @F'ASCAL PASCAL)dragon.pas PASCAL>/e~<i t (~]. Dad LINK: d ra30n • re 1 Loading EXIT @save dragon. ~~~·~e DRAGON.EXE.2 Saved @T'un dragon How man~ coins does ~our pla~er have? Gold:25 S i 1 ve T' : ~jb C(JPF'f.~ r : 7 Total wealth is: $ 76b.75 @ The program Swap, shown at the beginning of the chapter, shows the use of variable parameters in a procedure. PROCEDURE Switch (VAR A, B : INTEGER); VAR Temp: INTEGER; BEGIN Temp ::::: B; B ::::: A; A ::::: Temp; END; When the procedure Switch is called, the values of X and Yare assigned to A and B respectively. The procedure switches the values of A and B; and, since they are variable parameters, these changes in value also apply to the actual parameters X and Y. 7-9 PROCEDURES AND FUNCTIONS Combining Value and Variable Parameters The following example shows parameters in a function: FUNCTION S~ffiffietr~ the use of both value and variable (VAR S~mArr : SQuareArr; SidE.' ! I NTEGEfO : BOOLEAN; VAR I¥J : INTEGER; BEGIN SYmlT!(,?tr~ ::::: TF~LJE; FOR I := 1 TO Side DO FOR J := I TO Side DO IF A[I,JJ <> AC,J,IJ THEN S~mmetr~ := FALSE END; array is two-dimensional The function Symmetry returns TRUE if a the type symmetric and FALSE if it is not symme tr ic . Suppose Square__ Arr is defined as follows: TYPE SQuare_Arr = ARRAY[1 •• 10,1 •• 10J OF INTEGER; That is, it is a IOO-element array of" integers. The parameter Side is of type INTEGER and holds the length of the sides of the current array being tested. The function heading specifies that an actual parameter of type Square Arr will be passed as a variable parameter. However, the actual--parameter of type INTEGER that is passed to Side is a value parameter. You can reference the function Symmetry as follows: IF SYmmetrY (This_Arr, This_Side) THEN WRITELN ('The array is Symmetric'); Say that This Arr is of type Square Arr, and This Side is of type INTEGER. This Arr will be passed as a variable parameter, and This Side will Ee passed as a value parameter. 7-10 PROCEDURES AND FUNCTIONS 7.4.3 Examples In the following examples, the program Pass demonstrates the use of these terms. The procedure Change is used to show the use of local variables, global variables, value parameters, and variable parameters. PI~OGI;:AM P as~:; (I NPUT y OUTPUT) , Number : INTEGER; : CHAF~; L :i. ITt i t : F~ E() L ; L(·:~ttpr PROCEDURE Change (New_Number CHAFO, VAF~ <* statempnts for the procedure Change*) BEGIN FOR I := 1 TO 3 DO BEGIN WRITELN ('Enter a new value for Number:'); READLN (New_Number), WRITELN ('Enter a new value for Letter:'); READLN (New_Letter); WRITELN ('Entpr a new value for Limit:'); ~\: EADL. N (L i ITt it) ; END END, (* main BEGIN Nt.JlTtb(·~r Lf.·~tt(~T' . • • _. ._. :;::: bod~ of the program *) r.;- ... ,.}, 'A'j Limit ::::: 12.:::j; WRITELN ('The value of Number is:'yNumber:3), WRITELN ('The value of Letter is:',Letter:2); WRITELN ('The value of Limit is:', L..imit:4:2), Change (Number, Letter); WRITELN ('The new value of Number is:',Number:3), WFUTELN ('The new valu(~ of Letter is:' ,LetteT':2); WRITELN ('The new value of Limit is:', Limit:4:2), END. Example 1 The following declaration shows the definition of global variables for the program: VAF~ Number : INTEGER, Letter : CHAR, Limit : REAL, section These global variables are defined in the declaration these variable names associated with the main block of the program; subprograms can be used anywhere in the main block or in any of the defined in the declaration section. 7-11 PROCEDURES AND FUNCTIONS Example 2 The following shows the use of heading: INTEGER; (Nf?w .... NuITlbe T' formal parameters VAR New_Letter in the procedure CHAR) , The formal parameter list lists the variable nnmes that are associnted with variable names used in the procedure call. The names of the formal parameters are unknown outside the subprogram, and therefore cannot be used elsewhere in the program. Example 3 The following shows the use of a value parameter: New .... Numb~:~ T' : INTEGEH; The variable name New Number is associated (when the called) with n variable name in the procedure call. procedure is A value parameter does not pass a value from the subprogram back to the block from which it is called. The type must be specified, and the type must agree with the type of the variable named in the procedure call. Example 4 The following shows the use of a variable parameter: CHAF~ The v~riable name New Letter is associated (when the called) with a variable name in the procedure call. procedure is A variable parameter passes the value from the subprogram back to the block from which it is called. Variable parameters must be preceded with the reserved word VAR. As with value parameters, the type must be specified, and the type must agree with the type of the variable named in the procedure call. Example 5 This example contains a local variable. A local variable can be used only in the subprogram in which it is defined. It does not pass any values to or from the subprogram. Local variables are frequently used in FOR statements in subprograms. INTEGER; VAR New_Letter CHAR) ; VAF, I INTEGER; Local variables in subprograms are defined exactly as if they were being defined in the declaration section for the main block of the prog ram. 7-12 PROCEDURES AND FUNCTIONS Example () This is the call to the subpro~ram: BEGIN Chan~e <Number, Letter); The call includes the procedure name and the actual parameter list. The actual parameter list includes the names of all the variables that are being used to pass data to the subprogram. The actual parameter list must coincide with the formal parameter list in two ways: the number of variables must match, and the type of variables must match. When a procedure is called, the leftmost variable in the actual parameter list is associated with the leftmost variable in the formal parameter list. CHAr,) ; Chan~e (Number, Letter); The top line shows the formal parameter list. The second line shows the actual parameter list. When the procedure is called, New Number is associated with Number, and New Letter is associated with Letter. When the flow of the program ~eturns to the main block, the value associated with New Letter is assigned to Letter. The value associated with New iumber is not passed out of the procedure because New Number is a vallue parameter, and values of value parameters are not-returned from the subprogram. 7-13 - APPENDIX A PASCAL DEFINED NAMES This appendix contains lists of the names defined by PASCAL. section A.I lists the reserved words that cannot be redefined as identifiers. Section A.2 lists the semireserved words that can be redefined. Section A.3 lists the predeclared identifiers that hold a special meaning to PASCAL, but can, if necessary, be redefined as user identifiers. A.I RESERVED WORDS AND ARRAY BEGIN CASE CONST DIV DO DOWNTO ELSE END A.2 FILE FOR FUNCTION GOTO IF IN %INCLUDE LABEL NIL NOT OF OR PACKED PROCEDURE PROGRAM RECORD REPEAT SET THEN TO TYPE UNTIL VAR WHILE WITH SEMIRESERVED WORDS MODULE OTHERWISE REM VALUE A.3 PREDECLARED IDENTIFIERS ABS ARCTAN BOOLEAN CARD CHAR CHR CLOCK CLOSE COS DATE DISPOSE DOUBLE EOF EOLN EXP OPEN ORD OUTPUT PACK PAGE PRED PUT READ READLN REAL RESET REWRITE ROUND SIN EXPO FALSE FIND GET HALT INPUT INTEGER LINELIMIT LN MAXINT NEW NIL ODD A-I SINGLE SNGL SQR SQRT SUCC TEXT TIME TRUE TRUNC UNDEFINED UNPACK WRITE WRITELN APPENDIX B ASCII CHARACTER SET Table B-1 summarizes the ASCII character set. ASCII character set is a constant value of the CHAR. The ASCII decimal number in Table B-1 ordinal value (as returned by the PASCAL associated character in the type CHAR. Table B-1: Each element of the PASCAL predefined type is the same as the ORD function) of the The ASCII Character Set ORD Decimal Number Character Meaning o NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO SI DLE DCl DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US SP Null Start of heading Start of text End of text End of transmission Enquiry Acknowledgement Bell Backspace Horizontal tab Line feed Vertical tab Fo nn feed CarJriage return Shift out Shift in Da ta 1 ink e sc a pe Device control 1 Device control 2 Device control 3 Device control 4 Negative acknowledgement Synchronous idle End of transmission block Cancel End of med i urn Substitute Escape Fil,e separator Group separator Record separator unit separator Space or blank Exclamation mark Quotation mark 1 2 3 4 5 5 7 8 9 10 11 12 13 14 15 If) 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 " B-1 ASCII CHARACTER SET Table B-2: The ASCII Character Set (Cont.) ORD Character Meaning # Number sign Dollar sign Percent sign Ampersand Apostrophe Left parenthesis Right parenthesis Asterisk Plus sign Comma Minus sign or hyphen Period or decimal point Slash Zero One Two Three Four Five Six Seven Eight Nine Colon Semicolon Left angle bracket Equal sign Right angle bracket Question mark At sign Uppercase A Uppercase B Uppercase C Uppercase D Uppercase E Uppercase F Uppercase G Uppercase H Uppercase I Uppercase J Uppercase K Uppercase L Uppercase M Uppercase N Uppercase 0 Uppercase P Uppercase Q Uppercase R Uppercase S Uppercase T Uppercase U Uppercase V Uppercase W Uppercase X Uppercase Y Uppercase Z Left square bracket Decimal Number 35 36 37 38 39 40 41 42 43 $ % & ( ) * + 44 45 46 47 48 49 50 51 52 / o 1 2 3 4 53 5 54 n 55 56 57 58 59 7 8 9 1)0 < 61 62 > 63 ? 64 65 @ A 66 67 68 69 B C D E 70 F G H I J K L 71 72 73 74 75 76 77 M 78 N 79 80 81 82 83 84 85 86 87 88 89 90 91 o P Q R 5 T U V W X Y Z r B-2 ASCII CHARACrER SET Table B-2: The ASCII Character Se t ORD Decimal Number 92 93 94 95 9e) 97 98 99 100 101 102 103 104 105 106 107 -----Character (Co n t. ) Meaning -----\ or or a b c d E! f 9 h i. ~i k lOR 1 109 110 m n III 0 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 P q r c· ~) t II v '-I{ x y r, ~. Back slash Right square bracket Ci rcumfl ex or up arrow Back arrow or underscore Grave accent Lowel::-case a Lowercase b Lowercase c Lowel::-case d Lowercase e Lowercase f Lowercase 9 Lowercase h Lowercase i Lowercase j Lowercase k Lowel::-case 1 Lowercase m Lowercase n Lowercase 0 Lowercase p Lowercase q Lowercase r Lowercase s Lowercase t Lowercase u Lowercase v Lowe lrcase w Lowercase x Lowercase y Lowercase z Left brace vertical line Right brace Ti1dE~ DEL ------ Delete B-3 --------------,------------------------- APPENDIX C SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Tables C-I and C·-2 summarize the procedures and functions declared by PASCAL. Some of the listed procedures and functions are not described in this primer. For information on these, see the TOPS-20 PASCAL Language Manual. Table C-l: Predeclared Procedures Procedure Parameter Type CLOSE(f) f DATE(string) string = variable of type PACKED ARRAY [ 1 .• 11] OF CHAR Assigns current date to string. DISPOSE (p) p = pointer variable Release storage for pA. The pointer variable p becomes undefined. DISPOSE(p, tl, ••• ,tn) p = pointer variable tl, ••• ,tn tag field constants Release storage for pA; used when pA is a record with variants. Tag field values are optional; if specified, they must be identical to those specified when storage was allocated by NEW. FIND(f,n) f = file variable n = positive integer expression Moves the current file position to component n of file = file variable Action Closes file f. f. GET (f) f = file variable C-l Moves the current file position to the next component of f. Then GET(f) assigns the value of that component to fA, the file buffer variable. SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-l: Predeclared Procedures (Cont.) Procedure Parameter Type Action HALT None Calls LIBSSTOP, which signals SS$ ABORT. Without an appropriate condition handler, HALT terminates execution of the program. LINELIMIT(f,n) text f f i I e variable integer n expression Terminates execution of the program when output to file f exceeds n lines. The value for n is reset to its default after each call to REWRITE for file f. MARK(a) a a variable of type "INTEGER Places a marker for use when allocating memory for dynamic variables. NEW( p) p pointer variable Allocates storage for p" and assigns its address to p. NEW(p, tl, .•. ,tn) p = pointer variable tl, ... tn = tag field constants Allocates storage for p"; used when p" is a record with variants. The optional parameters tl through tn specify the values for the tag fields of the current variant. All tag field values must be listed in the order in which they were declared. They cannot be changed during execution. NEW does not initialize the tag fields. OPEN(f,attributes) f file variable attributes; see the TOPS-20 PASCAL Language Manual Opens the file f with the specified attributes. C-2 SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-I: Predeclared Procedures (Cont.) Procedure Pa r arne te r 'Type Action PACK(a,i ,z) a = variable of type ARRAY [m .. nl OF T starting i subscript of array a z = variable of type PACKED ARRAY fu .. vl OF T Moves (v-u+l) elements from array a to array z by assigning elements a ri 1 t h r 0 ug h a[i+v-ul to zful through z [v]. The upper bounn of a subscript must be greater than or equal to (i+v-u). PAGE(f) text f variable Skips to the next page of file f. The next line written to f begins on the second line of a new page. PUT (f) f file variable Writes the value of fA, the file buffer variable, into the file f and moves the current file position to the next component of f. READ(f, vl, ..• ,vn) f = file variable vl, ..• ,vn variables Assigns successive values from the input file f to the variables vI through vn. You must specify at least one va ria b 1 E~ ( vI). Th e default for f is INPUT READLN (f, vI, ••• ,vn) text f variable vI , •.• , vn variables file Performs the READ procedure, then sets the current file position to the beginning of the next line. The variables vI through vn are optional. The default for f is INPUT. RELEASE(a) a a variable of type "INTEGER Deallocates memory allocated by the NEW procedure up to the marker set by the MARK procedure. C-3 file SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-l: Predeclared Procedures (Cont.) Procedure Parameter Type RESET (f) f = file variable Enables reading from file f. RESET(f) moves the current file position to the beginning of the file f and assigns the first component of f to the file buffer variable, f~. EOF(f) is set to FALSE unless the file is empty. REWRITE (f) f file variable Enables writing to file E. REWRITE(f) truncates the file f to zero length and sets EOF(f) to TRUE. UNPACK ( z , a , i) z = variable of type PACKED ARRAY[u .. v] OF T a = variable of type ARRAY rm •. nl OF T starting i subscript in array a Moves (v-u+l) elements from array z to array a by assigning elements z [u] through z r v] to a[i] through a [1+v-ul. The upper bound a subscript must be greater than or equal to (l+v-u). TIr-tE (s tr ing) string = variable of type PACKED ARRAY [1 .• 111 OF CHAR Assigns the current time to string WRITE f = file variable pI, ..• ,pn write parameters Writes the values of pI through pn into the file f. At least one parameter (pI) must be specified. The default for f is OUTPUT" f text variable pI, .•. ,pn parameters Pe r fo rms the WRITE then procedure, skips to the the beginning of next line. The write parameters are optional. The defaul t for f is (f ,pI, ••• ,pn) WRITELN(f,pl, ••• ,pn) Action file write OUTPUT~ C-4 SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-2: Predeclared Functions Category Function Parameter Type Result Type Purpose Arithmetic ABS (x) In teger, real, double Same as x Computes absolute x. In teger, real, Double Real the Computes arctangent of x. AHCTAN(x) COS (x) EXP (x) LN (x) SIN (x) Integer, real Double Integer, real Double Integer, real Double Integelr, real Double value the of Double Real Computes the cosine of x. Double Real Double Real Double Real Computes e**x, the exponential function. the Computes natural logarithm of x. The value of x must be g rea ter than o. Computes of x. the sine Double SQR (x) Integer, real, double Same as x Computes x**2, the square of x. SQRT(x} In tege r , real Double Real Computes the square is root of x. If x zero, less than PASCAL genera tes an error. C-5 Double SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-2: Predeclared Functions (Cont.) Category Function Parameter Type Result Type Purpose Boolean EOF (f) File variable Boolean Indicates whether the file position is at the end of the file f. EOF(f) becomes TRUE only when the file position is after the last component in the file. The default for f is INPUT. EOLN (f) Text file variable Boolean Indicates whether the position of file f is at the end of a line. EOLN (f) is TRUE only when the position pointer is after the last character in a line, in which case the value of fA is a space. The default for f is INPUT. ODDen) In teger Boolean Returns TRUE if the integer n is odd; returns FALSE if n is eVI~n. UNDEFINED(r) Real, double Boolean Returns TRUE is the value of r is not in the proper floating-point fo rma t. C-6 SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-2: Predeclared Functions (Cont.) Category Function Parameter Type Result Type Purpose Transfer CARD(s) Set Integer Returns the number of elements currently belonging to the set s. CHR (n) Integer Char Returns the character (if one exists) whose ordinal value is n. OHD (x) Any ordinal type Integer Returns the ordinal value corresponding to the value of x. ROUND(n) Real, double Integer Rounds the real or double-precision value n to the nearest integer. SNGL(d) Double Real the Rounds double-precision real number d to a single-precision rea 1 n urn b e r • TRUNC (n) Real, double Integer Truncates the real or double-precision value n to an integer. C-7 SUMMARY OF PREDECLARED PROCEDURES AND FUNCTIONS Table C-2: Predeclared Functions (Cant.) Category Function Parameter 'rype Result Type Purpose Misc CLOCK None Integer Returns an integer value equal to the central processor time used by the current process. The time is expressed in milliseconds. EXPO(r) Heal, double Integer Returns integer-valued exponent of floating-point representation the the of r. PRED(x) Any ordinal type Same as x Returns the predecessor value in the type of x (if a predecessor exists) . SUCC (x) Any ordinal type Same as x Returns the successor value in the type of x (if a successor exists) • C-8 GLOSSAHY actual parameter Value or variable that is passed in a procedure or function and is used during execution of the subprogram. call actual parameter list List of actual parameters specified in a subprogram call. The actual parameters must be separated by commas, and the entire list must be enclosed in parentheses. address Specification of a location in the computer's memory. arithmetic expression Expression that evaluates to a real or integer value. arithmetic operator Symbol used with numeric variables, function references, and co"hstants in forming arithmetic expressions. In PASCAL, the arithmetic operators are +, -, *, I, **, DIV, MOD, and REM. array Collection of data items, called components, that have the same type and share an identifier. The components can be accessed by the array identifier and an index enclosed in brackets. See also index. ASCII character set Characters and output control data that represent characters in PASCAL. (ASCII stands for American Standard Code for Information Interchange.) Each member of the ASCII character set corresponds to a unique integer between 0 and 127, inclusive. assignment statement Executable statement that assigns a value to a variable. base type (1) For a subrange, the scalar type of which it is a subset. For example, the subrange 0 •• 123 has the base type INTEGER. (2) For a set, the nonreal scalar type from which the elements of the set are chosen. Glossary-l GLOSSARY block Declaration and executable sections of a program, procedure, or function. One block can be nested in another; for example, a procedure block is nested in the block of its declaring program. Boolean expression Expression that evaluates to one of the Boolean values, THUE. FALSE or BOOLEAN type Predefined scalar type that has the identifiers FALSE and TRUE as constant values. bound Upper or lower limit of a subrange, often used index limits for a dimension of an array. in defining the case label In the CASE statement, a constant of the same type as the case selector. A 1 ist of case labels, separated by commas and followed by a colon (:), pr,ecedes each statement tha t can be chosen for execution. case sE~lector In the CASE statement, the expression whose value determines the statement selected for execution. In choosing the statement to be executed, the CASE statement first evaluates the case selector. It then scans the case labels preceding each possible statement, and executes the statement that is labeled with the value of the case selector. character Single element of the ASCII character set predefined type CHAR. and a value of the See also character string Sequence of ASCII characters, enclosed in apostrophes. string constant and string variable. CHAR type Predefined scalar type constant values. that has the ASCII character set as comment Any sequence of characters appearing between the character pairs (* and *) or { and }. Comments are for documentation purposes and are ignored by PASCAL. compil er Program that translates source program statements into an module. Glossary-2 object GLOSSAHY component In an array, an individual data item denoted by and an index for each dimension. the array name compound statement One or more PASCAL statements, bracketed by the reserved BEGIN and END, that are executed sequentially as a unit. words conditional statement Statement that selects another statement for execution, depending on the value of an expression. PASCAL's conditional statements are IF-THEN, IF-THEN-ELSE, and CASE. constant Literal that represents a value that cannot change during program execution. Examples include 'p', 3, 2.781, and 'metaphysics'. control statement Statement that directs the flow of control in a program, such the IF-THEN-ELSE, FOR, WHILE, or CASE statement. as control variab]e Scalar variable that takes on sequential values with each iteration of a FOR loop. After completion of the loop, the value of the control variable is undefined. data structures Combinations of single data items that data, for example, records or arrays. form related groups of data type See type. decimal notation Representation of real numbers in the integer.fraction format, as in 23.27, -7.83, and 0.0. declaration Specification that lists one or more labels or that associates an identifier with what it represents. Labels and identifiers for constants, types, variables, procedures, and functions must be declared. declaration section The part of a program or subprogram declaration and definitions. block that contains the when is default Action taken or value explicitly specified. assumed by Glossary-3 the system none G LOSSl-.RY delimiter P~nctuation mark or reserved word that sets off one part of a the PASCAL program from another. BEGIN and END enclose (; ) executable section or a compound statement. The semicolon ( ) separates declarations or statements, and the period indicates the end of the program. . dimension Range of values for one subscript of an array. An array can have any number of dimensions; see multidimensional array. double precision Precision of approximately floating-point rea 1 n urn b e r ; precision. l~ the significant digits for a type DOUBLE provides double DOUBLE type Predefined scalar type that has double-precision real numbers values. as end - 0 f- f i 1 e Condition indicating that the current file contains no more data. The EOF function tests this condition. end-of-line Condition indicating that the current line contains no more data. The EOLN function tests this condition. enumerated type identifiers. Type comprising a sequence of values denoted by list of identifiers, separated by commas and enclosed parentheses, defines an enumerated type. A in executable image File containing the executable version of a program. An executable image is the output from the linker, and is created by linking one or more object modules. executable section The part of a block that delimited by BEGIN and block. contains the executable statements, END, that perform the actions of the executable statement Statement in the executable section of the block that performs an action or directs the flow of control. expression A constant, a variable, a function reference, or some combination of constants, variables, function references, operators, and parentheses that PASCAL can evaluate. Every expression is associated with a type. Glossary-4 GLOSSARY external file File that exists outside the scope of the PASCAL program, therefore must be specified in the program heading. and field Named component of a record, containing data items of one or more types. References to a field are in the record.fieldname format. field width Minimum number of characters that the WRITE or WRITELN procedure writes to a text file for a particular expression or character string. file See file variable. file component Accessible unit of a file variable. A file component can be of any type except a file type or a structured type containing elements of a file type. file name On TOPS-20, a 1- to 39- character name component of a source file specification. However, the name of a relocatable binary file must contain no more than six characters. file generation number Numeric component of a TOPS-20 file specification. As a file is updated and changed, the file's generation number is updated with each successive copy. file position position immediately following the file component that was last read or written. Only the component at the current file position can be accessed. file specification Unique TOPS-20 identification of a file on a mass storage medium (such as a disk). It describes the physical location of the file (node, device, and directory) and identifies the file name, file type, and file generation number. file type (1) On TOPS-20, in the source file specification, the 0- to 39-character type component that usually describes the nature of a file or how it is used. For example, PAS indicates a PASCAL source program. However, the file type of the reI file must contain no more than three characters. (2) In PASCAL, a structured type that is a sequence of any number of data components of the same type. Glossary-5 GLOSSARY file variable Named sequence of components of the same type used in I/O operations. A file can have any number of components; they can be of any type except a file type or a structured type containing components of a file type. floating-point notation Representation of real number data in the mantissa.fraction format, followed by a positive or negative exponent. The exponent is introduced by the letter E for a single-precision number, such as 7.321E02, and the letter D for a double-precision number, such as 4.0D-6. formal parameter Name that is declared in the heading of a procedure or function, and that represents an actual parameter when the procedure or function is invoked. formal parameter list List of passing mechanisms and formal parameter declarations that appears in the heading of a procedure or function. The entries in the list are separated by semicolons, and the list is enclosed in parentheses. function Program unit that returns a value when executed. A function consists of a heading, which includes the function's name and result type, and a block. function heading Specification of the name, formal parameter list, and result type of a function in a function declaration. function reference Use of a function name and actual parameter list in an executable statement to invoke the function. global identifier Identifier that is declared in a block at an outer level and therefore can be used inside the current (inner-level) block without redeclaration. global variable Variables that are declared in the declaration section for the main block of the program. Their scope is the entire program. heading Specification that precedes a block and defines the block's and parameters. Glossary-6 name GLOSSAHY identifier One or more alphanumeric characters that denote a variable, constant, type, procedure, function, or other item that is not a reserved word. Although an identifier can be any length, PASCAL treats only the first 31 characters as significant. index An expression of an ordinal type that is used with an array to specify a component of that array. name input procedure Procedure that reads data into a program. PASCAL provides predeclared input procedures: READ, READLN, ~nd GET. three integer In PASCAL, a whole number between -34359738368 and a value of type INTEGER. +341597381~7; INTEGER type Predefined scalar type that has integers as values. interactive mode Mode of communication in which the system responds to the commands and program input that the user types at the terminal. internal file File that exists only within the scope of a block and is when execution of that block terminates. deleted label (1) See case label. (2) Unsigned integer constant that is declared in the LABEL section and used to make a statement accessible from a GOTO statement. The label precedes the statement and is separated from it by a colon (:). LINK Program that creates an executable image from one or more object modules. Programs must be linked before they can be executed. LOAD Command used to invoke the LINK program. local identifier Identifier that is declared within a block and therefore inaccessible, outside that block. is unknown, and logical operator Reserved word or symbol that specifies a logical logical operators in PASCAL include AND, OR, and NOT. Glossary-7 test. The GLOSSARY loop body One or more statements that are specified condition is met. executed repetitively until a multidimensional array Array with elements of an array type. Each dimension of a its own subscripts, which can be of multidimensional array has different types. modulus Remainder of dividing one number by another. functions return the modulus. The MOD and the REM nested Containect within, as in a function declared within a procedure or a record that is a field of another record. object module Binary output from a language compiler or assembler that is input to the linker. The linker processes one or more object modules to produce an executable image. operator Symbol used in an expression to specific task. PASCAL includes logical operators. perform a cause PASCAL to relational, and arithmetic, ordinal Term used to encompass all nonreal scalar data types; refers to integer, character, and Boolean data types. ordinal ordinal value Integer corresponding to the position of a given value in a sequential list of values of its type. Ordinal value applies only to integer, character, Boolean, enumerated, and subrange types. The ORD function returns the ordinal value of an expression of one of these types. output procedure Procedure that writes data into a file. PASCAL provides predeclared output procedures: WRITE, WRITELN, and PUT. three packed Stored as densely as possible in the computer's memory. parameter Means of passing information between program units. See actual and write parameter, formal parameter, read parameters, parameters. Glossary-8 . . . . . . . . . . . . . . . . 1 . . . . . . . . . . . . ._ _ _ _ _ _ _ _ _ _ _ _ _ _ _ __ GLOSSARY parameter list Specification of the actual or formal parameters for a procedure or function. The parameter list follows the name of the procedure or function and is enclosed in parentheses. See also actual pRrameter list and formal parameter list. Pa scal (1) Blaise Pascal, a French mathematician and philosopher, born in 1623 and died in 1n~2. (2) Structured programming language developed by Niklaus Wirth in Zurich, Switzerland in the early 1970s. pointer Variable whose value is a reference to a dynamic variable. precedence rules Rules applied to the order of evaluation of operations in an expression. An operation with higher precedence is performed before an operation with lower precedence. predecessor value Value that immediately precedes a given value in any nonreal scalar type. The PRED function returns the predecessor value. predeclared Declared by PASCAL rather than by the programmer. predeclared identifier Identifier declared by PASCAL to name a type, constant, variable, procedure, or function. predeclared subprogram Procedure or function declared by PASCAL and without further declaration. available for use predefined See predeclare-d. procedure Program unit that consists of a procedure heading and a block. See also When called, a procedure is executed as a unit. predeclared subprogram. procedure call Statement that invokes a procedure. A procedure call consists of the name of a procedure and its actual parameter list (when requi red) • procedure heading Specification of the name and optional procedure in a procedure declaration. Glossary-9 formal parameters of a GLOSSARY program heading Specification that begins a PASCAL program. The program specifies the program's name and its external files. heading read parameters Variables used as parameters in a call to the READ procedure to which input values will be assigned. or READLN real number In PASCAL, the floating-point internal representation of a number that can be of any size; however, each number can be rounded to fit the precision of 27 bits (7 to 9 decimal digits). The value 0.0 is also included. REAL type Predefined scalar type that has single-precision real numbers values; synonymous with SINGLE type. as record Organized collection of data containing one or more fields, of which can be of a different type. each relational operator Symbol that tests the relationship between two values, the result of which is one of the Boolean values, FALSE or TRUE. PASCAL's relational operators are <, >, <=, >=, and <>. repetitive statement Statement that causes an action to be performed iteratively. repetitive statements are FOR, REPEAT, and WHILE. P~SCAL's reserved word Ward set aside by the PASCAL compiler as the name for a declaration, statement, data structure, delimiter, or operator. Reserved words have special meanings to the compiler and cannot be used as identifiers. return value Result of a function, assigned to the function's name during its execution. The return value is supplied to the calling program wherever a reference to the function appears. scalar data type Type in which the values are unique and indivisible units of data. The values of a scalar type follow a particular order. Predefined scalar types include INTEGER, REAL, CHAR, and BOOLEAN. scope Portion of the program in which an identifier has a particular meaning. The scope of an identifier is the block in which it is declared. Glossary-IO GLOSSARY semireserved word Word set aside by the PASCAL compiler that has a special meaning to the compiler. Semireserved words can be used as identifiers. set Collection of nonreal scalar elements, called members. single precision Precision of approximately floating-point real number; single precision. seven significant digits for a the types SINGLE and REAL provide SINGLE type Predefined scalar type that has single-precision real numbers val ues; synonymous wi th REAL type., as source file TOPS-IO or TOPS-20 file that contains source used as input to a language compiler. program statements statement Sequence of reserved words, identifiers, operators, expressions, and special s)~bols describing a program action or altering the flow of program execution. string See character string. string constant Character string used as a literal constant in the example 'one pink rose'. program, for string variable Variable of type PACKED ARRAY an integer constant. rl .. n] OF CHAR, where n represents structured data types Collection of related data components. the same type (as for arrays and files) for records). The components can be of or of different types (as subprog ram Procedure or functions; used in this manual in descriptions that apply to both procedures and functions. sub range types Subset of an existing scalar type, defined for use as a type. A subrange must be a continuous range of values, and is described by its upper and lower bounds separated by the .• symbol. Glossary-II GLOSSARY successor value Value that succeeds a given value in any nonreal The SUCC function returns the successor value. scalar type. symbolic constant Name defined to represent a constant value; of the value. can be used in place symbol ic name Word used in a PASCAL program. A symbolic name can be a reserved word, a predeclared identifier, or a user identifier. text file File that has components of type CHAR and is into lines. implicitly divided type Set of values, usually named with an identifier, for which certain operations are defined. Some types are defined by PASCAL -- INTEGER, REAL, SINGLE, DOUBLE, BOOLEAN, and CHAR. Others are defined by the programmer. user-defined type Type defined by the programmer. User-defined types can be scalar (enumerated or subrange), structured, or pointer. user identifier Identifier created by the programmer to denote constant, type, variable, procedure, or function. a program, value initialization TOPS-20 extension that allows a programmer to assign a constant value to a variable in the program's declaration section. value parameters Parameters in which the value is passed only to the subprogram. Another value is not passed back from the subprogram. variable Data item (of fixed type) execution of the program. that can change in value during variable parameters Parameters in which the value is passed to the subprogram, and a changed value is passed back to the block from which the subprogram is called. write parameters Expressions that are specified as parameters to the WRITE WRITELN procedure, which writes them in the specified file. Glossary-12 or INDEX -AABS function, C-8 Actual parameter list See Glossary Actual parameters, 7-3, 7-7 See Glossary Address See Glossary AND operator, 2-11, 3-2, ~-9 ARCTAN function, C-8 Arithmetic expressions, 2-8 See Glossary Arithmetic functions, C-R Arithmetic operators, 2-7, 2-8 See Glossary ARRAY, 3-2, 5-2 Arrays, 2-6, 5-1, 5-2 See Glossary ASCII character set, B-3 See Glossary Assignment operator, 6-2 Assignment statement, 1-6, 2-7, 6-1, 6-2 See Glossary -8- Base type, 2-6 See Glossary BEG IN, 1- 3, 3 - 2 Binary notation, 2-3 Block, 1-2, 3-1, 7-2, 7-3 See Glossary Boolean expressions, 6-5, 6-8, 6-10, 6-11 See Glossary Boolean functions, C-8 BOOLEAN type, 2-3, 2-5, 3-3 See Glossary Bound See Glossary -c- CARD function, C-8 Case label See Glossary Case selector, 6-13 See Glossary CASE statement, 6-10, 6-13 Case-label list, 6-11 CHAR type, 2-3, 2-5, 3-3, 5-2 See Glossary Character See GJ ossary Character strings, 5-8 See Glossary CHR function, C-8 CLOCK function, C-8 CLOSE procedure, C-4 Command EXECUTE, 1-11 LOAD, 1-11 See Glossary Commen ts, 1-2 See Glossary Comparisons, 2-10 Compiler See Glossary Compiling a program, 1-10 Component type, 5-2 Components, 5-1 See Glossary Compound statement, 1-~, 6-1, 6-3 See Glossa ry Conditional statement, 6-1, 6-10 See Glossary CONST, 1-4, 3-1, 3-2, 3-4 Constant definitions, 3-4 Constants, 2-1 See Glossary Control statement See Glossary Control variable, 6-4 See Glossary COS function, 3-3, C-8 Creating a program, 1-9 CTRL/Z, 4-14 Calling a function, 7-6 Calling a procedure, 7-3 Index·-l INDEX (Cont.) Expressions (Cont.) Boolean, 0-5, h-8, 0-10, 0-11 See Glossary logical, 2-5, 2-11, 6-9 relational, 2-5, 2-10 External file See Glossary -0- Data structures See Glossary Da ta types, 2-1 See Glossary DATE procedure, C-4 Decimal notation, 2-3 See Glossary Declaration section, 1-2, 1-4, 7--2 See G]ossary Declarations, 3-1 Declaring a function, 7-5 Decla~ing a procedure, 7-3 Default See Glossary Defining logical names, 4-2 Definitions, 3-1 Delimiter See Glossary Dimension See Glossary DISPOSE procedure, C-4 DIV operator, 2-8, 3-2 DO, 6--4, 6-8 Dollar sign, 3-3 Double precision, 2-3, 2-4 See Glossary DOUBLE type, 2-3, 3-3 See Glossary DOWNTO, 6-4 -F- -EELSE, 3-2 END, 1-3, 3-2, 5-11 End-of-file See Glossary End-of-l ine See Glossary Enumerated types, 2-6, 3- 7 , 3-8 See Glossary EOF function, 3-3, 4-1, 4-12, 4--13, C-8 EOLN function, 4-1, 4-12, 6-9, C--8 EXE file, 1-11 Executable image See Glossary Executable section, 1-2, 1-5, 7-2 See Glossary Executable statement See Glossary EXECUTE command, 1-11 Executing a program, 1-11 /EXIT switch, 1-10 EXP function, C-8 EXPO function, C-8 Expressions, 2-2, 2-7 See Glossary a r i t hm e tic, 2 - 7 SE~e Glossary FALSE, 2-5, 3-3 Field See Glossary Field names, 5-10 Field widths, 4-8 See G]ossary Field-width parameters, 4-9 FILE, 3-2 File See Glossary Fi 1 e componen t See Glossary File generation number See Glossary File name See Glossary File position See Glossary File position pointer, 4-13 File specification See GJossary File type See Glossary File variable See Glossary Files, 2-6, 5-1 FIND procedure, C-4 Floating-point notation, 2-3 See Glossary FOR statement, 6-3, 6-4 Formal parameters, 7-3, 7-5, 7-7 See Glossary FUNCTION, 1-4, 3-1, 3-2, 7-1, 7-5 Function See Glossary ABS, C-8 ARCTAN, C-8 CARD, C-8 CHR, C-8 CLOCK, C-8 COS, 3-3, C-8 EOF, 3-3, 4-1, 4-12, 4-13, C-8 EOLN, 4-1, 4-12, 6-9, C-8 EXP, C-8 EXPO, C-8 LN, C-8 ODD, C-8 ORD, 2-3, 2-6, C-8 PRED, C-8 ROUND, C-8 SIN, C-8 SNGL, C-8 SQR, C-8 Index-2 .w__________________________ . . . . 1. . . . . . . . . . , . . . . . . . . . . . . . . . . . . . . . . . . . . . ., . . . . . . . . . . . . . . ._ _ _ _• • • • , . • . . . . . . . . . . . . . . . . . . . . . . . . _ _ INDEX Function (Cont.) SQRT, C-8 SUCC, C-8 TRUNC, C-8 UNDEFINED, C-8 Function call, 7-~ Function example, 7-~ Function heading, 7-5 See Glossary Function reference See Glossary Function type, 7-S Functions, 2-1 -GGET procedure, C-4 Global identifiers See Glossary Global variables, 7-2 See Glossary Glossary See Glossary -HHALT procedure, C-4 Heading See Glossary Hexadecimal notation, 2-3 -IIdentifiers, 2-1 See Glossary IF statement, 3-2 IF-THEN statement, ~-10 IF-THEN-ELSE statement, 6-10, 6-11 Index See Glossary Index type, 5-2 INPUT, 1-4, 3-3, 4-1 Input procedure See Glossary Integer See Glossary INTEGER type, 2-3, 3-3 See Glossary Interactive mode See Glossary Internal file See Glossary -LLABEL, 1-4, 3-1 Label See Glossary LINELIMIT procedure, C-4 LINK See Glossary /LISTING switch, 1-10 (Cont.) LN function, C-8 LOAD command, 1-11 See Glossary Loading an object file, 1-11 Local identifier See Glossary Local variables, 7-2 Logical expressions, 2-5, 2-11, 5-9 Logical operators, 2-7, 2-11 See Glossary Loop body See Glossary Loops, 6-4, ~-5, ~-8 Lower limit, 3-9 -MMembers, 5-1 Miscellaneous functions, C-8 MOD operator, 2-8 ~10DULE, 3--2 ~~odulus See Glossary Multidimensional arrays, See Glossary 5-~ -NNested See GJossary NEW procedure, C-4 NOT operator, 2-11, 3-2 -0- Object module See Glossary Octal notation, 2-3 onD function, C-8 OPEN procedure, C-4 Operator See Glossary AND, 2-11, 3-2, 6-9 ass i. g nm e nt, 6 - 2 DIV, 2-8, 3-2 MOD, 2-8 NOT, 2 -11, 3 - 2 OR, 2-11, 1-2, 6-9 REM, 2-8, 1-2 Operators arithmetic, 2-7, 2-8 See Glossary logical, 2-7, 2-11 See Glossary relational, 2-7, 2-10, 5-10 See Glossary OR operator, 2-11, 1-2, 6-9 ORD function, 2-2, 2-5, C-8 Ordinal See GJossary OTHERWISE, 3-2 OTHERWISE clause, ~-11 Index--3 INDEX (Cont.) OUTPUT, 1-4, 3-3, 4-1 Output procedure See Glossary -p- PACK procedure, C-4 PACKED, 5-9 Packed See Glossary Packed array, 5-8 PAGE procedure, C-4 Parameter list, 7-2 See Glossary Pa rameters, 7-7 See Glossary a c tua 1, 7 - 3, 7 - 7 See Glossary formal, 7-3, 7-7 See Glossary read See Glossary value, 7-7 See Glossary variable, 7-7 See Glossary write See Glossary PASCAL extensions, 1-1 PASDDT, 1-11 PASIN:,4-2 PASOUT:, 4-2 Period, 1-2 Pointer See Glossary Pointer data types, 2-2 Precedence, 2-12 Precedence of operators, 2-12 Precedence rules See Glossary PRED function, C-8 Predecessor value See Glossary Predeclared functions, C-4, C-8 Predeclared identifiers, 3-2, 3-3, A-I See Glossary Predeclared procedures, C-4 Predeclared subprogram See Glossary PRINT command, 1-11 PROCEDURE, 1-4, 3-1, 3-2, 7-1, 7-3 Procedure See Glossary CLOSE, C-4 DATE, C-4 DISPOSE, C-4 FIND, C-4 G E'I', C-4 HALT, C-4 LINELIMIT, C-4 NEW, C-4 Procedure (Cont.) OPEN, C-4 PACK, C-4 PAGE, C-4 PUT, C-4 READ, 3-3, 4-1, 4-3, 5-9, C-4 READLN, 3-3, 4-1, 4-5, C-4 RESET, C-4 REWRITE, C-4 TIME, C-4 UNPACK, C-4 WRITE, 3-3, 4-1, C-4 WRITELN, 3-3, C-4 Procedure call, 7-3 See Glossary Procedure example, 7-4 Procedure heading, 7-3 See Glossary P R OG R AM, 1- 4, 3 - 2 Program development, 1-7 Program example, 1-12 Program head ing, 1-2, 1-4 See Glossary Program structure, 1-2 PUT procedure, C-4 -RRead parameters See Glossary READ procedure, 3-3, 4-1, 4-3, 5-9, C-4 Reading data, 4-1, 4-3 READLN procedure, 3-3, 4-1, 4-5, C-4 Real number See Glossary REAL type, 2-3, 2-4, 3-3 See Glossary RECORD, 3-2, 5-11 Record See Glossary Record declaration, 5-10 Records, 2-6, 5-1, 5-10 REL file, 1-11 Relational expressions, 2-5, 2-10 Relational operators, 2-7, 2-10, 5-10 See Glossary REM operator, 2-8, 3-2 REPEAT statement, 3-2, 6-3, 6-5 Repetitive statement, 6-1, 6-3 See Glossary Reserved words, 1-3, 3-2, A-I See Glossary RESET procedure, C-4 Result type, 7-5 REWRITE procedure, C-4 ROUND function, C-8 RUN command, 1-11 Index-4 INDEX (Cont.) -SScalar data types, 2-2 See Glossary Scope See Glossary Scope of identifiers, 7-3 Section declaration, 1-2, 1-4, 7-2 See Glossary executable, 1-2, 7-2 See Glossary Semicolon, 1-2 Semireserved words, 3-2, A-I See Glossary Sets, 2-5, 5-1 See Glossary SIN function, C-8 Single precision, 2-3 See Glossary SINGLE type, 2-3, 3-3 See Glossary SNGL function, C-8 Source file See Glossary SQR function, C-8 SQRT function, C-8 Statement assignment, 1-6, 2-7, 6-1, 6-2 See Glossary CASE, 6-10, 6-13 compound, 1-6, 6-1, 6-3 See Glossary conditional, 6-1, 6-10 See Glossary control See Glossary FOR, 6-3 IF, 3-2 IF-THEN, 6-10 IF-THEN-ELSE, 6-10, 6-11 REPEAT, 3-2, 6-3, 6-5 repetitive, 6-1, 6-3 See Glossary WHILE, 3-1, 6-3, 6-8 Statements, 6-1 See Glossary String constant See Glossary S t ring va ria b 1 e See Glossary Structured data types, 2-2, 2-6 See Glossary Structured types, 5-1 Subprogram See Glossary Subprogram call, 7-2 Subprogram format, 7-2 Subprogram heading, 7-2 Subprograms, 7-1 Subrange type, 2-6, 3-6, 3-7, 3-9 See Glossary SUCC function, C-B Successor value See Glossary Switch /EXIT, 1-10 /LISTING, 1-10 Symbolic constant See GJ ossary Symbolic names, 3-1 See Glossary Syntax rules, 3-3 -TText files, 4-1, 4-12 See Glossary THEN, 3-1, (-)-10 TIME procedure, C-4 TO, 6-4 Transfer functions, C-8 'I'RUE, 2-5, 3-3 TRUNC function, C-8 'I'YPE, 1-4, 3-1 'I'ype See Glossary BOOLEAN, 2-3, 2-5, 3-3 See Glossary CHAR, 2-3, 2-5, 3-3 See Glossary DOUBLE, 2-3 See Glossary INTEGER, 2-3, 3-3 See Glossary REAL, 2-3 See Glossary SINGLE, 2-3 Type definitions, 3-5 -uUNDEFINED function, C-8 Underscore, 3-3 UNPACK procedure, C-4 UNTIL, 3-1, 6-5 Upper limit, 3-9 User identifiers, 3-3 See Glossary User-defined types, 2-6, 3-7 See Glossary -vVALUE, 1-4, 3-1, 3-2 Value initialization See Glossary Value parameters, 7-7, 7-8 See Glossary VAR, 1-4, 2-7, 3-1, 3-6 Variable declarations, 2-6, 3-6 Variable parameters, 7-7, 7-8 See Glossary Variables, 2-1, 2-6 global, 7-2 See Glossary Index--5 INDEX Variables (Cont.) local, 7-2 -wWHILE statement, 3-1, ~-3, ~-8 (Cont.) Write parameters See Glossary WRITE procedure, 3-3, 4-1, 4-7, C-4 WRITELN procedure, 3-3, 4-11, C-4 Writing data, 4-1, 4-6 rndex-6 TOPS-20 PASCAL Primer AA-L314A-TM READER:'S COMMENTS NOTE: This form is for document comments only. DIGITAL will use comments submitted on this form at the company's discretiion. If you require a written reply and are eligible to receive one under Software Performance Report (SPR) service, submit your comments on an SPR form. Did you find this manual understandable, usable, and well-organized? Please make suggestions for improvement. Did you find errors in this manual? If so, specify the error and the page number. Please indicate the type of reader that you most nearly represent. D Assembly language programmer D Higher-level language programmer D Occasional programmer (experienced) D User with little programming experience D Student programmer D Other (please speci~~~~~~,~~~~~~~~~,~~~~~~~~~ Name _~_~ _______________ Date ~ _ _ _,_________ Organization ___,______________~ Telephone _ _ _ _ _ _ _ __ Street _ _ _ _ _ _~___~_~__~~~_ _ _~_ _ City _ _ _ __ ,___________ State _ _ _ _ Zip Code _ _ __ or Country - - - Do Not Tear -- Fold Here and Tape 111111 No Postage Necessary if Mailed in the United States BUSINESS REPLY MAIL FIRST CLASS PERMIT NO. 33 MAYNARD MASS. POSTAGE WILL BE PAID BY ADDRESSEE SOFTWARE PUBLICATIONS -- 200 FOREST STREET MR01-2/L 12 MARLBOROUGH, MA 01752 Do Not Tear - Fold Here and Tape - - - - - - - __ - - - - - - - - - - - - - - - - - - - - __ - - - - - - - - __ - - - - __ I 1 I I I I I (J,j I'S I-J I~ I::: o o 0.1 C .£ ~ "5 u
Home
Privacy and Data
Site structure and layout ©2025 Majenko Technologies