XJDl5 SIGMA 5/7 BASIC

Xerox Oata Systems

Reference Manual

- ~ , ~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ .• ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ . ~~§~~ ~~§~~ ~~§~~ .' ~~§~~ ~~§~~ ~~§~~ ~ -~ - ~~§~~ ~~§~~ ~~§~~ .• ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ~~§~~ ------. '- .. ------..._- - -- -' ~- --- - . -- --.--- __ .--i.....",. ~_ -~._.______.. ______. __ . ______._ -'-_ ...... A- ______. __ Price: $2.00

BASIC REFERENCE MANUAL

for

XDS SIGMA 5/7 COMPUTERS

90 15 46C

July 1970

Xerox Data Systemsj701 South Aviation Boulevard/EI Segundo, California 90245

@1969. 1970. Xerox Data Systems. Inc. Printed in U.S.A. REVISION

This publication is a minor revision to the BASIC Reference Manual for XDS Sigma 5/7 Computers, and incorporates new material for the Universal Time-Sharing Monitor version of BASIC. A change in text from that of the previous manual is indicated by a vertical bar in the margin of the page.

RELATED PUBLICATIONS o

Title Publication No.

XDS Sigma 5 Computer Reference Manual 900959

XDS Sigma 7 Computer Reference Manual 900950

XDS Sigma 5/7 Batch Processing Monitor (BPM) Reference Manual 900954

XDS Sigma 5/7 Batch Processing Monitor (BPM) Operations Manual 90 11 98

XDS Sigma 5/7 Batch Time-Sharing Monitor (BTM) Reference Manual 90 1577

XDSSigma Multipurpose Keyboard/Display Reference Manual 900982

XDS Sigma 5/7 Mathematical Routines Technical Manual 900906

XDS Sigma Message-Oriented Communications Equipment Reference Manual 90 1568

XDS Sigma Character-Oriented Communications Equipment Reference Manual 900981

XDS Sigma 7 Universal Time-Sharing System (UTS) Reference Manual 900907

XDS Sigma 7 Universal Time-Sharing System (UTS) Operations Manual 90 1675

NOTICE

The specifications of the software system described in this publicotion ore subject to change without notice. The availability or performance of some features may depend on a specific configuration of equipment such as additional tape units or larger memory. Customers should consult their XDS sales representative for details.

ii CONTENTS

./------.., l. AN INTRODUCTION TO BASIC User-Defined Functions 16 16 The Computer Dimensioning 16 Computer Programs DIM 16 The BASIC System Print Images 17 A Sample Program PRINTUSING 17 : (Image statement) 17 2. ELEMENTARY FEATURES OF BASIC 5 Matrix Operations 18 Print 18 0 Elements of a BASIC Program 5 Put 18 Step Numbers 5 Get 18 Simple 5 Size 19 Simple Variables 5 Read 19 (' Arithmetic Operators 5 Input 19 Intrinsic Functions 5 Zero 19 Expressions 6 Constant 19 Error Messages 6 Identity Matrix 19 Defining Arithmetic Operations 6 Copy 20 LET 6 Scalar Multiplication 20 6 Addition and Subtraction 20 6 Transposition 20 7 Multiplication 20 Data 7 Inversion 20 PRINT 7 Simultaneous Equation Solution 21 Data Input 8 DATA 8 4. BASIC OPERATING PROCEDURES READ 8 22 Miscellaneous 8 On-Line STOP and PAUSE 8 22 Calling BASIC END 8 22 REM 8 Editing Mode 22 Looping 8 Compi lation and Execution Mode 24 Escape Key Activation FOR 9 24 Parameter Setting NEXT 9 24 Direct Statements 25 3. ADVANCED FEATURES OF BASIC 10 File Operations 25 Precision of Output 25 Other Elements of a BASIC Program 10 Printer Width 25 Status Arphanumeric Constants 10 25 Sign-Off 26 Subscripted Variables_ 10 Batch Processing 26 Additional Intrinsic Functions 10 Print Formats II UTS BASIC ADDITIONS 30 Number Ranges 12 5. External Data Input 12 Summary of UTS Additions 30 INPUT 12 UTS BASIC Language Extensions 30 Rereading Data 13 Character String Manipulation 30 RESTORE 13 Intrinsic Functions Added to UTS BASIC 32 Branching to a 13 Chain Link Statement 33 GOSUB and RETURN 13 Additions to Edit Command List 33 Multiple Path Branching 14 CLEAR 33 ON 14 NULL 33 GOTO ••. ON 14 FILE PACK 34 File Manipulations 14 EXECUTE 34 OPEN 14 SET 34 CLOSE 15 DELETE 34 PUT 15 INPUT 34 15 Increased Interaction, Edit-Execute Activities_ 34 Running Consecutive Programs 15 Break-Proceed Logic Changes 35 CHAIN 15 Changes in Direct-Statement Capability ___ 35

iii Summary of UTS BASIC Operating Procedures __ 35 ILLUSTRATIONS Group 1 . 35 Group 2 35 Group 3 36 1. The Evolution of a Program 2 Group 4 36 2. Sample Program 2 Proceed 36 3. Modified Sample Program 3 Direct Statements 36 4. Nested Loops 9 Batch Processing 36 5. Coding Sheet with Modified Sample Program __ 26 I/O Control 36 6. Deck Setup for BASIC Batch Processing 27 7. Deck Setup for BASIC Batch Processing (UTSl-- 28 6. BASIC MESSAGES 37 INDEX 48 APPENDIXES TABLES

A. SUMMARY OF BASIC STATEMENTS 41 1. Order of Arithmetic Operations 5 B. BASIC EDITING COMMANDS 44- 2. Partial list of BASIC Intrinsic Functions 5 C. BASIC INTRINSIC FUNCTIONS 45 3. Condition Operators 7 D. TECHNICAL ASPECTS OF MATHEMATICAL 4. Additional BASIC Intrinsic Functions 10 RUN-TIME FOR BASIC 47 5. Intrinsic Functions, UTS BASIC Only 33

iv 1. AN INTRODUCTION TO BASIC

BASld is a programming system that enables a person with COMPUTER PROGRAMS little or no computer experience to write computer programs for solving a variety of numerical problems. The system is A computer program is analogous to the operations manually easy to learn and to use, but it also conlains a number of performed on a desk calculator in solving a problem. That advanced features that make it suitable for programming is, a program is a series of instructions (statements) that complex problems. prescribes a set of operations to be performed by the com­ puter to solve a particular problem. To make up the pro­ To augment the flexibility of the language, XDS BASIC gram, the programmer selects and orders the instructions he provides the user with two highly desirable capabilities for requires out of many the computer can perform. These in­ on-I ine operation: o structions are usually in a format referred to as "symbolic 1. Immediate, statement-by-statement syntax checking, language". That is, they are made up of ordinary numbers, which permits the programmer to correct syntax errors English words, and alphabetic symbols in a form that can be without the necessity of waiting compilation and re­ input to the computer. sulting error messages. As the program is read into the computer, it must be trans­ 2. Direct execution of statements, which allows the pro­ formed (compiled) from symbolic language into so-called grammer to debug a program and to continue execution "machine language", which is the only language the com­ without recompilation. Additionally, direct statements puter understands. After the machine-language program permit use of the computer in a desk calculator fashion. has been produced, the computer can be allowed to "exe­ cute" it; that is, to step through the instructions in the Alternatively, after on-,line development, programs may be program one at a time, performing the operations each submitted for compilation under the Batch Processing Moni­ calls for. When the program specifies, the results accumu­ tor System. BASIC is most effective in small to medium lated up to a certain point are recorded permanently by scale applications of a computational nature. being sent to some output device such as a line printer, typewriter, magnetic tape, or card punch. This output This chapter orients the reader to fundamental programming produced by the user's program is usually printed in concepts. The reader with some programming experience natural-language form as English words, abbreviations, and may skip to Chapter 2, where the elementary BASIC state­ decimal numbers. When the program has finished operating, ments are explained. As the skill of the BASIC programmer either it will be rerun using new data, or another program increases, he may progress to Chapter 3, where more ad­ wi II be read in and executed. vanced features of the system are presented. Chapter 4 describes procedures for operating the computer within the THE BASIC SYSTEM BASIC system. The appendixes contain reference material including a summary of the BASIC statements. BASIC is an consisting of both the BASIC language and the BASIC processor for the language. The BASIC language is composed of English words, decimal THE COMPUTER numbers, special characters, and rules of usage with which the user writes a BASIC program. The BASIC processor is a The beginning programmer may think of a computer as an previousl y-stored program that compiles the user's BASIC­ elaborate desk calculator; that is, a device capable of language program and assists in execution of the resulting performing step-by-step calculations on data to praduce a machine-language program. The overall flow of information numerical result. That part of the computer most like a from programmer to computer and back is shown in Figure 1. calculator is the arithmetic unit, in which mathematical operations are performed. Other, no less important, ele­ ments of the computer that a calculator does not have are At this point, the user need not be concerned with opera­ a memory unit for storing program instructions and data, a tional details such as entering his symbolic program into control unit for stepping through the program and directing the computer, the compilation of the program into machine the execution of its instructions, and input/output devices language, the actual execution of the program, or the for accepting the program and data and for delivering the handling of output. Operating instructions and related results to various output media. matters are explained in Chapter 4.

A SAMPLE PROGRAM Figure 2 shows a program written in the BASIC language. This program evaluates the quantities tBASIC stands for Beginner's All-Purpose Symbolic Instruc­ tion Code, which was originOlly developed at Dartmouth -B ±~B2 -4AC College. 2A

An Introduction to BASIC Programmer Analyzes new prob­ lem or output of pre­ vious program ond designs method of solution 5 Output Programmer Transm i tted to output Selects required media in natural­ BASIC instructions language form for his program

4 3 Program Program Compiled and Input to computer executed

Figure 1. The Evolution of a Program

Study the program step-by-step. The simplicity of BASIC ments always begin with a step number, and in this case, are makes it possible, even for beginning programmers, to specified in multiples of 5. This numerical spacing gives understand the logic of the program. This program wi II be the programmer enough "elbow room" to insert statements, used to illustrate some fundamental elements of the BASIC if necessary, without renumbering following statements. In language. (In BASIC, multiplication is indicated by an BASIC, step numbers range from 1 through 99999. asterisk (*), and division by a slash (/). The symbol < means "less than".) Except for statement 35, statements 15 through 55 are LET statements. A LET statement assigns the value of whatever is on the right side of the equal sign to the variable that is 15 LET A = 1 on the left side of the equal sign. A variable is a quantity 20 LET B = 5 whose value may vary or change according to the conditions 25 LET C = 4 of the program. In this program, the value +1 will be as­ 30 LET D2 = B B - 4 A C * * * signed to variable A, the value +5 will be assigned to vari­ 35 IF D2 0 THEN 70 < able B, and the value +4 will be assigned to variable C. 40 LET D = SQR(D2) (The plus sign is optional.) 45 LET A2. = A + A LET Xl = (-B + D)/A2 50 LET statement 30 defines an arithmetic operation; it says LET X2 = (-B - D)/A2 55 that the variable D2 is to be set equal to the quantity B2 - PRINT Xl, X2 60 4AC. The computer is able to evaluate t.his formula because STOP 65 it has already been told the values of A, B, and C. For 70 PRINT 'NO REAL ROOTS' this program, then, D2 is actually equal to 52 - 4 x 1 x 4. 75 STOP The program was written so that the variables and the formula 99999 END are defined in different steps because the programmer may Figure 2. Sample Progra m want to change the values of A, B, and C at a later time without rewriting the entire program. The sample program consists of an ordered series of state­ ments. Each statement is a line of information that either Statement 35, an IF ... THEN statement, sets up a condition tells the computer to perform some operation, or provides that has to be tested before the computer can do any more data that wi II be used in these operations. Note that state- work. It tells the computer to verify whether the variable

2 A Sample Program D2 (calculated in the preceding statement) is less than zero, It soon becomes apparent that this program has definite that is, a negative number. If the statement is true, that is, limitations if we want to compute the result for a number of if D2 is less than zero, the computer will "branch" to state­ values of the variables. However, we can modify the pro­ ment 70, skipping over statements 40 - 65. gram so that we may easily insert many different values for A, B, and C. The altered program is shown in Figure 3. Statement 70 is a PRINT statement. It tells the computer to print on on output device the message contained within 25 READ A, B, C the quotation marks, namely, NO REAL ROOTS. The con­ 30 D2 B * B - 4 * A * C ditional test set up in statement 35.and its resulting message 35 IF D2 < 0 THEN 70 are inc luded in the program to warn the user that he cannot 40 D SQR(D2) calculate the square root of a negative number. If state­ 45 A2=A+A ment 35 is not true, that is, if D2 is positive or zero, the 50 Xl := (-B + D)/A2 computer wi II go to the next statement in the program. 55 X2 = (-B -D)/A2 60 PRINT Xl, X2 Statement 40 tells the computer to calculate the square root 65 GOTO 25 of D2 and to assign that value to the variable D. The com­ 70 PRINT 'NO REAL ROOTS' puter performs this square root calculation with no further 75 GOTO 25 direction from the program because it has been previously .' 80 DATA 1,5,4,2,3,5,2,7,3 programmed to perform this common mathematical procedure. 99999 END Previousl y programmed operati ons such as SQR are called intrinsic functions. They are designated by 3-letter codes Figure 3. Modified Sample Program similar to SQR. Intrinsic functions will be discussed in Chapter 2. The characters enc losed by parentheses following Notice that the word LET does not appear in the modified the code word SQR are called the argument. The argument program. The command word LET may be omitted from the of a function usually represents the value to be used in the LET statement, thereby simplifying the writing of the pro­ calculation called for. In this case, the argument D2 is gram. Also notice that the first three LET statements in the the name of a variable whose value was calculated in an old program have been replaced by a READ statement in the earl ier step. modified program. Statement 45 assigns the value of the sum A + A to the READ tells the computer to assign, in consecutive order, the variable A2. data values given in a DATA statement to the variables specified in READ. The computer will search the program Statements 50 and 55 define similar arithmetic operations for the DATA statement (statement 80) and will assign its and assign their values to variables Xl and X2, respectively. first three values, 1,5, and 4, to variables A, B, and C, Notice that certain terms in these two statement are grouped respectively. within parentheses•. This grouping is done to accommodate the order in which the computer performs arithmetic opera­ The program will then calculate D2 and take appropriate tions. In the BASIC system, the computer will consider ciction. GOTO statements, after the PRINT statements, first parenthesized quantities, then it will exponentiate will direct the computer back to the READ statement (via (indicated by the symbol I), then it will multiply and divide its step number) where it will be instructed to pick up the (symbols * and /) and finally, it will add and subtract (+ next three values in the DATA statement. and -). When no operation takes precedence over another, the comput~r evaluates operations from left to right. If the The computer wi II now assign 2,3, and 5 to A, B, and C, numerators were not enclosed by parentheses in statements respectively, and will calculate the result. In this case, 50 and 55, only the quantity D would be divided by A2 and statement 35 will be true, that is, D2 will be a negative this quotient would then be added to or subtracted from -B. number and the computer will branch to statement 70, The parentheses alter this sequence of operations because , . where the PRINT statement will tell the computer to print quantities contained within parentheses are evaluated first. the message NO REAL ROOTS. Statement 75 will be exe­ To avoid mistakes, the programmer is advised to check that cuted next and will direct the computer bock to statement he has the same number of left and right parentheses in any 25 READ to pick up the last three values in DATA. When formula. th; final ~alculations and printouts are made, all values in the DATA statement will have been used, and the program Statement 60, another PRINT statement, will print out the wi II stop by i tse If. calculated values of X 1 and X2. Numbers, the usual output of the computer, are generally Statements 65 and 75 stop the program. printed out in a recognizable form. Occasionally, however, the numbers are very large or very small, and the computer Statement 99999 indicates the end of the program. prints them out in what is called floating-pointt notation. In summary, the complete program outlined a calculation, specified values to be used in its solution, and printed out tThis is computer terminology for exponential (scientific) either the answer or an error message. notation.

A Sample Program 3 The numbers 3.4E-6 and. 7E+9 are in floating-point nota­ 4030 LET B 1 tion. The E means that the decimal value is found by multi­ 4040 PRINT SQR{B) plying the number preceding E by 10 to a specified power 4050 LET B B 1 (exponent). The power of 10 to be used is the plus or minus val ue following theE. This is much less compl i cated than The three statements will give the square root of an increas­ it appears. In actual practice, the exponent value follow­ ing number if we have some way of returning to statement ing the E simply tells the programmer which way and how 4040 each time statement 4050 is executed. The IF ... THEN many places to move the decimal point. Plus means move statement provides this "conditional branching" capability to the right and minus means move to the left. Thus 3.4E-6 {the symbol < means "less than or equal to"}. means 3.4xI0-6 or .0000034, and. 7E+9 means. 7xl09 or 700000000. 4030 LET B I 4040 PRINT SQR(B} 4050 LET B B I As we did in the calculation of the X values in the sample 4060 IF B 100 THEN 4040 program, the programmer wi II frequently want to repeat a < calculation in his program several times, varying the quanti­ NoH ce that statement 4060 repeated Iy sends the computer ties in the calculation each time. A repeating operation back to statement 4040 until the upper limit of 100 is ex­ is called an iterative process. For purposes of illustra­ ceeded. When this condition occurs, the computer will not tion, consider a case where the programmer wishes to return to 4040, but will execute the statement following calculate the square root of a number. The hypothetical PRINT statement 4060. The repetitive execution of statements 4040 to 4060 comprises an iterative process or "loop", a commonplace computing technique. Looping will be explained in more 4050 PRINT SQR(100) detail in Chapter 2 in the discussion of the FOR and NEXT statements. will calculate and print the square root of 100 wIth no fur­ ther direction needed from the program. If, however, the This concludes the introduction to BASIC programming. programmer wants the square roots of all numbers from I Chapter 2 explains in somewhat greater detail the features through 100, the PRINT statement wi II have to be rewritten already covered in this chapter, and also presents some ad­ 100 times. The task may be greatly simplified by construc­ ditional statements that are part of the set of elementary ting the set of statements shown below. BASIC statements.

4 A Sample Program 2. ELEMENTARY FEATURES OF BASIC

In the following chapters, certain conventions have been Table 1. Order of Arithmetic Operations adopted for defining the BASIC commands. Capital letters indicate command words that are required in the literal form Order Symbol Explanation shown. Lower case letters are figurative representations of constants, step numbers, etc. Cpmmand parameters enclosed 1 t Exponentiate by braces ({}) indicate a required choice. Parameters en­ 2 * and / Multiply and Divide closed by brackets ([J) are optional. Ellipsis marks ( ••• ) signify optional repetitions of the preceeding bracketed pa­ 3 + and - Add and Subtract rameter. BASIC recognizes the period as a decimal point, not as a terminator. Note that an operator of order 1 or 2 may be followed by an operator of order 3, but that no other cases of consecu­ ELEMENTS OF A BASIC PROGRAM tive operators are permitted.

There are a number of elements common to most BASIC pro­ INTRINSIC FUNCTIONS grams. They are step numbers, simple constants, simple variables, arithmetic operators, expressions, and intrinsic The BASIC system provides a total of 19 intrinsic functi ons. functions. The most commonly used functions are shown in Table 2 below. More advanced functions are explained in Chap­ STEP NUMBERS ter 3. When a function is used in a statement, it must be followed by an expression enclosed in parentheses called the Every statement in a BASIC program must begin with a argument (arg). The value of the argument is either used unique step number. Step numbers range from 1 through directly in the function calculation, or signals the computer 99999 and are ordered naturally, preferab Iy with sufficient to perform the calculation in a predetermined manner. The spacing to allow for insertions to the program. purpose of most of the functions shown below is obvious and familiar. The INT function is often used to acquire the in­ SIMPLE CONSTANTS teger part of a calculated number. For example, INT(A), where A is computed to be 2.675, would produce the num­ A simple constant (that is, a nonvarying quantity) is com­ ber 2. The INT function may also be used to obtain three posed of digits that either stand alone, have an embedded significant digits (with rounding) as in the followi ng example: decimal point, or are preceded or followed by a decimal 50 LET S INT «A * 100) + .5)/100 point. For example, 2, 7.8, .5, and 12 are simple con­ stants in BASIC. When statement 50 is exec uted, Sis assi gned the val ue 2.68. Simple constants may be modified by floating-point nota­ tion, as in 2.5E-15, where the E denotes that the number Table 2. Partial List of BASIC Intrinsic Functions that precedes it is to be multiplied by 10 to the plus or minus power following the E. Accordingly, the number Function Result 2.5E-15 is really the number .0000000000000025. The plus sign "is optional for positive powers. SIN (arg) Calculates sine of argument in radians. COS (arg) Calculates cosine of argument in radians. SIMPLE VARIABLES TAN (arg) Calculates tangent of argument in A simple variable is denoted either by a single letter, or by radians. a letter and a digit from 0 through 9. This convention al­ Calculates arctangent of unitless argu- lows the programmer a total of 286 simple variables. For ATN (arg) example, A and W3 are simple variab.les. Note that if the ment in radi ans. letter-and-digit combination is used, the letter must pre­ Cal culates exponenti al function, that cede the number. EXP (arg) . (argument) IS e ARITHMETIC OPERATORS ABS (arg) Calculates absolute value of argument. BASIC uses common mathematical symbols to denote arith­ Calculates natural logarithm (base e). metic operations. These arithmetic operators are shown in LOG (arg) Table 1 below. The table also shows the order of preced­ LGT (arg) Calculates common logarithm (base 10). ence of the various operations. When no operation takes precedence over another, the computer wi II perform oper­ SQR (arg) Ca leu Iates square root of argument. ations from left to right. The order of operations may be altered by use of parentheses. Use of parentheses is advised INT (arg) Acquires the integer part of the argument. if the sequence of operations seems questionable.

Elementary Features of Basic 5 EXPRESSIONS Note that the LET statement does not define an equality between the variable(s) on the left side of the equal sign The word "expression", sometimes shown in explanations as and the expression(s) on the right side. Rather, LET means expr, represents a simple constant, simple or subscripted that the variable is assigned the resultant value of the variable (see Chapter 3), or function reference, that may expression defined on the right side of the equal sign. stand alone or that may be used in any combination when Statements 15, 20, and 25 of the sample program in Fi gure separated by the symbols for addition, subtraction, multi­ 2 assign values to variables A, B, and C. plication, division, and exponentiation. The components may also be enclosed by porentheses. The symbols + ond - Arithmeti c operations may be performed through use of the may also be the initial character of an expression and moy LET statement. Statement 30 of the sample program in immediately follow a left parenthesis. Some typical expres­ Figure 2 is a good illustration of this type of LET assignment. sions are A + 1 30 LET D2 == B * B - 4 * A * C

(B-X)/D If the user has a series of assignments in his program, he and may string them together in the same line, separating them with commas. Series assignments are made from left to right. (2tX)+ SIN(Y) For example, statements 15, 20, and 25 of the sample pro­ gram could be rewritten as ERROR MESSAGES 15 LET A = I, B = 5, C "" 4 If the computer detects an error in a statement (such as an or alternative Iy, error in the format or a reference to a nonexistent step num­ ber), it will output a message telling the programmer the 15A 1,B 5,C=4 nature of the error and the step number of the incorrect statement. In general, an error prevents execution of the Other uses of LET are shown below. program. The error messages produced by BASIC are shown in Chapter 6. 70 LET T TAN(X)

With these ground rules established, it is now possible to 90 S X t 2, C = X t 3 * SIN(X) examine in detail the commands that constitute the primary part of the BASIC language. The commands are: Besides making a series of assignments as in statement 15 above, a LET statement also may make parallel assignments. LET STOP Parallel assignment occurs when the same value is simul­ taneously assigned to several variables. An example is IF .•• THEN PAUSE shown below. GOTO END 20 P,Al,Q3 4* ATN(l) PRINT REM DATA FOR Statement 20 assigns the value of the expression 4* ATN(l) to P, ta AI, and to Q3. If subscripted variables (see READ NEXT Chapter 3) are used in parallel assignment, the subscripts are calculated before assignment is made.

Series and parallel assignment may both occur in the same DEFINING ARITHMETIC OPERATIONS LET statement, as in

LET The LET statement defines a relationship between 30 P,Al,Q3 4*ATN(1), A=l, B=5, C=4 expressionst in a program. It is of the form Series and parallel assignments should be made for related step [LET] variable[, variable] ••• expr quantities, as a change in one dictates rewriting the entire statement. [,variable [, variable] ••• exprJ •.• where a variable is either a simple variable or a subscripted BRANCHING variable (see Chapter 3). IF ... THEN The IF ••• THEN statement provides a con- ditional branching capability. A conditional branch is a process in which a test is made to determine if some condition is true, and if it is, to branch to and execute some specified statement in the program. When the \ET statements also may make reference to alphanumeric tested condition is not true, the branch does not take place, constants (aconst), which are explained in Chapter 3. and the statement following the conditional branch

6 Defin~ng Arithmetic Operotions/Branching statement is executed instead .. The form of the IF •.• THE N calculation, a message that is in the program, or any com­ statement is bination of these items. The output is produced on a line condition printer, typewriter, card punch, magnetic tape, Teletype, step IF expression expression operotor or other device. The PRINT statement has the genera I form

THEN} step step PRINT [expression(s), or text string(s) {GOTO with commas or semicolons] The condition being tested is speciJied between the IF and the THEN or GOTO commands in the statement. The step where the word PRINT is usually followed by the name of number of the statement to which the computer will be di­ the item that is to be printed. Two sample PRINT state­ rected is specified following the THEN or GOTO command ments from the quadratic equation program in Figure 2 are in the statement. The IF ••• THEN statement may contain alphanumeric constants as well as expressions (see Chapter 3). 60 PRINT Xl,X2 The operators that can be specified in the IF ... THEN state­ ment are given in Table 3. 70 PRINT 'NO REAL ROOTS' Table 3. Condition Operators Statement 60 will print out the calculated values of the Operator Explanation variables Xl and X2. Statement 70 will cause the message enclosed by single quotation marks to be printed out. Note = Equal to that a string of text must be enclosed by either single or double quotation marks. Blanks, which usually enhance the >< or <> Not equal to appearance of text, may be freely interspersed within the string and will be reproduced in the output as presented. < Less than More than one text string may be present in a PRINT state­ ment. Each separate string, however, must be enclosed by > Greater than quotation marks.

<= or Less than or equal to A PRINT statement may contain a reference to an intrinsic function. For example, >= or => Greater than or equal to 1220 PRINT SQR(X) Some sample IF ••• THEN statements are given below. will calculate and print the square root of the variable X, while 400 IF N :: t5 THEN 999 1230 PRINT X; SQR(X) 600 IF SIN (X +H) <=COS(X * G) +E GOTO 250 will print the current value of the variable, followed by its 910 IF W = Y GOTO 15 square root. Besides the· conditional branching capabi I ity of the IF ... THEN statement, BASIC also provides an unconditional PRINT can also contain variables, providing that the vari­ branch, the GOTO statement. abies have been defined in statements preceding the PRINT. The following statement is an example of this use of PRINT. GOTO It is sometimes necessary to alter the normal executing sequence of the program. This change can be 1250 PRINT B * B - 4 * A * C accomplished with the GOTO statement. GOTO takes the form Similarly, the statement step GOTO step Asample GOTO statement is shown below. 1260 PRINT (7/8) t 14 850 GOTO 320 Execution of statement 850 wi II cause the computer to branch wi II give the value of the fraction 7/8 raised to the r4th to statement 320. An attempt to branch to a nonexistent power. step number causes an error message to be output. The word PRINT, used alone in a statement, causes the DATA OUTPUT printer to advance the paper by one line. An example is shown be Iow. PRINT The PRINT statement tells the computer to print.out the current value of a variable, the results of a 4050 PRINT

Data qutput 7 DATA INPUT STOP and PAUSE STOP or PAUSE is used to terminate execution of the program at any point desired by the pro­ The data val ues used in the execution of a program may be grammer. Its step number is printed out when termination contained in a DATA statement. They are called into use occurs. The forms are at appropriate times by the READ statement. READ and DATA are used in combination with each other. One should step STOP not appear in a program without the other to complement it. step PAUSE

DATA DA TA statements form a chained I ist of constants Chapter 4 outlines methods for resuming operation using that the READ statement accesses from left to right, top to direct statements. bottom. t DATA takes the form END The END statement indicates the end of a program. step DA TA [constant]L [constant]] ... Its form is step END Simple constants may be preceded by a plus or minus sign. An empty field after DATA, as in END is treated like STOP and PAUSE. Programs need not contain an END statement and may contain more than one. 1250 DATA REM The REM (Remarks) statement allows the program- or an empty field between commas or after a terminating mer to interject commentary anywhere in the program with­ comma, as in out affecting its execution. REM may be used to identify the compl ete program, or, more important, the function or 1260 DATA 1,2,3,,5, purpose of various sections of the program. REM takes the form 1270 DATA 6,7,8, step REM [commentary] implies a value of zero. Data statements may appear any­ The commentary portion of the statement may include any where in a BASIC program, and do not have to be consecu­ characters up to the end of the I ine. If commentary is tive. However, it is good practice to group the DATA omitted, REM will produce a dummy line in the program. statements near the end of the program, thereby making it possible to add as many statements as are needed to contain Branching to a REM statementisallowed and is recommended the data val ues without disrupting the order of the preced­ when branching to a closed subroutine. Such use of a REM ing statements. statement serves to identify the subroutine. It also allows statements to be inserted at the beginning of the subroutine, READ READ assigns (in consecutive order) the values in if unused line numbers exist between the REM statement and the DATA statement(s) to the variables listed in the READ the first executable statement of the subroutine. statement. The form of the READ statement is

step READ variable [, variable] •.. LOOPING BASIC provides the programmer wi th sti II another method There is no comma following the final variable in the list. for specifying data values for variables. This method de­ fines a loop using FOR and NEXT statements. A loop is a A sample statement is given below. portion of a program written in such a way that it will exe­ cute repeatedly until some test condition is met. A FOR 555 READ B,C, D and NEXT loop causes execution of a set of steps for suc­ cessive volues of a variable until a limiting value would be If a READ statement requests data after the list of constants exceeded. Such values are specified by establishing an in the DATA statement has been exhausted, execution of initial value for a variable together with a limit value, and the program ceases and a message is output to the program­ on increment or decrement that is used to modify the vari­ mer advising him of the out-of-data condition. able each time the loop is executed. When the limit is ex­ ceeded,an exit condition built into the loop allows the com­ MISCELLANEOUS STATEMENTS puter to proceed to the following body of the program. FOR and NEXT loops, therefore, have three main components: The material covered up to this point is all the beginning programmer needs to know to write fairly complex programs 1. An initial value expression for the variable used by the except for one essential - some way to tell the computer to formulQ. stop processi ng the program. There are three ways to accom­ 2. A limit value expression beyond which the varioble plish this in BASIC; the STOP and PAUSE statements and the may not be incremented (or decremented). END statement. 3. An optional increment or decrement expression value tThe DATA statement may also contain alphanumeric con­ to be added to (or subtracted from) the value of the vari­ stants (aconst) which are explained in Chapter 3. able for each pass through the loop (except the lost).

8 Data Input/Miscellaneous Statements/looping FOR The FOR statement defines loop parameters. It of the variable X and the result of 2X. Statement 70 causes gives the initial value of the variable, the expression for the computer to return to statement 50, where it pi cks up the limit value which the variable may not exceed and the next value of X, that is +5. The computer then prints which causes the loop to terminate, and (optionally) the 5 and 32 and again goes to NEXT which returns it to FOR. increment or decrement expression. If the step increment When X attains the limit value of 11, statement 60 will be or decrement is not expressly given in the FOR statement, executed and control wi II pass to 70. The computer wi II it is assumed to be +1. The FOR statement tokes the again try to increment X by 3, but as the upper limit of form variable X will have been reached, the computer will "fall through" statement 70 and control wi II pass to the next step FOR simple variable expression TO statement. At this point, X will have the value II, the last value which does not exceed the terminal value. expression [STEP expression] Loops may be contained within other loops (nested), but The expression preceding TO specifies the initial value of the loops may not "cross". This exclusion is illustrated in the variable, the expression following TO gives the limiting Figure 4 below. value, and the expression following STEP gives the incre­ ment or decrement. The computer evaluates the initial value expression only once, when the FOR statement is FOR W executed. The other two expressions are also evaluated when FOR is executed, but, additionally, are reevaluated correct -----l---.J FOR X every time the NEXT statement is executed. A sample FOR NEXT X statement is shown below in the discussion of NEXT. FOR Y NEXT The function of the NEXT statement is to return FOR Z the computer to the beginning of the loop (FOR) after a incorrect new value of the simple variable has been computed. Its NEXT Y form is NEXT Z step NEXT simple variable NEXT W

Note that the simple variable in the NEXT statement must be specified exactly as it appeared in the FOR statement. Figure 4. Nested Loops

The easiest way to understand a FOR and NEXT loop is to follow one through its entire sequence of operations, as in BASIC allows loop nesting to 26 levels, that is, the BASIC the following statements. program may contain no more than 26 FOR statements whose corresponding NEXT statements have not yet been encoun­ 50 FOR X = 2 TO 11 STEP 3 tered in compilation. 60 PRI NT X, 2 t X Chapter 2 has presented the beginning programmer with a 70 NEXT X sufficient number of BASIC statements to generate a wide variety of fairly complex computer programs. When the Statement 50 sets the initial val ue of X to 2 and specifies programmer has developed a comfortable level of profi­ that X thereafter will be incremented by 3 each time the ciency with these statements, he is urged to toke advantage loop is performed until X has the limiting value 11. State­ of the more sophisticated features of the BASIC system that ment 60 causes the computer to print out the current value are presented in Chapter 3.

Looping 9 3. ADVANCED FEATURES OF BASIC

For simplicity, explanations in previous chapters have As a further example of matrix notation, consider the fol­ covered only the essential features of BASIC program ele­ owing table, which lists expenses for a four-day car trip. ments. This chapter contains additional information on these Column 2 3 4 elements and also explains advanced features of BASIC.

June 5 June 6 June 7 June 8 OTHER ELEMENTS OF A BASIC PROGRAM Row ~Item The additional program elements presented below give the Gas, oil 21.29 20.84 19.42 6.08 user greater flexibility in using the statements explained in Chapter 2, and also augment the capabilities of the new 2 Tolls 1.32 .86 .40 .07 statements described in this chapter. 3 Food 11. 18 12.83 14.39 5.06

ALPHANUMERIC CONSTANTS 4 Lodging 10.05 12.78 10.35 .00 5 Misc. 1.35 .44 .90 .10 Besides the simple constants previously explained, BASIC also contains alphanumeric constants (aconst). An alpha­ If we consider the table to be a matrix called E, the amount numeric constant is a combination of up 'to six characters, ($10.05) spent for lodging on June 5 would be represented including blanks, enclosed by single or double quotation by E(4,1), and the amount ($5.06) spent for food on June 8 marks. If the alphanumeric constant is enclosed by single would be represented by E(3,4). quotes, a single quote may not appear as one of the six ADDITIONAL INTRINSIC FUNCTIONS characters of the alphanumeric constant. A parallel con­ dition exists for use of the double quotes. Terms such as The additional intrinsic functions presented in Table 4 pro­ "HANGUP" and '123GO' are examples of alphanumeric vide the programmer with greater flexibility in writing pro­ constants. An alphanumeric-constant val ue may be assi gned grams and eliminate the need for redundant programming of to any variable via LET, INPUT, READ, GET, MAT READ, these common procedures. A complete list of BASIC intrin­ MAT INPUT, or MAT GET statements, and may be tested sic functions is given in Appendix C. via the IF statement, as in All intrinsic functions, except for MAX and MIN, require 15 IF X = "NO" GOTO 99 exactly one argument. MAX and MIN functions require a list of two or more arguments separated by commas, as in Alphanumeric values are meaningfully compared only for MAX(lOO,X,SQR(Y)). The SGN function is useful in finding equality or inequality. the sign of a computed value. TAB is often used for printing out data in columnar form. PRC indicates the extent of pre­ SUBSCRIPTED VARIABLES cision required for output of numeric quantities. Arguments In addition to simple variables, BASIC also provides for of zero for DAY, TIM and YER produce alphanumeric results. subscripted variables. A subscripted variable denotes an DAY, TIM, and YER with arguments of zero, and TAB and element of an array, that is, a list or table of data. The PRC should not be combined with other elements to form individual values within the array are called array ele­ expressions. That is, if such a function appears in an ex­ ments. We refer to an array element by specifying the name pression, it must be the only term in the expression. of the array (always a single letter) and the position of the Table 4. Additional BASIC Intrinsic Functions element in the array. For example, the fourth element in the array named L is denoted by L(4). The value inside the Function Resu It parentheses is called the subscript, and is represented byan expression that can be reduced by the computer to a single SGN(arg) Identifiesalgebraic sign of argu- integer value. (Subscript expressions are evaluated to in­ ment, and producesa -1 for nega- teger value after adding 2-20.) Subscripts range from 1 tive arguments, a 0 forO, and a through the maximum allowed dimensioned value. +1 for positive arguments. Arrays can have either one or two dimensions. A one­ RND(arg) Produces, for each call, the next dimension array is called a vector and is characterized by element of a sequence of uni- a single subscript. The subscript denotes the position of the formlydistributed random numbers desired array element in the list of data. Sample vector that are greater than 0 but less array elements are A(l) and B(J + 3). than 1. If arg is 0 for the first When an array has two dimensions, it is called a matrix. RND call of a program, the iden- Data in a matrix is thought of as being arranged in rows tical sequence of random numbers and columns. Each element in a matrix is identified by two wi II be generated if the program subscripts separated from each other bya comma. The first is rerun and arg is not changed. subscript specifies the row number and the second specifies Otherwise, an unrepeatable se- the column number. For example, C(K, L) and D(M+2,N+3) quence will be generated. denote matrix array elements.

10 Advanced Features of BASIC Table 4. Additional BASIC Intrinsic Functions (cont.) REGULAR FORMAT Function Result When the regular format is specified by using commas to DAY(arg) Supplies the calendar day. Ifthe separate the elements in the PRINT statement, the print argument is 0, the output form is line is thought of as consisting of a series of 14-character mon dd, as in MAR 07. If the fields. Each comma causes a shift to the next field. For argument is nonzero, the output example, form is a floating-point number 4040 PRINT A, B, C whose integer part represents the month, and whose fractional part will cause the values of A, B, and C (from the sample pro­ represents the day of the month gram) to be printed at 14-character intervals, as in divided by 100. For example, 5 4 3.07EO represents March 7. ,., When the regular format option is specified, at least two TIM (a rg) Suppl ies the time of day. If the blanks follow the last printed character. In some cases, argument is 0, the output form is this spacing may cause an extra field shift. hh:mm, as in 15:09. If the argu­ ment is nonzero, the output form is a floating-point number whose PACKED FORMAT integer part represents the hour and whose fractional part repre­ Packed format, which is specified by using semicolons to sents the minutes divided by 60. separate the elements in the PRINT statement, causes the For example, 15.15EO represents printed output to be compressed on the page by reducing 3.09 PM. the spacing between fields. Each semicolon causes a field shift that is either two or three positions in length, so that YER(arg) Suppl i es the year. If the argu­ the shift reaches an even-numbered position. For example, ment is 0, the output form is19yy, statement 4040 above could be written as as in 1969. If the argument is nonzero, the output form is a 4040 PRINT A;B;C floating-point number whose value is equal to the year, as in with a resul tant output of 1969.0EO. 154 Selects the maximum value in the It is important to note the di fference between the TAB func­ I ist of arguments. tion and the output format characters. TAB causes output Selects the minimum value in the to be printed at a specified position, and is most useful in I ist of arguments. providing columnar output. The output format characters (, and ;) cause the output to be printed at intervals that TAB(arg) Advances the print device to depend on the number of preceding (printed) characters. the column designated by the argument and should only be An example of TAB function use is shown below. The log­ used in a PRINT statement. in procedure and meaning of the "greater than" sign (» are TAB cannot be used to back­ explained in Chapter 4. Note that the semicolon after space the print device. TAB(4) in statement 60 does not affect the printed output. !BTM/1 IS ON THE AIR PRC(arg) Specifies the number of signifi­ 12/17/'68 11:45 cant digits in printed output, and !LOGIN: YZ is only used in a PRINT state­ ! BAS IC ment. A 0 argument specifies 6- >10 LET X=-l, Y=l significant-digit output format, >20 PRINT "123456789" and a nonzero argument specifies >30 PRINT X 16-significant-digit output. >40 PRINT TAB(4),X >50 PRINT TAB(4),Y PRINT FORMATS >60 PRINT TAB(4);Y >99999 END A line of printed output contains a number of print positions >RUN numbered from left to right. Punctuation marks in the 11:47 12/17 PRINT statement - commas and semicolons - define the 123456789 desired appearance, or format, of the printed output. The -1 punctuation marks tell the print device at which position -1 to start printing. BASIC has two types of output format, 1 regular and packed. Regular format is specified by using 1 commas to separate elements in the PRINT statementi packed format is specified by using semicolons. 99999 HALT

Other Elements of a BASIC Program 11 If a PRINT statement ends with a punctuation mark, the ap­ Use of PRC is shown below. Note that the PRC designation propriate field shift takes place and subse!:juent printing starts remains in force unti I changed by another PRe. This example at that point on the same print I ine. Otherwise, subsequent a Iso ill ustrates the appearance and use of di rect statements printing starts on a new line. All printing is left-justified (see Chapter 4). in its field. If a field shift places a field in a position to >LET I~1/30 extend beyond the last allowed print position, a new line is >PRINT I generated and the field is printed on the new line. 3.33333E-02 >PRINT PRc(l),I This pro·cedure is modified when printing text. If a text 3.333333333333333E-02 string overflows the last position, the string is truncated at >PRINT I that point and the remainder is printed on the next line. 3.333333333333333E-02 Text strings may extend beyond any number of field bound­ >PRINT PRC(O);I aries •. It is permissible to have neither a comma nor a semi­ 3.33333E-02 colon on either side of a text string in a PRINT statement, > but no spacing wi II occur before or after the string in the > printed output. !BYE 12/17/'6811:49 Format characters may be used alone in PRINT statements, or they may be used in any number and combination to cause The rest of this chapter will be devoted to explanations of appropri ate field shifts. the remaining BASIC statements. They are: INPUT PUT NUMBER RANGES RESTORE GET GOSUB CHAIN Common inputs to and outputs from the computer are numbers. RETURN DEF Because they are often modified during the computing pro­ ON DIM cess, the appearance of input numbers and output numbers GOTO .•• ON PRINTUSING may differ. OPEN Image CLOSE MAT BASIC handles input numbers that are within a certain range of values. The legal interval for magnitudes of numbers is There are 15 variations of the MAT (matrix) statement 75 from 5.398 x 10-79 through 7.237 x 10 , and zero. above. These variatians are designed to handle the many matrix operations. Some familiarity with matrix theory is Output numbers are printed in fields of varying widths across assumed in the explanations. the page according to the following rules.

1. Numbers are left-justified in their fields. EXTERNAL DATA INPUT 2. Positive numbers are preceded by a blank, negative numbers by a minus sign. INPUT The INPUT statement requests .data from a source that is external to the program, that is, Teletype unit, 3. If the number is a whole number (integer) whose magni­ 9 card reader, canso I e, or other input device. (INPUT differs tude is less than 1,000,000,000 (10 ), it is printed in from READ in that when using READ, the DATA statement from 1 through 9 positions after a blank or a minus. and its data values are contained within the program itself.) 4. If the number is nonintegral or its magnitude is greater Data may be stored in an external medium for two reasons: than or equal to 109 (for example, -10.5, .5, 123.45, either the data is unknown when the program is written but ar 10 12) its most significant part will be rounded to 6 wi II be suppl ied when the program is run, or the amount of or 16 digits according to the PRC function and will be data is too large for inclusion in the body of the program. treated as follows: The INPUT statement takes the form a. If, after rounding, the absolute value of the num­ step INPUT variable Gvariable]. .. ber is greater than or e!:jual to 0.1 but less than 106 or 10 16, the number is printed, in 8 or 18 There is no comma following the final variable in the list. print positions, in fixed-point notation; that is, its Wheh the INPUT statement is executed, data values are form will be a blank or minus, a maximum of 6 or read into the computer from the external storage medium 16 integer digits, followed by the decimal point and are assigned, one at a time, to the variables designated and a maximum of 6 or 16 digits. in the INPUT statement. It should be emphasized that data is stored as it is received, and that the variables are satis­ b. If, after rounding, the absolute value of the num­ fied (that is, associated with the data) in the order in which 6 ber is less than 0.1 or greater than 10 or 10 16, they are specified. Some sample INPUT statements are shown. the number is printed in floating-point (scientific) notation; that is, its form will be a blank or minus, 100 INPUT X the most significant integer digit, a decimal point, 110 INPUT A,B,Z,Y,R3 5 or 15 dec i mal dig its, foil owed by the letter E, a 120 INPUT B(l,N) ,C(N),N plus or minus, and a 2-digit exponent. 130 INPUT N ,B(l,N) ,C(N)

12 External Data Input Every time statement 100 is executed, the computer will source input and, because of its form, will cause supply a data value to the variable X. Statement 110 will an error message (e. g., BAD FORMAT). supply data values to A, B, Z, Y, and R3, in that order, from the list of data supplied by the programmer. State­ In the batch mode, with input data via the card reader, ments 120 and 130 will very probably not be equivalent, if there are unused data cards at the end of program execu­ even though the same variables are specified in both. They tion, a Monitor error message wi II resul t and any remaining will not be equivalent even if the data values are supplied activities prior to the next job card will be aborted. in the same order as the variables were given, unless the value of N is not changed by execution of either of the INPUT statements. REREADING DATA The data values (simple and alphanumeric constants) that satisfy the variables in INPUT are contained in a list of RESTORE The RESTORE statement alters the normal data, separated by commas. If the list begins with a comma sequence of DATA statement accession. DA TA statements (or in the case of successive commas), the computer under­ are normally accessed as the preceding DATA statement is stands that a data value of zero precedes the comma. For exhausted. For example, of the following set of DATA example, the computer interprets statements,

,5,3,4 100 DATA 1,2,3,4

110 DATA 5,6,7,8, as meaning the data values 0, 5, 3, and 4. Similarly, if the list ends with a comma, as in 120 DATA 9, 10, 11, 12

1,2,3, statement 110 wi II be accessed on Iy after data va I ue 4 in statement TOO has been assigned to a variable, and state­ the computer will assign to the variables in the INPUT ment 120 will be accessed after data value 8 in the statement the data values 1,2,3, and O. Finally, the list preceding statement is assigned. RESTORE allows the programmer to alter this sequence by directing the computer (via a step number) to a specified DATA statement from which data accession will proceed in the normal manner. will be interpreted as data values 5, 1,0,5, I, and 2. The RESTORE statement is frequently used for accessing data that will be used several times in the program, and After the entire list of variables in an INPUT statement is eliminates the need for writing duplicate DATA statements satisfied, control passes to the next program statement. If, when the same data is to be accessed more than once. The at that time, the current line of input values has not been form of the RESTORE statement is exhausted, the remaining values will be accessed by the next INPUT statement executed. step RESTORE [step]

If the input line shown above are entered in response to where the second "step" must be the step number of a statement 100, etc., and N == 2 prior to executing state­ val i d DA T A statement in the program. Some samp I e ment 100, the result is as follows: RESTORE statements are given below.

x =0 740 RESTORE 125

A==5 B 3 Z 4 Y R3 = 2 900 RESTORE

B(I,2) == 3 C(2) 0 N 5 If the step number is omitted in the RESTORE statement (as in step 900 above), the computer will return to the first N == 1 B(1, 1) 0 C(1) == 5 DATA statement in the program.

The values 1 and 2 are pending for any subsequent INPUT statement. BRANCHING TO A SUBROUTINE

Note: In BTM on-line BASIC, with INPUT via the users GOSUB and RETURN The GOSUB and RETURN state- console, if a portion of an input line is unused at ments provide subroutine capability in BASIC. A sub­ the end of execution, it will be interpreted as new routine is a section of the main program that completes a

Rereading Data/Branching to a Subroutine 13 specific task. GOSUB, in the main body of the program, a value of 3 for I will direct the computer to step number di rects the computer (vi a a step number) to the fi rst state­ 500, and a value of 1 will direct it to step 300. If the ment of the subroutine. After the subroutine has been computed expression does not equal the position of a step executed, RETURN directs the computer to the statement number in the I ist, control passes to the next statement in following GOSUB, where the main program continues. The the program. Notice that there is no comma following the form of GOSUB and RETURN are fi nal step in the list.

step GOSUB step GOTO ... ON The GOTO ... ON statement is similar to the ON statement in operation. The form ofthe GOTO •.. step RETURN ON statement is where RETURN is the last executed statement of the subroutine. step GOTO step 1,step 2, •.• ,step n ON expression

Some sample GOSUB and RETURN statements are shown Some samples are shown below. below. 10 GOTO 80,80,70,99999 ON I

10 GOSUB 500 30 GOTO 55,65,75 ON 1-2

525 RETURN FILE MANIPULATIONS A file is a collection of items treated as a single unit. It Notice that the RETURN statement does not contain the step is necessary for the computer to recognize distinct files and number of the statement following GOSUB - the computer to manipulate them in an organized manner so that files be­ remembers its place in the program. longing to different programs are not discarded or combined. The four BASIC statements OPEN, PUT, GET, and CLOSE An attempt to execute a RETURN statement before a GOSUB provide this file-manipulating capability (see also MAT statement is executed causes output of an appropriate error PUT and MAT GET). message. Execution of too many GOSUBs before a RETURN also causes an error message to be printed. The pro­ gram may execute up to 20 GOSUB statements before a OPEN The OPEN statement performs the following file RETURN is needed. management functions: 1. Designates that the named file is to be used for input (I) or output (O). MULTIPLE PATH BRANCHING 2. Positions the named file at its start point. The programmer has several methods for altering the exe­ 3. Appends an end-of-file mark to the open output file cution sequence of a program. One of the most commonly before positioning the file at its start point. used is the IF .•. THEN statement. However, if many dif­ ferent branches are to be taken according to certain criteria, 4. Closes (with an end-of-file mark) an output file when inclusion of an IF ••• THEN statement for every branch be­ the statement spec ifies that a second fi Ie is to be an comes unwieldy. To overcome this inconvenience, BASIC output fi Ie. provides the programmer with a means for selecting the 5. Closes an input file when a subsequent OPEN state­ desired branch according to the computed value of a speci­ ment specifies that a second file is to be an input fied expression. This type of branchisaccomplished through file. use of the ON or the GOTO ••• ON statement. If the named file is being opened for input, the assump­ ON The ON statement directs the computer to the step tion is that the file exists and that it contains data to number that is specified in the expression portion of the be read by the user's program. If the named file is be­ statement. ON takes the form ing opened for output and if such a file exists, it is opened so that data can be written into it. However, if it does not exist, an output file will be established, step ON expression. {GOTO}THEN stepl,step2, ... ,stepn given the name (and optional password) specified in OPEN, and opened for output.

where "expression", after it is computed to an integer value, Noti ce that functions 4 and 5 precl ude the possibi I ity of represents the position of the desired step number in the list having more than one fi Ie open for input and more than one of step numbers that follows GOTOorTHEN. For example, other file open for output at one time during execution. in the sample statement below, When a file is opened for output and a PUT or MAT PUT statement is executed, data is sequentially placed in the 100 ON I GOTO 300,400, 500 open output file. Information about the nature of the data, Lposition 3 such as whether it isfromanarrayormatrix, is not included. Lposition 2 Thus, if the file is subsequently opened for input, the data l position 1 is accessed sequentially from the start of the file.

14 Multiple Path Branching/File Manipulations The OPE N statement takes the form where I designates the input file and 0 designates the out­ step OPE N name [;password] put file. It is recommended that output files be closed as soon as practical to conserve memory space. Executing a 1'V1r'f'I"'l,pr~ to end of line] CLOSE statement when there is no 'open input or output fj Ie is not considered an error and has no effect on the program. where name refers to the name of a file that is external to PUT The PUT statement enters data into the currently the current BASIC program. An external name takes the open output fi Ie. The data may be read at a later time by form of an alphanumeric constant (in quotes) or a simple either the current BASIC program or subsequent BASIC pro­ variable (containing an alphanumeric constant). grams. The form of the PUT statement is The name may optionally be followed by a password and, for ste PUT{expreSSion} [,f expressiOn}] ••• input files only, an account number. The further designa­ p aconst aconst tion of password and account number reduce the chances of a file being inadvertently opened and possibly destroyed by where the data values to be entered into the file may take another program accessing a file with the same xname. (For the form of an expressionoran alphanumeric constant. There further information, see" File operations", Chapter 4.) Both Is no comma following the final expression or aconst in the of these items may take the form of either an alphanumeric I ist. Some sample PUT statements are shown below. constant or of a simple variable whose value is alphanumeric 880 PUT "CLOUDY",55J2 when the OPEN statement is executed. The password must be preceded byasemicoloni the account number, by a colon. 881 PUT TIM(X),DAY(Xt YER(X) File name musHoliow the keyword OPEN, and the account 882 PUT FNH(Al) + P * Q and/or password designators must follow file name. If both account and password are specified, the order of their ap­ The FNH in statement 882 is an example of a user-defined pearance is optional. Account numbers may not be used in function. These are explained below under "User-Defined output OPENs. Functions". The comma before I or 0 is optiona I. Ei ther the I or the o must be shown to designate input or output file, but the If an error occurs in transferring data to the output file, or if no output fj Ie has been opened, execution of the user's letters may be followed by any characters up to the end of the line. Some sample OPEN statements are shown below. program terminates with an appropriate message. (An out­ put file created without a password is temporary and exists 12 OPEN "MASTER" INPUT only for the duration of the JOB in which it was created.) 13 OPEN Xl,OUTPUT GET The GET statement retrieves data prepared by a 25 OPEN "FILEX":' ACCT33' ;"FRIEND"IN previously-executed BASIC program or by the current pro­ gram. Data is assigned to specified variables as it is re­ 95 OPEN XII ceived from the currently open input fi Ie. GET is of the form 96 OPEN 'MASTER', 0 step GET variable~variable] .•. 100 OPEN 'NAME';' PASS';' ACCTO I' I where the variables may be simple or subscripted variables. All output files are declared to be Hiles (temporary files) There is no comma following the final variable in the list. at the time the OPEN .•. 0 statement is executed. Hiles An attempt to read nonexistent data terminates execution are released at the end of the current job unless(l) the files of the program with output of an appropriate message. This were closed and (2) a password was specified at the time they situation may arise when were opened. Closing is accomplished by subsequent execu­ 1. No input file is open. tion of a CLOSE 0, or an OPEN ••• Ostatementl or by an OPEN ••• I statement for the file in question. Specifying a 2. The open input file is empty. password in the OPEN ••• 0 statement exempts a file from 3. An end-of-fi Ie condition occurs. the temporary-file procedure, subject to the aforementioned requirement that the file be closed. AdditionallYI the program will be terminated and an error In BASIC, a closed file cannot be extended. Reopening a message will be output if an error occurs in reading the data. fi Ie for output results in the deletion of the fi Ie with that name in the logged-on account. OPEN, CLOSEI PUTI GETI MAT PUT, and MAT GET permit the computer to access and to create fi les that are external The next three statements permit the BASIC programmer to to the currently-operating program. BASIC also provides close files, to store information in, and to get information the programmer with a device for successively executing a from an open fi Ie. series of programs thraugh use of the CHAIN statement.

CLOSE The CLOSE statement doses the currently open input or output file. The form of the CLOSE statement is RUNNING CONSECUTIVE PROGRAMS

CHAIN CHAIN directs the computer to acquire and step [characters to end of line] CLOSE{~} run another program of a series of programs without further

Running Consecutive Programs 15 action by the programmer. The format of the CHAIN state­ The computer checks DEF statements for identical simple ment is variables in the list of dummy arguments, undefined func­ tions, multi-defined functions, and consistency between the step CHAIN name [ipassword] [:acct no] number of arguments suppl ied by the programmer when the where name (and, optionally, password and acct no) is the function is called (referred to) and the number of arguments identity of a program as defined in the discussion of the in the DEF statement. However, it is the responsibility of OPEN statement. the programmer to avoid circular definitions in and among the DEF statements. Improper uses of DEF are shown below. When executed, CHAIN produces the following results: Case 1. Circular definition within statement 1. The current program is discarded, but the values of its variables are and 1200 DEF FNA(X) x + FNA(X)

2. The named program is obtained, compiled, and executed Case 2. Circular definition among statements if possible. 1400 DEF FNA(X) X + FNB(X) Note that only the simple variables computed by the pro­ 1450 DEF FNB(X) X * FNC(X) gram are retained when CHAIN is executedi all array values 1500 DEF FNC(X) FNA(X)/X and dimension information are lost. (See" Dimensioning" later in this chapter.) A sample CHAIN statement is shown below. DIMENSIONING 950 CHAIN II PART2" :A;P A dimension is the largest value that a subscript may attain for a given subscripted variable (array). This limit tells the USER-DEFINED FUNCTIONS computer how many storage units of the computer's memory DEF If the programmer wants to make use of a function to allocate for the array. Dimensions are specified explic­ that is not included in the set of BASIC intrinsic functions, itly in the DIM statement, but the user may make array refer­ ences wi thout correspondi ng DIM statements. In such cases, or if he intends to make repeated use of an involved expres­ implicit dimensions are used. Implicit dimensions are: 10 sion, he may define the function in a DEF statement and storage units for a vector, and 100 storage units for a matrix make reference to it according to a name he designates. The form of the DEF statement is (that is, a 10 by 10 matrix). If the program uses MAT state­ ments (explained later), the dimensions of all arrays referred to in these statements must be explicitly defined in DIM step DEF FN letter(simple variable ~simple variable] statements . . . . ) = expression DIM There are three reasons for explicitly specifying where the letter following FN provides a unique name for the dimensions of an array: the function. There is no comma following the final simple 1. The user may wish to allocate more space for his array variable in the list. The simple variables appearing in pa­ than allowed by implicit dimensions. Thus, DIM A(18) rentheses to the left of the equal sign are dummy arguments. wou Id reserve 18 storage un i ts for the vector A. That is, they only serve to identify which of the simple variables in the expression to the right of the equal sign are 2. The user may wish to restrict the reserved storage space arguments. There must be at least one such argument, al­ for each array to its exact dimensions, thereby conserv­ though it is not necessary that any or all of the arguments ing space. For example, DIM B(3,4) reserves 12 storage appear in the expression. Each time the function is evalu­ units for matrix B, thereby leaving for other use the re­ ated, current argument val ues will be substituted for these maining 88 units that would have been allocated by im­ terms in the expression. The following examples illustrate plicit dimensions. typical DEF formats. 3. The user may wish to use a given array in a MAT statement. DEF FNA(X) X+B*X 65 The DIM statement takes the form 100 DEF FNB(X) X * SIN(FNA(X + C» step DIM letter{dimx [,dimx]), ~letter{dimx[,dimxJ)J. .• 120 DEF FNX(XO,Xl,X2) = XO*X1 *X2/K where each letter is the single-letter name of the array be­ 550 X FNX(1,2.3)+FNB(y + 3.14) ing dimensioned, and each dimx is a dimension expression that denotes the maximum number of row or column elements Line 550 is an example of how the functions defined in lines in the array. Dimension expressions may not contain user­ 100 and 120 might be used later in the program. The vari­ defined funetions, array references, letter digit variables, able X to the left of the equals sign is a different entity from or letters that have not been set (see "Parameter Setting" or the dummy variables X in the DEF statements. Figure 6, Chapter 4), and are evaluated during compilation (not during execution) by truncating to an integer value after DEF statements may appear anywhere in the BASIC program, adding 2-20• If dimensions for more than one array are including those cases in which the function is referenced specified in a DIM statement, they are separated by commas. prior to its definition. A given array may be dimensioned only once in a BASIC

16 User-Defined Functions/Dimensioning program via a DIM statement. DIM statements may appear 3. The decimal point is denoted by a • symbol. For ex­ anywhere in a BASIC program. A sample DIM statement is ample, the statements given below. 3: 11 •11 AND -.1111 ALSO +111111. 10 DIM M(3,3),V(128) 23 PRINTUSING 3, 1.2, -1/4, 100.453 PRINT IMAGES will generate 1.2 AND -.25 ALSO+ 100 For added flexibility, BASIC provides the user with another method of specifying the final appearance of printed output. 4. If a field contains a decimal point, the user may also The technique uses combinations of PRINTUSING and Image append four trailing exclamation points to signify statements. floating-point notation. (If more or fewer than four exclamation points are shown, they will be printed lit­ PRINTUSING The PRINTUSING statement supplies erally in the output.) BASIC determines the need for parameters that are to be "inserted" into the referenced floating-point notation according to the rules given for Image statement. PRINTUSING takes the form the PRINT statement. The four! 's provide for a letter E, a plusorminus sign, anda two-digit exponent. Note step PRINTUSING stePGexpression(s) or text string(s)] that a decimal point may be placed anywhere in the where the step number that follows the command word desig­ field, but that, on printing, it will follow the first digit. nates the Image statement into which this PRINTUSING's The position of the floating-point notation remains un­ parameters will be embedded. A sample PRINTUSING changed. For example, the statements statement is shown below. 98 PRINTUSING 99, 1/30,2/30 50 PRINTUSING 75,X,SQR(X),'SQ. ROOT' 99:VALUES ARE 1I.1I111!!! AND +111111. !!!! APPX.

The parameters of statement 50, that is, the current value will generate of X, the square root of X, and the text string 'SQ. ROOT', VALUES ARE 3.33E-02 AND +6.66E-02 APPX. will be embedded, from left to right, in the designated fields of statement 75 (a field is a group of character posi­ 5. Except for the II, period, and! symbols, characters that tions that is treated as a distinct unit). Note that commas followthecolonwill be printed exactlyasshown, with are used to separate parameters in PRINTUSING. spacing as provided by blanks in the Image stateme;:;t:" 6. Text'strings may be inserted in fields containing deci­ : The Image statement (characterized by a colon after mal points or specifying floating-point notation. In the step number) complements the PRINTUSING statement addition, if the field is preceded by an algebraic sign, in that Image statements depict the final printed appearance its position will be preempted by the text string. For of PRINTUSING parameters. An Image statement is of the form example, the satements step: [lis and/or characters to end of line] 11 :THE VALUE IS -11. 11111111 where the characters that follow the required colon are gov­ 47 PRINTUSING II, "TOO BIG" erned by the following rules. will generate 1. Eachdigit positionisdesignatedbyallsymbol. Also, text THE VALUE IS TOO BIG strings to be derived from the PRINTUSING statement are indicated by II symbols. For example, the statements If a text string is larger than its corresponding field, it will 50 PRINTUSING 75,X,SQR(X),'SQ. ROOT' be truncated on the right. 75:IF X II, II IS ITS 1111111111111111 In addition to the above rules, printing is subject to the will generate the following output (assuming X is cur­ followi ng conventions. rently 4): 1. If the field to the left of a dec imal point is not large IF X 4, 2 IS ITS SQ. ROOT enough to contain a numeric value, asterisks are in­ serted in the printed output as a warning to the pro­ 2. If a field is preceded by a plus sign, positive values are grammer. For example, the statements preceded by a plus sign and negative values by a minus sign. On the other hand, if a field is preceded by a 50 PRINTUSING 75,X,SQR(X),'SQ. ROOT' minus sign, positive values are preceded by a blank, 75:IF X =' 11,11 IS ITS 1111111111111111 negative values by a minus sign. For example, the statements will generate, assuming an X value of 25, 5: _1111, _1111, +1111, +1111,1111 IF X *, 5 IS ITS SQ. ROOT 14 PRINTUSING 5, -19, +20, -21,20,99 Also, if a negative value is associated with a field containing no sign position, a minus will appear in wi II generate the first position, and any remaining field positions -19,20, -21, +20,99 will conta i n asteri sks.

Print Images 17 2. If an Image field is larger than necessary, the printed of the same letter to designate a simple variable.) Current output will show blanks preceding expression values and dimensioning may not exceed absolute dimensioning. Ma­ following text strihg values up to the required number trix operations and their corresponding MAT statements are of positions in the field. presented below.

3. If a PRINTUSING statement specifies more values than PRINT there are fields in the complementary Image statement, the Image statement is repeatedly used until all PRINT­ The MAT PRINT statement prints arrays in regular or packed USING values are printed. For example, the statements format. The form of the statement is 8: N = ##11#11 step MAT PRINT aname [{;} anamel- . [;] 90 PRINTUSING 8, 1, 4, 90, 81777 wi II generate where aname is the letter designation of an array that has been dimensioned in a DIM statement. Some sample MAT N= I PRINT statements are shown below. N= 4 1000 MAT PRINT A, B; C 90 N 1001 MAT PRINT D; N = 81777 There are two types of print formats, regular, or pocked. 4. If a PRINT USING statement specifies fewer values than An aname parameter followed by 0 semicolon causes the there are fields in the complementary Image statement, named array to be printed in packed format. Otherwise, the printout will be terminated at the first unused field regu lar format is used. Statement 1000 wi II cause array A of the Image statement. For example, the statements to be completely printed before any element of array B is 9: 11 11#11#11# CASES 11#.1/ RESULTS printed. Array A will be printed in regular format, array B in packed format, and array C in regular format. Current 103 PRINTUSING 9, 'NO MORE' dimensions are used to determine how much data is printed wi II generate from an array. Statement 1001 will cause array D to be printed out in packed format. NO MORE CASES Vectors are printed in row fashion. Each row of a matrix Whenever a PRINTUSING statement is executed, printing is printed as one or more consecutive print-rows with a starts at the left of a new line. Values are rounded approx­ blank line between successive matrix-rows. Column I of imately prior to printout. Although the programmer may a matrix always occurs in the leftmost print field. specify numeric fields greater than 16 characters in length, only 16 significant digits are output (with trailing zeros to fi II out the field) for the fractional part of values. PUT

MATRIX OPERATIONS The MAT PUT statement enters arrays into the currently open output fj Ie. It takes the form Matrix operations in BASIC are controlled through use of a step MAT PUT aname &anameJ •.• special set of MAT statements. In addition to the usual set of allowed matrix manipu lations, SDS BASIC provides op­ There is no comma following the final array name in the list. tions for input of matrixes via console or file, copying of In the sample statement below, matrixes, and the solution of simultaneous equations. Some 1002 MAT PUT A,B of the matrix operations apply to vectors as well as to matrixes. At times, vectors are treated as either row or array A will be completely output before array B is output. column matrixes. Current dimensions determine how much data is output from a given array. Matrixes are entered into output files in row MA T statements may be specified to use variable dimensions, major sequence, that is, with the last subscript varying as long as these are within the dimension limits specified most rapidly. in DIM statements. In some cases, dimensions will vary because of the operations that are performed on them (for GET example, multiplication of nonsquare matrixes). Thus, there is current dimensioning (the result of the latest matrix oper­ The MAT GET statement reads array values from the cur­ ations, or as specified by the user in MA T SIZE statements), rently open input fi Ie. It complements the MAT PUT state­ and absolute dimensioning (given in DIM statements). ment, but ,can a Iso read data prepared by ordinary PUT statements. MAT GET takes the form Every array that is named in a MAT statement must be di­ step MAT GET adescr~adescr] ••• mensioned in a DIM statement. This assures that absolute dimensions exist, sets initial current dimensions, and dif­ where adescr is an array descriptor of the following format ferentiates between vectors and matrixes. (Note that use of a letter to designate an array does not preclude the use aname [(dimx [,dimx ])]

18 Matrix Operations In the array descriptor, the terms aname and dimx represent The rule for the use of commas and empty fields in the data the single letter array designator and dimension (subscript) list read by MAT INPUT is the same as described for the expression, respectively, of the array. As shown in the INPUT statement. general form above, therefore, on adescr term may indicate The remaining MAT statements resemble the LET statement a single letter array designator, a designator followed by in form and function. An array name (aname) always ap­ one subscript (a vector), or a designator followed by two pears immediately to the .left of the equal sign, and the subscripts (a matrix). The dimx expressions in an adescr named array is assigned values according to specifications term constitute variable dimensions; they provide a simple to the right of the equal sign. method for varying current dimensions during execution (not during compilation). One example of a MAT GET statement is ZERO 1008 MAT GET A(3,3),B(4,8) The MAT ZER statement zeros those el ements of the named array that fall within the range of current dimensions. Its format is SIZE step MAT aname ZER [(dimx [,dimx])] The MAT SIZE statement redefines current dimensions of the named array. Its form and some samples are shown below. The optional dimx terms have the same meaning described previously under MAT GET; that is, they are dimension step MAT SIZE oname (dimx[,dimx]) expressions specifying new current dimensions (subscripts) of [,aname(dimx [,dimx])] •.• the array, and as such constitute variable dimensions. For example, assuming the array B(5,5), that is, a 5 x 5 matrix 1003 MAT SIZE A(X+Y,Z),B(3) named B, the following statement, 1004 MAT SIZE D(4,5) 1010 MAT B '" ZER(3,2) The porometeraname is the single letter designator of an array, will zero elements (1,1),(1,2),(2,1),(2,2),(3,1), and (3,2), and dimx is any expression representing a legal subscript. leaving the remainder of the matrix unchanged. Other ex­ amples are READ 1020 MAT C '" ZER(10)

1030 MAT D = ZER The MAT READ statement is similar to the READ statement described in Chapter 2, except that it acquires whole ar­ rays of data, rather than just single data items. MAT CONSTANT READ has the form The MAT CON statement is ana logous to MAT ZER above, step MA TREAD adescr [,odescr] ••• except that it sets matrix elements to 1 (instead of 0). Its where adescr is on array descriptor of the same format pre­ format and a somple are given below. viously explained under "GET", namely: step MAT aname CON [(dimx [, dimx])] aname [(dimx[,dimx])] 2250 MAT L CON(3,5) If dimension expressions are included in the array descriptor, they specify current array dimensions. If they are omitted, IDENTITY MATRIX current dimensioning results from previous conditions. Some samples are shown below. The MAT IDN statement forms on identity matrix. Since the array must be a square matrix, new current dimension­ 1005 MA TREAD A(K/L + M,7) ing may have to be provided. Two forms of IDN are shown. 1006 MA TREAD B,C(3,4) step MA T aname = IDN [(dimx)] step MA T aname = IDN [(dimx, any characters to INPUT end of line]

The MAT INPUT statement is the array counterpart of the The first form, which gives the current dimension for the variable-oriented INPUT statement described in the begin­ row value only, is sufficient to define the square matrix. ning of this chapter. Format and a sample statement are The second form is provided for those users who wish to shown below. clearly indicate that the array is a square matrix. However, step MAT INPUT adescr[,adescr] .•• IDN may stand alone. Appropriate samples are shown. 1007 MAT INPUT A(3,4),B 1011 MAT Z = IDN When statement 1007 is executed, 12 values must be sup­ 1012 MAT B = IDN(4) plied for the 3 by 4 matrix A. These values are then fol­ 1013 MATC IDN(3,3) lowed by input for array B. Note that the number of values input to array B must match the current dimensions for B. 1014 MAT 0 IDN(X+Y)

Matrix Operations 19 COpy Sample TRN statements are shown below. 1019 MAT A=TRN(A) The copy statement copies arrays, and sets current dimen­ sioning of the array copi.ed into to that of the array copied 1020 MAT B '" TRN(C) from. The form of the copy statement is Current dimensioning of the matrix named on the left side step MA T aname = aname of the equal sign is set consistent with current dimensioning of the matrix named on the right. In the sample copy statement below, 1015 MAT A;= B In the rema in i ng three MAT statements, the same array name may not appear on both sides of the equal sign. matrix B is copied into matrix A. Assume that B is a 4 x 4 matrix with current dimensioning (3,3). Only elements (1,1), (1,2), (1,3) ... (3,3) from BarecopiedintoA. Fur­ MUL TJPLICATION IS ther, any remaining elements in array A are not changed, and the current dimensioning of A becomes (3,3). In the multiplication operation, vectors are taken to be row or column matrixes as appropriate. If a vector is multiplied SCALAR MULTIPLICATION by a vector, the scalar (dot) product results. The form of the multiplication statement is The scalar multiplication operation multipl ies an array by step MAT aname aname"'aname a scalar quantity. The form of the statement is step MA T aname '" (expr) '" aname The following is a sample multiplication statement. where expr is an expression representing the scalarmultiplier, 1021 MAT Z B*C and the parentheses are required. In sample statement 1016, below, Note that current dimensioning must be consistent with the accepted rules of matrix multiplication. 1016 MAT A (A)*A 1017 MAT B = (SIN(X+H))*C The two remaining matrix operations, inversion and the solution of simultaneous equations, have several common the parenthesized A is interpreted by BASIC as a simple var­ characteri stics. iable, not as an array name. 1. The argument matrix must be square (according to its current dimensions). ADDITION AND SUBTRACTION 2. Results are approximate, not exact. Array addition and subtraction are performed through use of 3. At the user's option, the computed determ inant of the the MAT statement shown below. argument is stored in a simple variable. step MAT aname aname{:}aname 4. The contents of the argument matrix are destroyed, but current dimensions remain. This statement adds or subtracts the corresponding elements of the two arrays named on the right of the equal sign and INVERSION stores the results in the array named on the left. A sample is given for reference. The inverse of a square matrix is specified by the INV 1018 MAT Z B+C statement, as shown below. step MAT aname INV(aname [,simple variable]) The ambiguity introduced by allowing addition or subtrac­ tion of two vectors with storage in a matrix, or copying, where the inclusion of the simple variable (in which to transposition, and scalar multiplication of a vector into a store the computed determinant of the argument matrix) is matrix is resolved by considering the vectors as row vectors. a user option. Some sample INV statements are Current dimensions of both arrays named to the right of the equal sign must be equal for addition and subtraction. The 1022 MAT A INV(H) current dimensions of the array named on the left side of the 1023 MAT B INV(I,D) equal sign are set equivalently.

In calculating the inverse of the square (by current dimen­ TRANSPOSITION sioning) argument matrix, the target matrix is initially set to an identity matrix. Then the target is converted by those It is not necessary to transpose a vector arraYi the result is elementary row operations that reduce the argument matri x an exact copy of the argument vector. Matrixes are trans­ to the identity matrix. Upon completion of the conversion, posed by use of the TRN statement shown below. the target matrix is approximately the inverse of the argu­ step MAT aname TRN(aname) ment matrix. The values of the argument matrix are

20 Matrix Operations destroyed; both matrixes have current dimensioning origi­ target array by those elementary row operations that reduce nally applicable to the argument matrix. the argument matrix to the identity matrix. Upon comple­ tion of the conversion, the values of the argument matrix are destroyed, but current dimensions for both the target SIMULTANEOUS EQUAtiON SOLUTION and the argument arrays are unchanged. The target array contai ns the approxi mate val ues that are computed by taki ng Solution of simultaneous equations is accompl ished via the -1 SIM statement shown below. (argument) x (target)

step MAT aname = SIM(aname , simple variable) This result is equivalent to solving one or m sets of simulta­ neous linear equations having the same coefficient matrix, where, as in INY, the simple variable modification is a that is, the argument matrix. user option. Some sample SIM statements are shown below.

1024 MAT M = SIM(E) When a determinant calculation is requested in using INY or SIM, the following special situations may occur: 1025 MAT S = SIM(H,D2) 1. If the determinant value calculation results in a magni­ The target array contains one or more sets of linear equation tude greater than 7. 237x 1075, the value of the simple constant column vectors. The dimensions of this array must variable will be the alphanumeric value OYERFl. This be compatible with the square argument matrix. For exam­ does not affect the calculation of the inverse or simul­ ple, if the argument matrix has current dimension of (n,n), taneous equation solution. the target array must be either an n-dimension vector (one solution},or else an n by m matrix (m solutions). The argu­ 2. If the matrix is singular, the simple variable is given ment matrix contains the coefficient matrix. The solution a val ue of zero; the val ues of the argument and target of the simultaneous equations is arrived at by converting the arrays are destroyed.

Motrix Operations 21 4. BASIC OPERATING PROCEDURES

There are two methods of using the BASIC system - on-line When the system is ready to accept input, it signals the and batch processing. Operations for each of these meth­ programmer with a prompt character: ods are detailed below. A complete list of error messages is given in Chapter 6. > On-line operations discussed in this chapter are run under control of the Batch Time-Sharing Monitor (BTM) or the The BASIC system operates in three distinct modes, the edit­ Universal Time-Sharing System Monitor (UTS)i additional ing mode, the compi lation-and-execution mode, and the operations information pertaining only to UTS is given in desk calculator mode. The user is in the editing mode after Chapter 5. Batch operations are run under the Batch Pro­ completion of the above sequence. cessing Monitor (BPM), Batch Time-Sharing Monitor (BTM), and Universal Time-Sharing System (UTS).t EDITING MODE

ON-LINE The system is initially in the editing mode. In the editing " mode, programs are created at the console. A program, In the following discussion, output by the computer will be once created, may be saved on the disc file, and any pre­ underscored. All lines typed by the programmer must end viously saved program may be retrieved for further editing with a New Line character e. An exclamation point (!) or execution. After a > prompt has been issued, user may at the beginning of a line indicates that the executive sys­ switch to editing mode by typing a nondirect BASIC line or tem is in control of the computer, whereas prompts (» and any command that results in one of the following operations: question marks (?) indicate that the BASIC system is in con­ l. Line Insertion trol. The default condition for subscripted variable refer­ ences is the safe mode (see explanation of card number 4 2. Line Deletion under Figure 6). 3. Text Listing The procedures in this section describe BASIC console op­ 4. Text Saving erations under control of the Batch Time-Sharing Monitor (BTM) System using the XDS Model 7015 Remote Keyboard/ 5. Program Loadi ng Printer. However, a wide variety of other terminal units 6. Line Extraction may be used with BTM. Therefore, the following qualifica­ tions should be noted. 7. Line Renumbering 1. On the Teletype Model 37 ASR unit, the Escape key is labeled" Prefix", and the New Line key is labeled LINE INSERTION "Line Space". To insert a line, the user types as many as five digits for a 2. On XDS Models 7550 and 7555 KSR Keyboard/Display valid BASIC line number, followed by the remainingcharac­ units, the Return key is labeled "Cursor Return". ters in the line, the first of which must be nonnumeric. If 3. Further, it is suggested that, in using either the Model 37 the line has a total of 85 characters or less, and contains orone of theXDS Keyboard/Display units, the user input no local syntax error, it is accepted as a valid line and de­ in lower-case letters. Since the computer responds in letes any previous line having the same line number. The upper-case letters, the difference between input and prompt character is then issued indicating that the system response wi II be immediately evidentfrom the printout. is ready for more input. If syntax errors are found, an ap­ propriate error message is output, followed by the prompt character, and the system waits for new input. CALLING BASIC If more than five leading digits are typed (the first of which After following the log-in procedure for the proper executive is not zero), the message system/ thecomputerwill printoutanexclamation point, in­ dicating that the executive is ready to accept a command. xxxxxx LINE # ERROR In response to the exclamation point, the programmer types BA is output, where xxxxxx represents the ·first six characters of the line, and the line will be ignored. and the computer completes the line by printing out SIC If more than 85 characters are typed on the line, the message as in BASIC LINE TOO LONG

tSee Related Publications, p. ii. is output. The line will be ignored.

22 Basic Operating Procedures Programs developed on-line are constructed in a text edit­ TEXT SAVING ing area (that is, a working area) in the computer's core memory. When this area diminishes to 500 bytes or less, the The user may save information on temporary or permanent message files. The command is

SPACE LIMIT NEAR SAV[E OJ {~ER}xname [::~: : I -line II J is output, At a predetermined critical point (150 bytes), attempts to insert lines-will be unsuccessful and will result , _I' II ® in the message [ {11~ne:Ine 3 me 4 1]'" where xname is the name of the file on which information PROGRAM TOO LARGE will be saved. It may be an alphanumeric constant of 1-6 characters enclosed by single or double quotes, or 1-6 non­ blank characters followed by a blank, or by if no line LINE DELETION numbers are given. If the SAVE ON form is used, a check will be made that no other file exists with the same name To delete a line, the programmer types the line number before opening the file for output. A file created by SAVE followed by a New Line ®, and the line with that number ON is temporary and is released when the user logs off. The will be del eted. If the I ine does not exist in the program, SAVE OVER option unconditionally writes the file, whether the line number will be output along with the error message or not a previous file exists. The SAVE OVER option creates a permanent fi I e provided there was no previously executed NO PROGRAM SAVE ON command using the same file. Both SAVE ON and SAVE OVER reset the account information, if any exists. To erase everything in the text editing area, the user types Samples are given below. CLE [AR] ® SAVE ON"TEMP" 1-55,80-105 ® To delete specific lines or series of lines, the user may type SAVN'A' 1,5, 10, 15,30-40 e SAVE OVER PERM ® line II }[ {line # }] DEL [ HE] I' II _I' # 'I' # _I' # .. { me I me 2 me 3 me 4 ·8 SAVVER END 50-95,120 ® after the prompt, as in If the programmer types DEL 72 ® FIL [E] or the entire contents of the text editing area are copied over DEL 85 - 97, 112-124 ® the runfi Ie (see" File Operations" below). If the line or series of lines is not found, the NO PROGRAM message will be output preceded by the specified line or PROGRAM LOADING line series numbers. If an illegal line number is used, the LINE # ERROR message is printed, preceded by the first six To load a file into the computer, the programmer types characte~s of the illegal line number. The NO PROGRAM message does not inhibit further processing of the DEL line, LOA[D~ [xname]® whereas LINE # ERROR does inhibit further processing. where xnome is the name of the desired file. If xname is 'To delete an entire program, it is faster to use CLEAR nat specified, the runfile (see "File Operations" below) rather than DELETE. Further, the use of CLEAR recovers will be loaded. BASIC "weaves" the file information into all the space in the text editing area. the existing program by step number. If an illegal step number is encountered, the message

TEXT LISTING ILLEGAL LOAD

To list a line or a series of lines, the user types is output. Other syntax errors will couse output of error messages as explained in "Line Insertion", above. If no LIS [T] [II ne: _ I' # I, ne: _ I' II ® file exists, the following message is output. ~me I I ne 2J [{ ~me 3 me 4 1]'"

which will cause listing of the appropriate lines from the UNABLE TO OPEN program. Error messages are identi cal to those described for line deletion. If the user types If the LOAD command is typed while the user has BASIC LIST e in the compi lation-and-execution mode (see the next section all lines will be listed. If none exist, the NO PROGRAM in this chapter), the text editing area is cleared prior to the message wi II be output. load.

On-Line 23 LINE EXTRACTION This causes the program to be copied onto the runfile, if necessary (see" Fi Ie Operations" below). The computer then The programmer may delete a complete program except for compiles from the runfile or from the text edit area. If RUI'J certain areas designated by their line numbers or line num­ was specified, compilation will take place in the safe mode, ber groups. This is done by typing in which all variable subscripts will be checked against ab­ solute dimensions; otherwise, compilationwill proceed in the EXT [ RACT I'ine # I' ] [ 'I'{line # I' }] ·8 fast mode. If no errors are found, the program wi II be exe­ me # 1 - me #2 Ine #·3- Ine #4 •. ]~ cuted. If the compilation contains errors, the editing mode is restored and a prompt character is issued at the console. If no line numbers are specified, no operation takes place and a prompt is issued to the programmer. If a FAST or RUN command is given in the editing mode prior to the creation of a program, BASIC will enter the LINE RENUMBERING execution mode and will allow direct execution of state­ ments from the console as described below under" Direct The programmer may specify that his program statements be Statements". If input is required from the programmer renumbered, starting with a certain line number and renum­ during execution, the BASIC program will issue a question bering in specified increments. The command to be typed is mark at the console. When execution of a program or a direct statement is complete, a prompt character is issued. REN [UMBER] [step 1 [,steP2 [,incr] 8 JJ Additional statements then may be directly executed, or the where programmer may revert to the editing mode by typing an editing command. stePl is the lowest new line number steP2 is the point in the program at which to start Both RUN and FAST reset account information, if any exists. renumbering If the standard runfile is used, password information is reset, incr is the increment by which the newline num- if any was set. bers are to be spaced. For example, the sample statement ESCAPE KEYACTIVATION REN 135, 170, 5 Double activation of the Escape key causes the current op­ will cause the computer to change statement number 170 to eration to be stopped; BASIC then will request a new com­ number 135, the next statement number to be changed to 140, mand by issuing a prompt character at the console. If the etc., until the end of the program is reached. Defaultvalues Escape key is immediately depressed two more times, con­ for the parameters in the RENUMBER statement are 100, I, trol passes to the executive program in charge of the com­ and 10, in that order. When a replacement is made for a puter. If, following escape from execution, the command step number, replacement is also made for any occurrence of the same step number within any statement in the program. 2. PRO [CEED] 8 Illegal RENUMBER syntax causes output of the message is typed after the prompt character, processing continues ILLEGAL with the core memory (but not file) conditions that were in effect immediately preceding the most recent activation of Also, if the renumbering process generates a line of more the Escape key. than 85 characters, the following message is output.

LINE TOO LONG PARAMETER SETTING

To set the values of vector and matrix arrays, the program­ If RENUMBER increments a line number past the upper limit mer types of 99999, the following message is output. SET letter == digits [,letter == digits]. .. 8 LINE # ERROR where the value of the digit string (interpreted as a decimal If the renumbering process cannot be completed because of integer) is assigned to the appropriate declared letter param­ errors, the original program will remain unaltered. eter as indicated by the alphabetic character. These param­ eters are used by the for compilation of DIM statements ,that contain set letters. COMPILATION AND EXECUTION MODE Example: To change from the editing mode to the compilation and execution mode, the programmer types A program includes the statement 20 DIM C(B,B+5)8, B was set to 8. Absolute dimen­ RUN } {FAS [T] 8 sions will be (8,13).

24 On-Line DIRECT STATEMENTS In all fjle operations (SAVE, LOAD, RENUMBER, RUN, and FAST), fjle name, account number, and password logic Direct statements are statements without a step number. of the Batch Processing Moni tor fi Ie management system is They implement two important BASIC capabil ities: employed. Originally, the password and account number I. Desk-calculator mode of operation. are empty.

2. On-line debugging and verification. To establish the password or account information, the pro­ grammer types DESK-CALCULATOR MODE To enter the desk calculator mode, the programmer types PAS [SWORD]} . {ACC [OUNT] [stnng] ® CLEAR, followed by RUN or FAST.

The desk-calculator mode uses the computer in the simplest where "string" extends from the first nonblank character up and most direct manner, working without a stored program to seven characters preceding the New Line character. If or stored data. The problem to be solved is usually com­ no string is specified, PASSWORD or ACCOUNT will be bined with a PRINT statement, preceded if necessary by a reset. Once set, an account or password wi II be used in LET or another form of an assign statement. Typical exam­ every operation that requires the opening of a file, except ples of BASIC in the desk-calculator mode are as specified above under "Text Saving" and "Compilation PRINT 1.08513.6 and Execution Mode". Also note that execution of an OPEN or CHAIN statement by the object program will result in PRINT SQR (12 *12 + 15 * 15) modification of the account and password information. PRINT LOG(SIN (5.12» In the examples shown below, ACCOUNT and PASSWORD PRINT SQR (87) set the fi Ie names, and ACC and PAS reset them.

ON-LINE VERIFICATION ACCOUNT LBRYI On-line verification is a general term for various functions ACC that may be performed in checking out and debugging a pro­ gram. The following examples are typical: PASSWORD '3731' PAS GO TO 35 Branch to a desired state­ ment within a program and proceed with execution. PRECISION OF OUTPUT PRINT A(I,I),A{l,2),A(5,5) Verify assignment of If the programmer types values in an array.

LET Al =0 12;5 Modify a value then ENT [ER BASIC] (L) ® GO TO 20 continue at selected point. the extended precision print indicator will be set or reset, depending on whether the optional L is or is not typed. If the computer is in the execution mode, any valid BASIC statement, except for DATA, DE F, DIM, Image, PRINT­ USING, FOR, NEXT, or any statement containing ON, may PRINTER WIDTH be typed without a leading line number. This will indicate that the statement should be executed immediately. To change the width of the printer from its default value When in the editing mode, attempted use of the direct of 72, the programmer types statement capability will result in the error message WID (TH]digits ® RUN? ILLEGAL where the value of the digit string, interpreted as a decimal integer, must be within the allowed maximum and minimum FILE OPERATIONS values of 85 and 32, respectively.

The user may wish to store information in a file, to be re­ called at a later time. If the user does not specify a file STATUS name, the computer will provide a generalized name for his file. However, if the user types To determine the status of his program at any ti me, the pro­ grammer types NAM(E] [name] ® STA(TUS]® The nome of the runfile is changed to the name given. If "name" does not appear, the default runfile name is The system wi II respond wi th one of the three messages restored. EDITING, COMPILING, or RUNNING, as appropriate.

On-Line 25 To facilitate loop deteCtion, the RUNNII\JG message will one card and each interval on a line represents one charac­ be preceded by an appropriate line number if execution was ter space in the corresponding column of the card. Note interrupted whi Ie one of the instructions in the compi led that all characters take up only one column each. Conven­ program was being executed. tions have been adopted for manually printing certain con­ fusing charaCters, especially characters 0 and 0, 2 and Z, SIGN OFF and 1 and I. It is advisable to check with the computer facility's keypunch operator for notation conventions. To exit from BASIC, the programmer depresses the escape When completed, the coding sheet is sent to the programmer's key four times and waits for the executive level prompt (!). keypunch facility. There the program is punched onto cards, A Iternative Iy, the programmer may use the SYSTEM command and the deck of cards returned to the programmer. The deck, to return to the exec uti ve program. The command takes the form along with required BPM control cards, can now be sent to the computer facility to be run on the computer. Figure 6 ~ SYS [TEM] (0 shows a typical deck struCture for a BASIC program that is At this point, he may invoke another processor that oper­ run under BTM or BPM. Note that the dashed lines indicate ates under BTM or UTS System control, or he may vacate optional control cards. Card parameters are explained the terminal by typing below the figure. ! BY E (or OFF under UTS) Figure 7 shows a typical deck structure for a BASIC program that is run under UTS. Note that a subset of online editing BATCH PROCESSING commands is used in thisdeckstruCtureinstead of the special control cards (items 4, 5, 7, and 9 in Figure 6) that are The programmer prints his program on a coding sheet (see used in a BPM or BTM deck structure. Other online com­ Figure 5). The coding sheet is divided into 80 columns mands, such as LOAD, may be used in UTS BASIC in batch (corresponding to a standard data-processing punch card) and mode, but they are oriented primarily toward conversational a number of rows or horizontal lines. Each line represents operations and should be used with caution.

KEY PUNCH TRANSMITTAL 80 COLUMN

,.

KEYPUNCH WRITING CONVENTIONS ------, SUBMITTED BY: tit. ST. .>oH~ '~(zero)~( O)'L(one) ,..L(I) J,....(L) Z(slesh)'..±..(four) ;L,.(nine;'~(five)~(S) T ~(Y) DATE )"1..- '~-4.i Figure 5. Coding Sheet with Modified Sample Program

26 Batch Processing r------, ~.~ 0!t:~ ~~ ~~~ ~r~s __ ~ " IEOD} , I I {. , I I * I I I I I I I I 8. I,_J I _..J 7.

6. BASiC program r ------, 5.! * [~J ~ {~i9itS}] ['lJ 'I ... __ .L ______~ I

4. I *Sc[=] digit(s) " I 3. !BASIC ,..------..... 1I : 2. I BPM control cards " I I 1. !JOB 1 t--_J I I I I I J I _JI

Figure 6. Deck Setup for BASIC Batch Processing (BTM or BPM)

Card Parameter Description

1. !JOB Signals the beginning of a job stack. This card is required. t 2. BPM control cards May include BPM control cards such as !LIMIT, !STDlB, !MESSAGE, and !ASSIGN. These cards are optional. CHAIN programs can be file-managed.

3. ! BASIC Requests the BASIC processor. This control card is required.

4. *Sc [=]digit(s) One or more parameter setting cards to assign the designated constant value to the declared letter (used for compi lation of DIM statements that contain dec lared letters). Column 1 must contain an *, followed by an S in column 2. Column 3 contains the single-letter designation of an array. Column 4, always interpreted as "", is followed by a constant value.

5. Option declaration cord must have an * in column 1, followed by a blank. An S in column 3 indicates the safety mode for array referen<;es. If the safety mode is specified, the compiler checks the subscripts of subscripted variable references against the dimensions. Any other character (indicated by c) in column 3 indicates the fast mode. Thedefaultcondition is"fast".

D is the default case for the printer line width (l00). If a digit appears in column 5, succes­ sive columns of the cards are scanned unti I a nondigit character is encountered. The digits are then interpreted as the printerlinewidth(subject to maximum and minimum width parameters, currently 131 and 32, respectively). It is recommended that the D or digit(s) be followed by a comma. If neither a D nor a digit appears in column 5, the rest of the card is ignored.

[,l] An l in the column following the comma causes listing of all records following the option declaration cord up to on end-of-file mark, or an ! EOD or *RUN record. (*RUN will be listed, but! EOD will not.) This card is optional.

tForfurther information on these control commands, see the Sigma 5/7 Batch Processing Monitor Reference and Operations manuals.

Batch Processing 27 Card Parameter Description

6. BASIC program The programmer's BASIC program, in Iine-number order.

7. {lEaD} End of program. If no errors are detected by the compi ler, the program wi II be executed, be­ *RUN ginning at the statement with the lowest line number. If this card is omitted, the program will not be executed, even if no errors are detected. This allows compilation for diagnosis only.

8. data Data to be used in response to INPUT statements. The data should be followed by an end-of­ file mark, an I EOD, or a record with an * in column 1.

9. BPM control cards Other BPM control cards as required. In particular, the temporary files created via the a op­ tion of OPEN statements must be fi Ie-managed to permanent fi les if the programmer wants to retain the information.

9.

8. r,Ll~[T][ II~;;:~ _-I'~ -] (tll~ne~ ~I'-~}~J'~i I . me 1 me 2 [ me 3 I ne 4 I I I I I I I 7. er's BASIC program L------rENT BASIC][L] ------"'"', ~..L-----_--_-----, '\ 5 . .J..'SET letter = digits [,letter = digits]. .., I 4. ,...'WID ------, [TH] digits \ "I: I ;.: !.!:~~ ______" : I I 2. I UTS control cards , l LJ I. !JOB ", Il-J I , I I .J I I J

Figure 7. Deck Setup for BASIC Batch Processing (UTS)

Card Parameter Description

1. !JOB Signals the beginning of a job stack. This card is required.

2. UTS control cards May include UTScontrol cards such as !L1MIT, !STDLB, !MESSAGE,and!ASSIGN} These cards are optional. CHAIN programs can be file-managed.

3. ! BASIC Requests the BASIC processor. This, control card is required.

4. WID [TH] digits Changes the width of the printer from its default value of 72 to the specified value (digits). All commands may be started in column one or may be preceded by blank columns.

tFor further information on these control commands, see the Sigma 5/7 Batch Processing Monitor Reference Manual (900954).

28 Batch Processi ng Card Parameter Description

5. SET letter = digits Sets the parameter values of the dimensions of vector and matrix arrays. The value [,letter = digitsJ •.. of the digit string, interpreted as a decimal integer, is assigned to the appropriate declared letter parameter as indicated by the alphabetic character. These param­ eters are used by the compiler for compilation of DIM statements that contain set letters.

6. ENT[ER BASICJ [I-J Sets the extended precision print indicator when L is included; resets the indicator when L is not included. The default is normal precision.

7. BASIC program This is the programmer's BASIC program. In UTS, it need not be ordered seguen­ tially. Note that any run-time error or END, STOP, or PAUSE statement causes on exit from BASIC after a diagnostic printout.

8. Lists a line or a series of lines from the program. If LlS[TJ is used alone, all lines of the program will be listed.

9. RUN } If no errors are detected by the compiler I these commands cause the program to be {FAS[TJ executed, beginning at the statement with the lowest line number. If this card is omitted, the program will not be executed, even ifno errors are detected. The RUN card causes the program to be compiled in the safe mode, in which all variable subscripts will be checked against absolute dimensions. The FAS[TJ card causes the program to be compiled in the fast mode.

J O. data Data to be used in response to INPUT statements. The data should be followed by an

end-of-file mark, an 1 EOD I or a record with an * in column 1.

Batch Processing 29 5. UTS BASIC ADDITIONS

SUMMARY OF UTS ADDITIONS 9. Generating alphanumeric constants from strings for file identification. In addition to Sigma 5/7 BPM and BTM, BASIC can be run 10. Establishing maximum string length and storage require­ under the new Universal Time Sharing (UTS) Monitor for ments (Edit command). Sigma 7 computers. UTS BASIC differs from Batch/BTM BASIC in four major areas: These 10 capabilities are discussed in the following para­ 1. Language extensions. graphs (and "Edit Command List"). 2. New edit commands. REFERENCING STRING VARIABLES 3. Increased interaction between Edit and Execute modes. Strings are identified by the dollar sign followed by a fur­ 4. Context preservat i on. ther identification of the type of string specified: string scalar, string array, string array element, or substring. Ex­ Language extensions include capability for manipulating amples of each of these are given at the end of this discus­ character strings, the addition of 11 new intrinsic functions, sion. Strings may also be combined in expressions for the and capability for preserving array and string values in purpose of string concatenation. chaining programs via the CHAIN LINK statement. String scalars have the form New edit commands provide capabil ity for saving and re­ packing the current program (FILE PACK), for setting con­ $Ietter text of strings, arrays, or simple variables to zero (NULL), for selectively clearing arrays and strings (CLEAR)[ setting A string scalar may not appear in a dimension statement. maximum length for strings (SET), and a new command for To avoid conflict, the same letter may not be used for both directly executing a numbered statement (EXECUTE). a string sca lar and a string array or numeri c array. Increased interaction between Edit and Execute modes per­ String array elements are subscripted variables preceded by mits the user to mix editorial and run-time actions as freely the dollar sign. They have the form as possible. Changes allowing easier transition between editorial and execution modes affect the BREAK-PROCEED $Ietter (expr GexprJ) logic and the direct statement capabi Iity. where the optional expression denotes a matrix element. A Variable context (processed data) and program status are string with only one expression is a vector element.

preserved insofar as possible during operation. In particular I numeric and string array context, DATA pointing status and String arrays must be explicitly dimensioned. The form for GOSUB-RETURN status are saved over a wide range of oper­ dimensioning a string array is ations. Context preservation is discussed below under DIM $letter(dimx[,dimxJ) CHAIN LINK STATEMENT and SUMMARY OF UTS BASIC OPERATING PROCEDURES. Setting string array current dimensions is analogaus to setting numeric array current dimensions, using the statement UTS BASIC LANGUAGE EXTENSIONS MA TSIZE $Ietter (dimx[,dimxJ) CHARACTER STRING MANIPULATION Substrings are marked by a colon preceding an expression: In Batch/BTM BASIC, strings are I imited to alphanumeric $Ietter (:expr 1 [,expr 2J) constants up to six characters long and to text strings in where expression 1 indicates the position of the first char­ PRINT statements. UTS BASIC permits strings up to 85 char­ acter of the substring, and the optional expression 2 indi­ acters long and provides capabil ity for cates the length of the substring in number of characters. If expression 2 is omitted, the substring includes a II char­ 1. Referencing string variables. acters from the indexed character to the end. 2. Using string expressions. If a string is an element of a vector or a matrix, then the 3. Assigning a character string variable. form of the substring is 4. Assigning length or numeric value of a string variable $Ietter (expr 1 [,expr 2J : [expr 3J [,expr 4J) to a simple or subscripted variable. where expressions 1 and 2 are the indexes of a string array 5. Converting a numeric value to string format. element, expression 3 is the index, or string position, of 6. Concatenating strings. the first character of the substring; expression 4 is the length, or number of characters, in the substring. Again, if ex­ 7. Comparing strings. pression 4 is omitted the substring consists of all characters 8. Using strings in input/output statements. from the indexed character to the end of the string.

30 UTS BASIC Additions String examples are where sfunction is LEN or VAL. Both assignments can be made in one I ine (step number) separated by a comma as in $P string scalar the example $H (1) string vector element $'B (2,3) string matrix element 35 K 1 = LEN ($W{2, 3» , K2 VAL ($W(2, 3» $A (;4) substring consists of all characters from 4th to last characterof string scala r A in which the length of the matrix string element $W(2,3) is $A(:4t I) substring consists of 4th character of $A assigned to the simple variable K 1/ and its numerical value $B(2,3: 5,2) substring consists of 5th and 6th char­ to K2. The arguments for both functions must be string ex­ acters of string matrix element $B (2,3). pressions. If the character string specified for VAL doe.s not STRING EXPRESSIONS represent a correctly formatted decimal constant, an error message is generated and execution terminates. String expressions may be used as arguments for string func­ tions, PUT, PRINT and PRINT USING statements, string con­ CONVERSION TO A STRING catenations, and string comparisons. They must be explicitly stated in the PUT, PRINT and PRINT USIN G statements, but The output conversion routine automati cally converts an ex­ may be in either impl icit or explicit format in all other cases. pression to string format, but in manipulating text it may be The implicit string expression (strexp) has the form desirable to have the same conversion performed internally, for example to store an evaluated expression in a file, or string } string } ] embedded as a substring with in a text string. The string­ tstring tstring conversion routine is available for this purpose. It has the var' { [ { form STR(expr[,rstring] ) + ~~~'(expr [,rstring]) ... Step LET string = STR (expr [,rstring]) where var' is a variable containing an alphanumeric constant. where STR is the new string-conversion function added to Impl icit string expressions are always to the right ofthe relation UTS BASIC. operator in string assignment statements and comparisons. Explicit string expressions (xstrexp) are required to avoid The replaceable-string (rstring) argument is optionally used ambiguity on whether or not string processing is called for. to indicate the image of the desired format. If the rstring The form of this expression is option is not used, format is that for print output conversion. $(strexp) } { Like the output conversion, string-conversion is governed by stri ng + strexp the setting of the precision flag. The string will have a where the dollar sign resolves the ambiguity that arises if leading blank if it is non-negative, but will not contain the first character is a letter character (as in STR or in a trailing blanks. The minimum length for a string is two variable). An implicit expression may be used only in a bytes; maximum length is 22 bytes for long precision and statement where the syntax is unambiguous in indicating 12 bytes for short prec is ion. string processing. Examples of STR (conversion-to-string) statements are Examples: LET $Z = B (2,3) + $A(:5) implicit string expression 10 $A = STR{3. 5, II • II) PRINT $(B(2,3) + $A(:5» expl icit string expression 20 $H(I :9) STR (SQR(X» PRINT B (2,3) + $A(:5) ILLEGAL I ambiguous 30 LET $W(2, 3) = STR(AI +BI*COS(X» syntax STRING ASSIGNMENT AND CONCATENATION ASSIGNING CHARACTER STRING TO STRING VARIABLE Simple variables provide storage for just one doubleword; Another string, an alphanumeric constant, a string converted therefore, a simple variable is limited to representing an expression (see above), or a concatenation of any or all of alphanumeric constant (maximum of 6 characters). these may be assigned to a string. The form of the string­ assignment and concatenation statement is Character strings more than 6 characters long must be as­ p p signed to string variables ($Ietter). Strings up to 6 charac­ step [ LET ] string• = {strex } r+ {strex }l ... ters are considered alphanumeric constants and may be as­ xstrexp L xstrexp signed to simple or subscripted variables. where strexp is an implicit string expression and xstrexp an STRING LENGTH AND VALUE ASSIGNMENTS explicit string expression (see String Expressions above). For these assignments, UTS BASIC provides two new intrin­ Examples: sic functions: LEN (for length) and VAL (for value). The assignments are made to simple or subscripted (not string) 10 LET $S = $H(I) variables and have the form: 20 $T $H(1) + $H(2) step [LET]var ~var] .•. =sfunct(strexp) 30 $U = 'NUTS'

UTS BASIC Language Extensions 31 40 LET$V = 'NUTS' + B4 + 'SOUP' 500 DATA "IT IS RAINING", "IT IS CLEAR" 50 $H(2:3) = STR(SQR(X)) + ' = SQRT OF X' 883 PUT $V, $W(I), $X(I,A) + "SNOWING", 60 $Z = $Z + $H(2:3) $(B5 + STR(V(I))

The left string is given a value and a length consistent with 910 READ $H(I), $H(2), $H(3) the items to the right of the equals sign. If the right con­ tains only one term, the statement performs string assign­ 700 GET $W(A I, A2), $X(B I, B2) ment. If the right side contains two or more terms, concatenation occurs in the order given. If the maximum 750 PRINT $("THE ANSWER IS" + STR(A7, ##. ##) +$B) string length is exceeded, the string is truncated. 760 PRINT US IN G 100, $H( I), $H(2) If assignment is to a substring whose current length is less than n-I, where n is the first character of the target sub­ 800 PRINT $A( I, I), $A( 1,2), $A( I, 3) string, then the gap to character n-I is filled with blanks. If target-substring length is specified and the number of char­ 400 MAT PUT $A, $B, $C acters transferred is less than this specified length, then the gap from the last character transferred to the specified length 410 MAT GET $A(2,3), $B is also filled with blanks. Characters in excess of specified length are not transferred. 420 MAT READ $F(4), $G STRING COMPARISON 430 MAT INPUT $W, $X

Strings are compared for identity or "magnitude" in IF •.. 440 MAT GET $A, B THEN or GOTO statements. The form of the statement is

. {strexp } {THEN } step IF string relop xstrexp GOTO step Step 440 requires that the data file have the correct number of string array elements to fill $A, immediately followed by numeric data to fill numeric array B. where relop is -.I relational operator, and strexp and xstrexp were explained under" String Expressions". Examples are The examples above show cases of string input/output only. The forms are similar to those described earlier fornonstring IF $W(: I) = 'W' GOTO 99 10 input/output. In UTS BASIC, statements may mix (with 20 IF $W < > STR(XI*YI+3) THEN 40 appropriate caution) string and nonstring items in the same statement, as shown in Appendix A. 30 IF $R > STR (0) GOTO 85

40 IF $A < "DOG" + $B(I :9) THEN 120 GENERATION OF ACONSTs FROM STRINGS

Strings are compared from left to right as character pairs. A string or string expression may be assigned to a simple or In comparing letters, A < B < C .•. < Z. A decision based subscripted variable, but only six characters will be trans­ on the relational operator is made when character pairsdiffer ferred and the rest truncated. If the string contains fewer or when both characters are nulls indicating coincident end than six characters, trailing nulls are generated to satisfy of strings. Program proceeds to next statement in case of the aconst format. mismatched pairs, i. e., special character paired with any other character, or alphabetic character paired with num­ eric character. Examples:

STRING INPUT/OUTPUT Al = $P

Explicit string expressions and text strings may be used in A2 = $B(:4) input/output statements in the form used for expressions and alphanumeric constants in Batch/BTM BASIC, subject to the A3=$('NO. '+$ C(A4)) general rules governing strings. That is, a run-time error results if a text string (more than six characters) is provided This provides an indirect means to assign strings as external as input to a nonstring variable, or nonstring input (not a names or file identifiers by first assigning strings to simple text string nor an alphanumeric constant) is provided to a variables. string. The statements used are INPUT, PUT, READ, GET, DATA, PRINT, MAT PUT, MAT GET, MAT READ, and MAT INTRINSIC FUNCTIONS ADDED TO UTS BASIC INPUT. Besides the three string functions previously discussed Examples: (LENgth, VALue and STRing), the II general functions listed in Table 5 have been added to UTS BASIC. All re­ 140 INPUT $W, $V( I, A) require one argument.

32 UTS BASIC Language Extensions Table 5. Intrinsic Functions, UTS BASIC Only

Function Result

CSC (arg) Calculates cosecant of an argument in radians. Overflow results in an error message and termination of execution.

SEC (arg) Calculates secant of an argument in radians. Overflow results in an error message and termination of execution.

COT (arg) Calculates cotangent of an argument in radians. Overflow results in an error message and termination of execution.

ASN (arg) Calculates arcsine of a unitless argument, in radians. If the absolute value of the argu- ment is greater than 1. 0, an error message is printed and execution is terminated. Re- solution of results is restri cted to the two quadrants from - rr/2 to rr/2.

ACS (arg) Calculates the arccosine of a unitless argument, in radians. If the absolute value of the argument is greater than 1. 0, an error message is printed and execution is terminated. Re- solution of results is restricted to the two quadrants from 0 to 11.

HSN (arg) Calculates hyperbolic sine of an argument. Overflow resu Its in an error message and termination of execution.

HCS (arg) Calculates hyperbolic cosine of an argument. Overflow resu Its in an error message and termination of execution.

HTN (arg) Calculates hyperbolic tangent of an argument.

LTW (arg) Calculates logarithm, base two, of an argument.

DEG (arg) Converts argument to degrees, in radians.

RAD (arg) Converts argument to radians, in degrees.

CHAIN LINK STATEMENT ADDITIONS TO EDIT COMMAND LIST

The CHAIN LINK statement differs from the CHAIN state­ New or expanded editing capabilities in UTS BASIC include ment in that it preserves array and string values. The CLEAR, NULL, FILE PACK, EXECUTE, SET, DELETE, and I CHAIN statement retains only the simple variables and dis­ INPUT commands. cards the rest of the program. CLEAR In addition to the capability existing in Batch/ BTM BASIC of clearing all program context, UTS BASIC The form of the statement is permits clearing of arrays or strings only. step CHAIN [LINK] file identification The command has the form ARR [AYS]] An example is CLE [AR] [ STR[INGS] @

950 CHAIN LINK "PART 2" :A;P It releases storage for the indicated option. where NliLL This command sets the value of specified items to :A is account A zero but does not rei ease or rea II ocate storage, nor does it modify current or maximum dimensioning of arrays. It has ;P is password the form A and P contain alphanumeric constants. "PART 2" is the name of the chained program. NUL [L] [~;: [~~Y~~]] @ SIM [VARS] The "UNK" part of the statement form is optional. With­ out it, the array context of the old program would simply NULL ARRAYS sets the value of all array elements to zero be discarded. With it, it is retained. for current dimensioning.

Additions to Edit Command List 33 NULLSTRINGS sets the length of all string scalars and Example: string array elements to zero. 40 PRINT Al, A2, A3, A4, A5 NULL SIMVARS sets all ~imple variables to zero. 50 GOSUB 110 60 PRINT A2 NULL performs all three options. 70 GOSUB 140

NULL does not modify source text or object code; however, zeroing simple variables affects FOR-NEXT statements in that this resets any loop control variables. SET The SET statement (see also "Parameter Setting", Chapter 4) can be used in UTS BASIC to establish maximum FILE PACK The FILE PACK command is an extension of string length for allocation of string storage. Default value the Batch/BTM FILE command which saves the entire current is 18; highest permitted value is 85 for anyone string. source program on RAD as RUNFILE (see Chapter 4). In UTS BASIC it has the form This form of the command is

SET $ == positive integer

The PACK option serves to recover the space that was oc­ Example: cupied by discarded text. If the option is exercised, pro­ gram text is read back into core memory in edited format, SET $ 12 that is, without the empty spaces due to deletions. allocates maximum storage of 12 characters for any string. FILE does not modify program context. FILE PACK sets Strings with more than 12 character are truncated and BASIC to editing mode and prohibits returning to execution length count for such strings is reduced to 12. without recompi I ing object code. Array and string context is preserved, as is DATA poi nting control and GOSUB­ In UTS the SET command also causes subsequent reallocation RETURN status. of array-stri ng storage as requi red for new parametri c dimensioning or new string lengths. During array-string EXECUTE The EXECUTE command performs two dis- storage reallocation, context is saved as new maximum tinctly different functions: (1) it specifies a single, num­ dimensions permit. bered statement for direct execution; and (2) it specifies a starting point for execution, with a halt at a specified step DELETE The DELETE command may be used to delete a number. The first use is for the programmer's convenience, named file in the user's account. The syntax is as follows. saving him time by letting him specify a step number in­ stead of requiring him to type the entire line. The second DEL[ETE] xname use is a valuable aid in debugging and verifying program segments without executing the entire program, as would be The name "xname" may be either an aconst or simple vari­ the case with a direct GO TO statement. able containing an aconst. If a password is currently in effect, it is applied.

The command has the form INPUT The 1 NPUT statement (see pages 12 and 32) a" ows input Ii nes to contai n fewer, or mo.re, elements tha n are present in the variable lists. If an input line does not satisfy the list, another line is called for, and if items are left over, they are used by the next INPUT statement (if where the optional step 2 specifies the step number at which any). In UTS BASIC, the following conventions apply to execution will halt. In the program example shown below, unused input val ues. EXE 40 would be equivalent to typing PRINT Al, A2, A3, A4, A5; and EXE 40-70 would be equivalent to typing 70 At the end of execution of a compiled program, unused HALT 6> GO TO 40, except that in the case of EXE 40-70 values of an input line are discarded. This is true for a the halt at 70 is temporary; that is, the line is restored to normal exit, a run-time error exit, or when a CHAIN is normal after the halt has occurred. In this example, if pro­ executed. gram returns from subroutine 110, line 60 is executed, fol­ lowed by the message In the direct mode, unused values are retained and may be accessed by later direct INPUT statements or by INPUT statements in a compiled program. 70 -EXEC- HALT INCREASED INTERACTION, EDIT -EXECUTE ACTIVITIES

EXECUTE is subject to all rules and restrictions applying To facilitate transitions between editorial and execution to direct statements (see below and "On-Line Operations", modeSt UTS BASIC incorporates changes in the BREAK­ Chapter 4). PROCEED logic and in direct statement capability.

34 Increased Interaction, Edit-Execute Activities BREAK.PROCEED LOGIC CHANGES precision control, runfile identification parameters, para­ metric dimensioning, and maximum string length. In Batch/BTM BASIC, BREAK may interrupt execution at any point, but PROCEED resumes execution only if The lists below present a summary of the effects of operator intervening console actions have not modified object code. action (command and statement input) on operating mode In UTS BASIC, only CLEAR, LOAD, or RENUMBER, or and context. failure to correct a diagnosed error prohibit PROCEED from resuming execution following a BREAK. GROUP 1 If a BREAK occurs during executron of a statement, that statement is fully executed and the line number of the The following commands do not change operating mode and next statement to be executed is saved before user is affect context only as the individual command explicitly given console control. PROCEED then returns to the indicates. saved line number. If that line has been edited out or is not an executabl e statement, execution resumes at the LIST No context change. next executable line. STATUS No context change.

CHANGES IN DIRECT·STATEMENT CAPABILITY WIDTH Set printer width.

UTS BASIC incorporates two important improvements in its ENTER BASIC Set output precision control. direct-statement capability: NAME Runfile identification. 1. The list of statements that may not be executed as di rect statements is reduced to DATA, DEF, Image, ACCOUNT Runfile identification. FOR, and NEXT. PASSWORD Runfile identification. 2. Direct statements maybe issued while in the edit mode. SA VE (ON or OVER) Generates text output file. Note that the following "dependent" statements cause re­ compilation of the entire program if they are issuedasdirect FILE f not FILE PACK) Outputs runfile. statements in the edit mode: IF, GO TO, PRINT USING, ON, READ, GOSUB, DIM, RESTORE and RETURN. With NULL (any option) Zeros selected context. the exception of DIM, which is a special case, all of these statements refer either explicitly or implicitly to numbered statements in the program and, therefore, have meaning GROUP 2 only in the program context. If a syntax error occurs any­ where in the program, the recompilationfor the dependent Input of any of the following commands leaves BASIC in direct statement is aborted with the message edit mode, requiring recompilation or normal compilation of object code before subsequent execution. If a Group 2 command is input while in execution mode, DATA list RECOMP FOR DlR ST ABORTED pointing control and GOSUB-RETURN status are saved. Other context is modified as indi cated: For all other di rect statements, the program is not recom­ piled. All direct statements, however, are checked for DELETE Removes line from active use. syntax errors. If an error is found, a diagnostic message is output and control is returned to the consale in the edit EXTRACT Removes program except mode. If no errors are found, execution mode (Safe or Fast) specified line(s). is reestablished and the direct statement is executed. Line insertion Adds line to active use.

SUMMARY OF UTS BASIC OPERATING PROCEDURES FILE PACK Releases st'-wage of deleted lines. BASIC is always running in one of three modes; edit, com­ pile, or execute. Compile is a transitory mode, leading LOAD (while in edit Acts as series of line directly to execution, if successful, or to edit, if failure mode) insertions. occurs. In on-line operation, transition from mode to mode may occur frequently because of operator actions. CLEAR ARRAYS or Releases storage STRINGS The variable context of principal interest during BASIC operations includes source text, object code, array and SET Sets parametric dimensioning string storage, DATA list pointing control, GOSUB­ letter, or maximum string RETURN status control, pri nter 'ine width control, output length.

Summary of UTS BASIC Operati ng Procedures 35 GROUP 3 Errors during recompi lation cause error message generation, abort object code generation and array-string storage re­ Input of any of the following commands leaves BASIC in allocation, and cause return to console in edit mode. If edit mode and requires normal compilation of object code recompilation is successful, execution is initiated at the before subsequent execution. Context of DATA list point­ "next statement" of the interrupted and modified program. ing and GOSUB-RETURN control is set to initial conditions. Other context is modified as indicated: If only Group 1 commands have been input since Break key activation, PROCEED causes return to the interrupted LOAD (while in exe­ New text. activity. cute mode)

CLEAR Clears arrays, strings, text, DIRECT STATEMENTS and object code. There are three categories of direct statements, in terms of RENUMBER Generates output file of text, operational impact: DIM statements, statements with does CLEAR, and loads num­ i ncl uded I ine-number references, and statements with no bered text. I ine-number references. " GROUP 4 DIM, as a direct statement, causes updating of storage requirements for arrays and strings and returns control in edit mode. Rules for command Group 2 apply. Input of e'ither FAST, or RUN, initiates normal compilation of object code from the current program text. Compilation Direct statements without line references are compiled and is in fast or safety mode as indicated. In addition to object executed independently of other program text or object code generation, string-array space is reallocated, but con­ code. If errors occur, messages are output and execution text is saved, as possible, where indicated by new absolute is aborted. Control is returned to console in same mode as dimensioning. before input of direct statement. If errors occur during compilation, messages are generated, Direct statements with line references require presence of and object code generation is aborted, as is array-string object code. If mode at input is execute, the direct state­ storage reallocation. Return is in edit mode, as per Group 3. ment is compiled and executed. If mode is edit, recom­ pilation of program is initiated. Compilation is aborted by If no errors occur, execution is initiated at start of program any error, in which case return is in edit mode. If recom­ with DATA list pointing and GOSUB-RETURN control pilation is successful, direct statement is compiled and initialized. executed. Return to console is in execute mode.

PROCEED BATCH PROCESSING PROCEED isa command to return to interrupted activity. UTS BASIC allows the use of either the up-arrow (or cir­ Three responses are possible: (1) immediate return to inter­ cumflex) or double asterisk as an exponentiation operator. rupt point; (2) recompile and return to "next statement", or The use ofthe doubl e asterisk is convenient for batch opera­ (3) indicate ILLEGAL and return to console in edit mode. tion, since the up-arrow requires an overpunch if cards The response depends on the categories of commands that are used as the input medium. have been input since the interrupt. In general, PROCEED is legal only if execution of a program has been interrupted; it always terminates the interrupt state. If any Group 3 or 4 1/0 CONTROL commands have been input since Break key activation, PROCEED is illegal. Output produced via LIST and PRINT is done via M:LO. INPUT is done via M:CI. Either of these DCBs may be SET If Group 2 commands have been input since Break key acti­ to a file (using TEL), and M:LO may be SET to a line vation, and PROCEED is legal, recompilation is initiated. printer.

36 Summary of UTS BASIC Operating Procedures 6. BASIC MESSAGES

This chapter lists BASIC error messages and other messages in alphabetical order. Messages that do not apply to all xxxx BAD FORMAT three monitors are designated !lUTS only" or "not in UTS". In the messages, xxxxx represents step number and x repre­ Message covers wide range of syntax errors. User should sents array name, function letter, or declared letter. Ex­ reexamine statement definition if error is not obvious. cept as noted in comments, an error causes termination of program execution. xxxxx BAD FORMULA xxxx ARG NO. ERR FNx An arithmetic expression error has been detected. Message covers a wide range of error situations such as missing op­ Confl ic t between the number of arguments defi ned and num­ ber of arguments used with the function. erators, missing operands, misspelled function names, mis­ spelled keywords, etc.

xxxxx ARRAY USED TWICE BAD STEP NO. AFTER STMT. xxxxx

MAT statement does not allow the same array name on both An illegal statement number (>99999, or first character is sides of equals sign. zero) occurred immediately after the statement at xxxxx. If the fi rst statement is incorrect, xxxxx is zero.

ARRAY CLASS CONFLICT xxxxx BAD STMT UTS only. Indicated letter used for more than one type of array. Example: B used for string vector but dimensioned Type of statement is not recognizable; most frequently, the as numeric vector. command key word has been misspelled.

xxxxx BAD CHAR BAD STMT ORDER AT xxxxx

Statement xxx xx contains an illegal character (for example, Statement step number following xxxxx is smaller or equal !, ?, @, etc.). Note, however, that all charocters having to xxxxx. Not applicable to on-line processing where the EBCDIC value of blank or greater are allowed in image statements are ordered automatica Ily before compilation. statements, text strings, and alphanumeric constants.

xxxxx BAD SUBSCR xxxxx BAD CONST Known subscript value is too small. xxxxx contains an improperly formed numeric or alphanu­ meri c constant. Probab Ie causes are xxxxx BAD TEXT STRING Numeric Text string either contains a New Line character{user prob­ Extra decimal points. 1. ably forgot end-quote mark), or has an unmatching quote,

2. More than two digits in exponent fields (for example, (as in 123 PRINT II DOUBLE QUOTE'), or contains a charac­ •OOlE100). ter having EBCDIC value lower than the blank character . 3. Underflow or overflow in conversion to floating-point form. BAD SUBSTRING PARAM o 4. Missing operator after the constant. UTS only. Run-Time error. Substring index is nonpositive Alphanumeric or starts beyond maximum string length. 1. Missing quotation mark. 2. Single (ordouble) closing quotation mark does not motch DATA MIX-UP, $STRING VS NUMERIC double (or single) opening quotation mark. UTS only. Either numeric data is being input to a string, 3. More than six characters between quotes. or text exceeding aconst length is being input to a simple 4. Contains a character having EBCDIC value less than the or subscripted variable (via READ, INPUT, GET, MAT blank character (for example, the e character). READ, MAT INPUT, or MAT GET).

BASIC Messages 37 xxxxx DEFD TWICE xxxxx FOR-NEXT ERROR

Function defined in DEF statement xxxxx was also defined Message covers FOR-NEXT errors illustrated below: by an earl i er DEF statement.

Case 1. Wrong Variable Reference xxxxx DIM ERR FORA NEXT B error DIM statement formula contains one of the fallowing; 1. User function call. Case 2. Improperly Sequenced Statements 2. Simple variable that is not "set" to some value. FORI FOR J 3. Subscripted variable reference. NEXT I error NEXT J error xxxxx DIMENSION INCOMPATIBILITY x Case 3. No cClrre~n(md FOR statement Dimensions not compatible in matrix operation. Examples; NEXT A error matrix identity, or inversion of nonsquare matrix; or wrong dimensioning for matrix multiplication or addition, etc. These messages may be compounded as in FORA xxxxx DIMD TWICE x FOR B FOR C Multiple-dimensioning has been attempted. Revise DIM NEXT B statements. error, FOR C is cancelled NEXT C error, FOR B is cancelled NEXT A DIMENSION TOO LARGE or alternatively FOR A Run-time error; dimension too large in matrix operation. FOR B FOR C NEXT B error xxxxx DIV BY ZERO NEXT C error Run-time or compi Ie error. Zero denominatar encountered in expression evaluation. END error, MISSING NEXTSTMT

-EXEC- HALT xxxxx HALT

UTS only. Not an error condition. Execution has reached Normal message at termination of run the halt point (second line number) set by an EXE[CUTE] N l-N2 statement. xxxxx HAS BAD STEP NO.

xxxxx EXPONENTIAL OVERFLOW A GOTO, GOSUB, IF, ON, PRINTUSING, or RESTORE contains a step number having a first digit of zero or having Floating-point overflow during exponentiation. more than five digits.

c xxxxx EXTRA COMMA xxxxx HYPERB FUNCT OVERFLOW I Error indirectly associated with bad comma. Examples: UTS only. Floating-point overflow during evaluation of hyperbol i c function. Syntax

X + (Y, Y) Array reference without array designator ILLEGAL

SIN (A, B) Too many arguments in intrinsic function Illegal editorial type-in. Variety of possible causes. May be misspelled edit command, aconst too long, illegal PRO­ M(X, Y,Z) Too many subscripts in array reference CEED, bad format on RENUMBER, etc.

38 BASIC Messages ILLEGAL INPUT NO STMTS

Illegal input in off-I ine mode. (See RETYPE for on-I ine mode. ) Source input contained no BASIC statements. (Not used in on-line compilations.)

xxxxx INCOMPATIBLE DIMENSIONS NON-EXISTENT LINE # Dimensions not compatible in matrix operatic;,. Examples: matrix identity or inversion on non-square matrix. Wrong In execution mode, a direct statement references a step dimensioning for matrix multiplication or addition, etc. number that is not in the compiled program.

xxxxx INVERSE TRIG FUNCT ERROR xxxxx NON-NUMERIC VAL

UTS only. Illegal argument for arcsine or arccosine. UTS only. VAL function argument (string expression) does not represent a number. xxxxx LINE TOO LONG xxxxx NON-POSITIVE DIMENSION Renumber operation has created source I ine too long for input/ output, or more than 85 characters in a line. Run-time error. Zero or negative dimension encountered in matrix operation. xxxxx LOG OF NON-POSITIVE ARG

Argument in logarithmic operation is not greater than zero. xxxxx NO OPEN INPUT FILE

xxxxx MISSING ARRAY x xxxxx NO OPEN OUTPUT FILE Not in UTS. Array was not allocated by "originating" Run-time error. Input or output (GET, PUT, MAT GET or BASIC program. (Occurs only in direct-execution mode.) MA T PUT) attempted without prior OPEN statement.

MISSING NEXTSTMT NO PROGRAM At least one FOR statement occurred without a matching. Source program does not exist for specified Iines or ranges NEXT statement; that is, there were more FORs than NEXTs. in edit statements. Example: statement was LIST 10-50, but no lines exist with numbers between 10 and 50. MISSING STEPS xxxxx NOT A DIRECT STMT xxxxx In Batch/BTM BASIC the following statements are not allowed The listed step numbers were referenced (via GOTO ••• ON, for direct execution. GOTO, GOSUB, IF, ON, PRINTUSING, or RESTORE), but did not appear as recognized statement numbers. DATA Image DEF NEXT MTRX/VEC x DIM ON FOR PRINTUSING Not in UTS (see "ARRAY CLASS CONFLICT" for UTS). GOTO ••. ON Message indicates conflicting use of array x.

UTS BASIC does not allow xxxxx NEGATIVE BASE TO A NON INTEGRAL POWER DATA Image Fractional exponentiation indicated but number is negative. DEF NEXT FOR

NO DIMSTMT ARRAY x OLD FILE Array is used in MAT statement or (UTS) string statements, but not dimensioned. SAVE ON was attempted on an existing closed file.

BASIC Messages 39 xxxxx OUT OF DATA xxxxx RUN INTERRUPTED

Not enough data for INPUT, READ or GET statements in UTS only. Message issued after "Break II (not error condition). off-I ine mode.

xxxxx OUT OF RAN GE REF. TO ARRAY x xxxxx SHOULD BE DATA STMT

Matrix operation in SAFE mode has referenced an index xxxxx was referenced in a READ or RESTORE statement but greater than maximum dimension for array x. was not a recognizable DATA statement.

xxxxx OVERFLOW xxxxx SHOULD BE IMAGE STMT

Floating-point overflow. xxxxx was referenced in a PRINTUSING statement but was o not recogn izabl e Image statement. xxxxx PAREN ERROR xxxxx SINGULAR MATRIX Message indicates a parenthesis imbalance. Inversion or simultaneous equation solution attempted on xxx xx POWER OVERFLOW si ngu lar matrix.

Floating-point overflow in t operation. xxxxx SQR ROOT OF NEG ARG xxxxx PROG TOO BIG Argument of square root function is negative. Program exceeds available memory. (Under UTS, try FILE PACK and possibly clear arrays and strings to recover waste xxxxx TOO MANY GOSUBS BEFORE RETURN space.) The return stack for GOSUB-RETURN logic is full and a G OSUB has been encountered. RECOMP FOR DIR ST ABORTED

UTS only. An error was encountered during recompilation xxxx TRIG FUNCTION OVERFLOW for a dependent direct statement or EXECUTE N l-N2. Recompilation is aborted. UTS only. Cotangent, secant, or cosecant evaluation yields floating-point overflow. xxxxx RESTORE TO A NON-DATA LINE xxxxx UNABLE TO OPEN xxxxx RESTORE statement indicates line other than DATA line. Attempt to open named file failed. File is probably not present, or has another account number. xxxxx RESTORE TO A NON-EXISTENT LINE

RESTORE statement indicates nonexistent line number. xxxxx UNDEF FNx

t RETYPE No DEF statement appeared for user function FNx.

Input error encountered in on-I ine mode. The arrow poi nts to the character at which error was noted. Execution is not ab­ xxxxx $TRING EXPR ERR orted. Retype input starting at beginning of the erroneous datum. Do not type carriage return or line feed before retyping. UTS only. Illegal string expression. Reasons may be varied.

xxxxx RETURN WITHOUT GOSUB xxxxx ZERO TO A NEGATIVE POWER Return statement reached but return stack is empty. Indi­ cates improper nesting or branching on GOSUB-RETURNs. 1operation attempted to raise zero to negative power.

40 BASIC Messages APPENDIX A. SUMMARY OF BASIC STATEMENTS

The complete set of BASIC statements is shown below. Capital letters indicate syntax that is required as shown. Lower case letters designate generic items. Command parameters enclosed by braces ({ }) indicate a required choice. Parameters en­ closed by brackets <[J) are optional. Ellipsis marks (.•. ) denote multiple occurrences of the preceding bracketed parameter. Unless otherwise noted, "variable" means either a simple or a subscripted variable. If the initial step number of a statement is enclosed by brackets, the statement may be executed directly in the on-line mode of operation. If it is enclosed by paren­ theses, it may be executed as a direct statement in UTS BASIC only.

Statement Page

step: [Is and/or characters to end of line] 17

ste ] CHAIN xname [[iPassword] [:acct no]] 15 [ p :occt no iPossword [step] CLOSE {bl [characters to end of line] 15

step DATA [[±]constant] [ [[±]constant]] ••. 8 aconst aconst

step DEF FN letter (simpl e variable [, simple variable] •.. ) '" expression 16

(step) DIM letter (dimx[,dimx]) [, letter (dimx [,dimx])] 16

[step] END 8

step FOR simple variable = expression TO expression [STEP expression] 9

[step] GET variable [, variable] •.• 15

[step] GOSUB step 13

[step] GOTO step 7

(step) GOTO step [, step] ..• ON expression 14

ste ] IF {expreSSiOn} {conditiOn} {expresSiOn} THEN} step 6 [ p aconst operator aconst { GOTO

[step] INPUT variable [, variable] 12

expreSSiOn} bl [ • bl ] {eXpression}] ••• 6 [step] [LET] variable [, variable] ••• {aconst Lrvaria e , varia e .,. aconst 20 [step] MAT aname = (expression)*aname 20 [step] MAT aname aname 20 [step] MAT ana me = aname {±} aname 20 [step] MAT aname = aname * aname 20 [step] MAT aname = CON [(dimx ['dimx] )]

ndim~ ] 19 [step] MAT ana me = ION L(dimx ,[any characters to end of line] [step] MAT aname = INV (aname [,simple variable] ) 20

[step] MAT aname = SIM (aname [,simple variable]) 21

Appendix A 41 [step] MA T aname TRN (aname) 20

[step] MAT aname == ZER [(dimx [, dimx] )] 20

[step] MAT GET adescr [, adescr] •.. 18

[step] MA T INPUT adescr [, adescr] .•. 19

[step] MAT PRINT aname [t} aname] ••. e] 18

[step] MAT PUT aname [, aname] ••• 18

[step] MAT SIZEaname(dimx [,dimx]) [,aname(dimx [,dimx])] ... 19

step NEXT simple variable 9

(step) ON expression GOTO} step [, step] ... 14 {THEN

[step] OPEN xname [[iPaSsword] [:acct noTI[] {aI } rcharacters to end of line] 14 :acct no ipassworlJ ' L

[step] PAU SE 8

7, 11 [.tep] PRINTbt,;:;::~].[:{;xt string} expreSSion]' •. text string

(step) PRINTUSING step , {express~on}] 17 [ text string

rstep] PUT {expression} expreSSiOn}] 15 l aconst [ , {aconst

[step] READ variable [, variable] ... 8

[step] REM [characters to end of line] 8

[step] RESTORE [step] 13

[step] RETURN 13

[step] STOP 8

Statements Valid in UTS BASIC Only

step] CHAIN LINK xname [[iPassword] [:acct no]] 33 [ :acct no ipassword

step DATA [~:~~s~nstant][ n:~~s~nstant]] •.• 32 fstring ~string

30

[step] GET {va;iable} [{Va~iable}] ••• 32 string , string

42 Appendix A Command Page [step] IF string {conditiOn} {strexp } {THEN} t operator xstrexp GOTO 5 ep 32

[step] INPUT {va:iable} ~ {Va:iable}] ••. string ~ string 32

eXpreSSiOn} }] variable [(variable] ..• = [jvariable [(variable]. .. aconst {:~~~::Sion}} { [step] [LET] { xstrexp xstrexp .•. 31 stri ng = strexp str i ng strep

[step1 MAT GET {$letter[vordimJ} [ {$letter[vardimJ}] ••• :J odescr I adescr 32

[step1 MAT INPUT {$Ietter [vardim ]].[ {$Ietter [vardim ]}] •.. :J adescr I odescr 32

[step] MAT PUT {$Ietter} [I {$Ietter}] ••• aname aname 32

30

i ' ] text stri ng [xstrexpJ '. ex ressiont [step] PRINT text stn ng {'} xstrexp [p ] .' xstrexp 32 [ expression ' xstrexp {' } ; expression text string

[step] PRINT USING step [ {:~;;::S!on}J 32 text strmg

32

rste ,1 READ {va:iable} [, {va~iable}] l' PJ string string 32

tThis expression may not contain the character + as its initial significant character.

Appendi x A 43 APPENDIX B. BASIC EDITING COMMANDS

The BASIC editing commands are shown below. Capital letters indicate syntax that is required as shown. Lower case letters designate generic items. Command parameters enclosed by braces ({ }) indicate a required choice. Parameters enclosed by brackets ([]) are aptional. Ellipsis marks (••• ) denote mu Itipl e occurrences of the preceding bracketed parameter.

Command Page

ACC COUNT] [string] @ 25

ARR[AYS] ]t 23,33 CLE [AR] [ STR[INGS] @

DEL [ETE] line #2} line #4}J ..• 23 {:;~::1 - [Iii;::3 - e

ENT [ER BASIC] [L] e 25

EXE [CUTE] t step 1 [- step ] 34 2 e

EXT [RACT] rline # ] [{ line If I] 24 ~ine #1 - line #2 'line 113 - line #4 .,. e

FAS [T] @ 24

FIL [E] [PAC [K]r e 23,34

23 LIS [T] :l-Ijne 11 ] [{,Iji;: line 1f }}" e [\;~: 2 :3 - 4

LOA [D] [xname] @ 23

NAM [E] [name] @ 25

t NUL [L] ~: ~t~~s]l e 33 [SIM [VARS]J

PAS [SWORD] [string] e 25

PRO [CEED] @ 35 24 REN [UMBER] rteP1 tsteP2 [, incr]J] @ 24 RUN e {N} [Iinell 1[{Iine# }U 23 SAY [E 0] VER xname linell -line #2J[ linell -line #4~'" 1 3 e

t SET {$h digits [,character = digits] ... @ 24,34 c aracter }=

STA [TUS] @ 25 SYS [TEM]@ 26 WID [TH] digits e 25 t UTS BASIC only

44 Appendix B APPENDIX C. BASIC INTRINSIC FUNCTIONS

Function Result

SIN(arg) Calculates sine of argument in radians.

COS(arg) Calculates cosine of argument in radians.

TAN(arg) Calculates tangent of argument in radians.

ATN(arg) Calculates arctangent of unitless argument in radians.

EXP(arg) Calculates exponential functions, that is e(argument).

ABS(arg) Calculates absolute value of argument.

LOG(arg) Calculates natural logarithm (base e) of the argument.

LGT(arg) Calculates common logarithm (base 10) of the argument.

SQR(arg) Calculates square root of argument.

that is, the greatest integer that is less than or equal to the INT(arg) Acquires the integer part of the argument, argument.

SGN(arg) Identifies algebraic sign of argument, and produces a -1 for negative arguments, a 0 for 0, and a +1 for positive arguments.

RND(arg) Produces, for each call, the next element of a sequence of uniformly distributed random numbers that are greater than 0 but less than 1. If arg is 0 for the first RND call of a program, the identical sequence of random numbers will be generated if the program is rerun and arg is not changed. Otherwise, an unre- peatable sequence wi II be generated.

DAY(arg) Supplies the calendar day. If the argument is 0, the output is mon ddt as in Mar 07. If the argument is nonzero, the output form is a floating-point number whose integer part represents the month, and whose fractional part represents the day of the month divided by 100. For example, 3.07EO represents March 7.

TIM(arg) Suppl ies the time of day. If the argument is 0, the output form is hh:mm, as in 15:09. If the argument is nonzero, the output form is a floating-point number whose integer part represents the hour and whose fractional part represents the minutes divided by 60. For example, 15. 15EO represents 3:09 PM.

YER(arg) Supplies the year. If the argument is 0, the output form is 19yy, as in 1969. If the argument is nonzero, the output form is a floating-point number whose value is equal to the year, as in 1969.0EO.

MAX(arg ) Selects the maximum value in the Iist of arguments. n

MIN(arg ) Selects the minimum value in the list of arguments. n

TAB(arg} Advances the print device to the column designated by the argument, and should only be used in a PRINT statement. TAB cannot be used to backspace the print device.

PRC(arg) Specifies the number of significant digits in printed output, and is used only in a PRINT statement. An argument of 0 specifies 6-significant-digit output format, and a nonzero argument specifies 16- significant-digit output.

Appendix C 45 The following functions are in UTS BASIC only.

Function Result CSC (arg) Calculates cosecant of an argument in radians. Overflaw results in an error message and termination of execution.

SEC(arg) Cal culates secant of an argument in radians. Overflow results in an error message and termination of execution.

COT{arg) Calculates cotangent of an argument in radians. Overflow results in an error message ond termination of execution.

ASN(arg) Calculates arcsine of a unitless argument, in radians. If the absolute value of the argument is greater than 1.0, an error message is printed and execution is terminated. Resolution of results is restricted to the two quadrants from -1T/2 to 1T/2.

ACS(arg) Cal culates the arccosine of a unitless argument, in radians. If the absolute value of the argument is greater than 1. 0, an error message is printed and execution is terminated. Resolution of results is re- stricted to the two quadrants from -0 to 1T.

HSN{arg) Calculates hyperbolic sine of an argument. Overflow results in an error message and terminatian of execution.

HCS(arg) Calculates hyperbolic cosine of an argument. Overflow resul ts in an error message and termination of execution.

HTN{arg) Calculates hyperbolic tangent of an argument.

LTW{arg) Calculates logarithm, base two, of an argument.

DEG(arg) Converts argument to degrees, from radians.

RAD{arg) Converts argument to radians, from degrees.

LEN (strexp) Gets current number of characters in string expression, as floating-point number.

VAL (strexp) Gets numeric value of string expression as floating-point value. Error exit if string expression not numeric

STR{expression Converts numeric value of expression to string format. Optional rstring argument permits specific format- [, rstri ng]) ting. If second argument is not used, standard print output format is used.

46 Appendix C APPENDIX D. TECHNICAL ASPECTS OF MATHEMATICAL RUN-TIME FOR BASIC

For a complete description of the routines used to evaluate The matrix package provided uses the most apparent and the elementary functions, the reader is referred to XDS natural algorithms for all operations except inversion and Sigma 5/7 Mathematical Routines Technical Manual, Pub­ solution of simultaneous linear equations. For both of these lication No. 900906. The algorithms used are described cases, Gauss-Jordan reduction with partial positioning for in catalog numbers 705002, 705004, 705006, 705008, size is used. The values of the orgument matrix are not re­ 705012, 705014, 705016, 705018, 705020, 705023, and tained, since this time-consuming function is often not 705027 in that publ ication. required. The matrix copy facility is provided for users who require retention. The time in microseconds to invert a The following are typical timings in microseconds. matrix of order n may be approximated by the formula

Routine Time Routine Time 3 2 24n + 90n - 85n + 360 LOG,LGT,LTW 200 t (power) 390 EXP 180 SEC,CSC 195 The random number generation technique used is a power SIN,COS 145 COT 280 residue method using the least significant 31 bits of the ATN 200 ASN,ACS 400 previous number and 65,539 as multipliers to develop a pro­ SQR 125 HSN,HCS 245 duct from which the 31 least significant bits are extracted. TAN 275 HTN 250 This integer is divided by 231 and the result extended to double precision floating form. The first 1,000,000 entries of the standard sequence have been sub jected to ch i-square, The user may expect more than 50 signifi cant bits in output length of run, and autocovariance (with lags of 1,2,4,8, resulting from these procedures. 16,32, and 64) analyses with very satisfactory results.

Appendix D 47 INDEX

Note: For each enfry in this index, the number of the most significant page is listed first. Any pages thereafter ~re listed in numerical sequence.

! (Executive prompt), 22,26 current dimensioning, 18 > (prompt), 22 Cursor Return key, 22 : (image), 17 # (digit position), 17 o A data input, 8 data output, 7 absolute dimensioning, 18 DATA statement, 8,3,13,25 ACCOUNT command, 25 decimal point, 17,5 aconst, 10 deck setup, 28 aconsts from strings, 32 DEF statement, 16,25 ACS function, 33 DEG function, 33 adescr, 18 DELETE command, 23,35 aophanumeric constants, 10 arithmetic operations, 6 dependent statements, 35 desk-calculator mode, 25 arithmetic operators, 5 DIM statement, 16,17,25 arithmetic unit, 1 dimensioning, 16 array addition and subtraction, 20 dimensioning, absolute, 18 array descriptor, 19 dimensioning, current, 18 arrays, 10 dimx, 19 ASN function, 33 direct statements, 25,35,36 B division, 2 BASIC messages, 37 batch processing, 26 E braces, 5 brackets, 5 editing commands, 44 branching, 6 editing mode, 22 branching to a subroutine, 13 END statement, 8 BREAK action, 34,35 ENTER command, 25 BY command, 26 error messages, 35,6 Escape key, 22 Escape key activation, 24 C exclamation point, 22 ca II i ng BASIC, 22 EXECUTE command, 34 capital letters, 5 executive level prompt, 22,26 card parameters, 27 exponential notation, 3 CHAIN LINK statement, 33 expr, 6 CHAIN statement, 15 expression, 6 character string manipulation, 30 external data input, 12 CLEAR command, 23,25,33 external name, 15 CLOSE statement, 15 EXTRACT command, 24 coding sheet, 26 commands, 6 commentary, 8 F compilation and execution mode, 24 FAST command, 24,25 conditional branch, 6 FILE command, 23 cond i ti onal operators, 7 file manipulations, 14 consecutive programs, 15 file operations, 25 control unit, 1 FILE PACK command, 34 conventions, 5 floating-point notation, 3 conversion to a string, 31 FN user function I. D., 16 copy statement, 20 FOR and NEXT loop, 8 COT function, 33 FOR statement, 9,25 CSC functi on, 33 functions, 5,10

48 Index Note: For each entry in this index, the number of the most significant page is listed first. Any pages thereafter are listed in numerical sequence. G N GET statement, 15 NAME command, 25 GOSUB statement, 13 nested loops, 9 GOTO statement, 3,7,14 New Line character, 22 GOTO ••• ON statement, 14 New Line key, 22 NEXT command, 25 NULL statement, 33 H number ranges, 12 HCS functi on, 31 HSN function, 31 o HTN function, 31 ON statement, 13 on-line operations, 22 on-line verification, 25 OPEN statement, 14 IF ••• THEN statement, 6,2 output, 7 i mage statement (step:), 16,25 input, 8,12 p I N PUT statement, 12 input/output devices, packed format, 11, 18 INT function, 5 parallel assignments, 6 intrinsic functions, 5,10,32,45 parameter setting, 23,32 INV statement, 20 PASSWORD command, 25 PAUSE statement, 8 period, 5 L PRC designation, 12 LEN function, 31,46 preci si on of output, 25, 12 LET statement, 2,3,6 Prefix key, 22 line deletion, 23 print formats, 11 line extraction, 24 print images, 17 line insertion, 22 PRINT statement, 3,4,7,25 Li ne Space key, 22 printer width, 25 LIST command, 23 PRINTUSING statement, 16,25 LOAD command, 23,25 PROCEED command, 24,36 loop dtection, 26 . program loading, 23 looping 8,4 prompt character (», 22 lower cose letters, 5 PUT statement, 15 LTW function, 33 R M RAD function, 33 MAT CON statement, 19 READ statement, 8,3 MAT GET statement, 19, 15 regular format, 11,18 'MAT ID N statement, 19 REM statement, 8 MAT IN PUT statement, 19 RENUMBER command, 24 MAT PRINT statement, 18 rereading data, 13 MAT PUT statement, 18,15 RESTORE statement, 13 MAT READ statement, 19 RETURN statement, 13 MAT SIZE statement, 19, 18 Return key, 22 MAT statements, 18 RUN command, 24,25 MAT ZER statement, 19 matrix, 10 matrix inversion, 20 s matrix multiplication, 20 sample program, 1,26

matri x operationsl 18 SAVE command, 23 matrix transposition, 20 scalar multiplication, 20 memory unit, 1 SEC function, 33 multiple path branching, 14 series assignments, 6 multiplication, 2 SET command, 24

Index 49 Note: For each entry in this index, the number of the most significant page is listed first. Any pages thereafter are listed in numerical sequence.

SET $ command, 32 text, 12 sign off, 26 text I isti ng, 22 SIM statement, 21 text saving, 22 simple constants, 5 text string, 7,12 simple variables, 5 Hiles, 15 simultaneous equation solution, 41 TRN statement, 20 statements, summary of, 21 STATUS command, 25 step numbers, 5 STOP statement, 8 u STR function, 31 user-defined functions, 16 string assignment to string variable, 31 UTS BASIC operating procedures, 35 string comparison, 32 string concatenation, 31 string expressions, 31 string input/output, 32 v string length and val ue assignments, 31 VAL function, 31 string variables, 30 subscripted variables, 10 summary of statements, 41 w SYSTEM command, 26 WID TH command, 25 T TAB function, 11 x temporary files, 15 xname, 14

50 Index t