Digital Equipment Corporation BASIC-PLUS-2 Language Manual
PDF
Documento
Anúncio
Anúncio
BASIC-PLUS-2
Language Manual
Order No. AA-0153A-TK
July 1977
This document describes the elements of the BASIC-PLUS-2 language
that are common to the DECSYSTEM-20 and the PDP-11. System
dependent information is found in the appropriate user's guide.
This is a new document.
OPERATING SYSTEM AND VERSION: TOPS-20 VO?
RSTS/E VO6GB
RSX-11M VOS
IAS VO?
SOFTWARE VERSION: BASIC-PLUS-2 VO1
To order additional copies of this document, contact the Software Distribution
Center, Digital Equipment Corporation, Maynard, Massachusetts 01754.
digital equipment corporation - maynard, massachusetts
First Printing, July 1977
The information in this document is subject to change without notice and should not be construed as a commit-
ment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors
that may appear in this document.
The software described in this document is furnished under a license and may be used or copied only in accordance
with the terms of such license.
Digital Equipment Corporation assumes no responsibility for the use or reliability of its software on equipment
that is not supplied by DIGITAL.
Copyright © 1977 by Digital Equipment Corporation
The postage prepaid READER'S COMMENTS form on the last page of this document requests the user's critical
evaluation to assist us in preparing future documentation.
The following are trademarks of Digital Equipment Corporation:
DIGITAL DECsystem-10 MASSBUS
DEC DECtape OMNIBUS
PDP DIBOL О5/8
DECUS EDUSYSTEM PHA
UNIBUS FLIP CHIP RSTS
COMPUTER LABS FOCAL RSX
COMTEX INDAC TYPESET-8
DDT LAB-8 TYPESET-10
DECCOMM DECSYSTEM-20 TYPESET-11
7/77-14
PREFACE. . . . ..
CHAPTER
BR WW О 1 во —
— о —
СНАРТЕК
10 го —
> ww
un Dd wi —
o
12 EJ EY Y EY EY IED EII IEEE IEEE
Oomph we LOHR
CHAPTER
‘0 Ww
PO PO IO to = Но о
LU to —
tv —
woo Lu WwW Wo QU Lo
Wo
CHAPTER 4
4.1
CONTENTS
inl
Page
Ce aa eno nan aa ra iX
PROGRAMMING IN BASIC . aaa 1-1
INTRODUCTION... aaa 1-1
STRUCTURL OFF A BASIC PROGRAM ©... ине [-1
Character Set... aaa 1-1
Line Format . oo aaa aaa 1-2
STATEMENTS aaa aaa aaa 1-3
Single Statement, Multi-Statement, and Continuation Lines... 1-3
DOCUMENTING PROCEDURES --
THE REM STATEMENT AND THE COMMENT ©... 1-4
ELEMENTS OF BASIC-PLUS-2 aaa 2-1
TERMINOLOGY L.11 1100 LL LL LL LL LL LL LL ALL LL 2-1
CONSTANTS © LL A LL A LL A A NA A LL ALL LL LL 11110 2-1
Numeric Constants aaa aaa 2-1
Integer Constants... . 2
String Constants .. 2
VARIABLES 1111111141 LL A LA LL LL LL LL LL 1111111101 2-3
Numeric Values . oo... LL LL LL LL LL LL LL 1100 2-4
Integer Values . . oo. LL LL LL LL LL LL LL 0 2-4
String Variables... . LL LL LL LL LL LL 11111000 25
Subscripted Variables .. 1111111110 LL LL LAN LL LL LL LL LL 2-6
FORMING EXPRESSIONS 1121111111 LL AL ALL LL LL LL LL LL 10 2-7
Arithmetic Expressions ....... LL LL LL LL LL LL 110 2-7
String Expressions ... 111104111111 2-8
Relational Expressions ...... LL LL LL LL LL LL 110 2-8
Comparing Strings Using Relational Operators ......... еее, 2-8
Logical Expressions ...... LL, 2-10
Functions © aaa aaanonenorAenern—, 2-11
Evaluating Expressions ..... aaa aaa 2-11
ASSIGNING VALUES TO VARIABLES THE LETSTATEMENT ..... 2-12
ARRAYS aaa aaa aaa 2-14
The DIM Statement .. 1112111010 LL LL LL LL LL LL LL LL 2-15
INPUT AND OUTPUT TO THE TERMINAL . . .. À 3-1
SUPPLYING DATA... aaa 3-1
The INPUT Statement... oo. aaa aa 3-1
The INPUT LINE and LINPUT Statements... ...... 3-3
READ, DATA, and RESTORE (RESET) Statements . ..........._. 3-4
CHECKING OUTPUT - THE PRINT STATEMENT . . ... 3-0
Printing Zones -- The Comma and the Semicolon ......... 11 0 3-8
Output Format for Numbers and Strings ........ ...... 3-10
The TAB Function... LL LL LL 3-11
FORMATTED OUTPUT - THE PRINT USING STATEMENT . . ........ ...... 4-1
INTRODUCTION TO PRINT USING . ©... aaa 4-1
CHAPTER
CHAPTER
- Bee eee
y lv 1919 1919 19 19.19 19
Ls ad e e El
e 3
т.
no La
4.6
1.0.
+
<
un
ie ль ii AAN AAA A UN A
bd 1D II ED tla te — — — =
A
UY
LN + ‘ло ‘
бл ль AA A A A NA
vr
Fam
—
~~
-
. » . .
— — — —
rain pp wi Ù
Ta
‘о 19 о ——
ud
Lys Es —
E AI
Un A
.
~~
—
sd td =
LG y —
an
<
—
|)
to
CONTENTS (CONT.)
Page
PRINTING NUMBERS WITH PRINT USING... o.oo 4-2
Specifying the Number of Digits... ooo ooo KK НН 4-2
Specifying the Location of the Decimal Point ©... 2.2. Lee ee eee 4-3
Printing a Number That is Larger Than the Field ......... 2.2002... 4-4
Printing Numbers With Special Symbols... 20000... 4-5
Printing Numbers With a Trailing Minus Sign... ooo ooo ooo о 4-5
Printing Numbers in Asterisk Fill Fields ©... ,.—— 4-5
Printing Numbers With Floating Dollar Signs... o.oo... o.oo coon ooo 4-6
Printing Numbers With Commas ......... 0.00. a eee ee eee se 4-6
Printing Numbers In E (Exponential) Format ...... 0... on 4-6
Fields That Excced BASIC's Accuracy . eee 4-7
PRINTING STRINGS WITH THLE PRINT USING STATEMENT ©. o.oo... 4-7
One-Character String Fields . o.oo ooo RK 4-7
Printing Strings in Left-Justified Format ..... .... 0.0000 eee 4-7
Printing Strings In Right-Justified Format... ........ ooo .. 4-8
Printing Strings In Centered Fields o.oo... oo oo ooo oo ooo 4-8
Printing Strings In Extended Fields... ooo ooo 4-9
SUMMARY OIF PRINT USING FORMAT ©... o.oo oo 4-9
THE IMAGE STATEMENT 1.2... к.кв нео 4-11
PRINT USING STATEMENT ERROR CONDITIONS ©... o.oo ooo 4-11
Fatal Error Conditions ... eee ae 4-12
Warning Conditions .... eee RK 4 A ee 4e eee a a ee 4-12
CONTROL STATEMENTS eee 5-1
TRANSFERRING CONTROL OF THE PROGRAM... ................... 51
Unconditional Transfer - The GOTO Statement ©... o.oo ooo oo, 5-1
Multiple Branching The ON-GOTO Statement... .................... 52
Conditional Transfer The IIF-THEN-ELSE Statement... ............... 53
EXECUTION OF LOOPS ©. eee 5-5
The FOR and NEXT Statements oo... oo eee 5-5
Nested Loops . 2... 2.0 A 4 LL 4 A 44 Se LR A LA 4 A ee ee LS 5-8
The Conditional FOR Statement ........ 2... о 5-10
The FOR Statement With Additional Test oo... ooo co oo ooo 5-11
WHILE And UNTIL Statements ©... o.oo se 5-12
TIME LIMITS ea aa A A A1 ee 5-12
The SLEEP Statement oo A 5-12
The WAIT Statement ..... . aaa A es 5-13
STOPPING PROGRAM EXECUTION THE STOP AND END STATEMENTS ©... 5-13
SUBROUTINES © aaa A LA A A4 LR 4 AR A4 ee ee 5-15
The GOSUB and RETURN Statements ..... 2, 5-15
The ON-GOSUB Statement . .... ee ee eee 5-16
ERROR CHECKING © © 1J
ONERROR GOTO and RESUME Statements ..... 2.2220 5-17
Error Table eee 5-18
STATEMENT MODIFIERS © © aer 1 eee 6-1
MODIFYING STATEMENTS ©. aaa 4 LL A4 14e 1e 6-1
The TF Modifier ...... нк 6-1
The UNLESS Modifier ..... ee 6-2
The WHILE Modifier ...... aa 6-3
Iv
CONTENTS (CONT.)
Page
6.14 The UNTIL Modifier RR 6-4
6.1.5 The FOR Modifier .. 111220011401 LL 4 LL LL A LA 44 LA ae a 1 2 2 6-4
CHAPTER 7 FUNCTIONS .. 1111111411 LL A LA 4 4 LL LL LA A A a LA LL LA a a aa a 2 7-1
7.1 TYPES OF FUNCTIONS AVAILABLE ........ aaa 7-1
7.2 NUMERIC FUNCTIONS . © ee 7-1
7.2.1 Trigonometric Functions (SIN, COS, TAN, ATN, and PI) . ................ 7-1
7.2.2 Algebraic Functions .. 111220000144 LL LL LL LL A LL LL LL A a a 1 2 7-3
7.2.2.1 Square Root Function (SQR) . aaa a A a aa ee 7-4
7.2.2.2 Exponential and Log Functions (EXP, LOG, and LOGI10). ................ 7-4
7.2.2.3 The Integer Function (INT)... ea 7-5
72.24 The Absolute Value Function (ABS) ea ae 7-7
7.2.2.5 The SIGN(SGN) And FIX(Fix) Funetions .. 1111110101 00111 LL 114 a 20 7-8
7.2.3 Random Numbers (RND And RANDOMIZE) .. 1.111111 1111 LL LL LL 144 7-9
724 The MOD Function ... 1201004410 LL 44 LL LA LL LA LL LL LL ALL LL 240 7-10
7.3 STRING FUNCTIONS © eee 7-11
7.3.1 Finding the Length of a String (LEN)... .... 7-11
7.32 Trimming Trailing Blanks (TRMS) ...... LL LL LL LL AL 1 144 7-11
7.3.3 Finding the Position of a Substring (POS, INSTR) . . .................... 7-12
734 Extracting a Segment from a String (SEGS) . ... LoL 7-13
7.3.5 The MID Function . . oe 7-14
73.6 The LEFTS and RIGHTS Functions .......... 2... eee. 7-15
7.3.7 The STRINGS and SPACES Functions ........ 2.2... 000. 7-16
7.3.8 The EDITS Function ......... aaa aaa reneneare ra 7-17
74 CONVERSION FUNCTIONS ©... aaa eee eee 7-18
7.4.1 Character and ASCII Code Conversions (ASCII and CHRS) ................ 7-18
74.2 Converting the ASCII Code to a Character ......... 2... eee. 7-19
7.4.3 Converting an Integer to RADIX-SO(RAD) ....... eee 7-20
744 The CHANGE Statement ....... ee ie 7-20
7.4.5 Numbers and Their String Representation (VAL and STRS) ............... 7-21
7.5 DATE AND TIME FUNCTIONS © ©... 7-22
7.0 USER-DEFINED FUNCTIONS - THE DEF STATEMENT -...... e. 7-23
7.6.1 Single-Line DEF ....... a aaa aaa aa en 7-23
7.6.2 Multi-Line Function Definitions . . . . . 4 LL LA 4 aa a 7-26
7.6.2.1 Multi-Line DEFF 1111100000 LVL LL LL LL AA LL 4 A A A AA LL LL A Le 7-28
CHAPTER 8 ARRAYS 111111 LL LL LL LL LL LL A LL A LL LL ALL LL LL 11140 8-1
8.1 DIMENSIONING AN ARRAY 1112201111 LL LL LL LL LL LL LL LL 8-1
8.2 INITIALIZING AN ARRAY e. aaa a 8-1
8.3 MATRIX OPERATIONS . 12211111 LL LL LL LL LL ALL LL LL a LL 8-3
8.4 ARRAY INPUT AND OUTPUT . . aaa 8-4
84.1 MAT INPUT Statement 1221114 LL LL LL LL LL A 4 LL A LA LA A A a CL ae 8-4
84.2 MAT PRINT Statement... L LL LL LL LL 1 LL LL LL LL A LA 210 8-5
84.3 MAT READ Statement . . . ea 8-5
844 MAT Functions TRN, INV, DET .. aaa 8-0
CHAPTER 9 WORKING WITH FILES ©... aereo. 9-1
9.1 FILES aaa aaa aaoanveddera ee nena 9-1
9.2 TERMINAL-FORMAT FILES . aaa 9-1
CONTENTS (CONT.)
MER
Page
9.2.1 Opening Terminal-Format Files... o.oo ooo 9-1
92.2 Closing Terminal-Format Files ..... ... 2.290... 9-3
9.2.3 Reading Data From A Terminal-Format File ....... 2... 9-4 -
9.2.3.1 The INPUT LINE # and LINPUT F Statements... ...... 2.0... ere 9-5
9.2.4 Writing To A Terminal-Format File . . .. .. e... 0,0... 9-5
9.2.5 Restoring A Terminal-Format File ......... 2.029.000. 9-6
9.2.6 Checking for the End of a Terminal-Format File . ..................... 9-7
9.2.7 The IFMORE Statement ....... eee 9-7
9.2.8 The NODATA Statement ...... eee 9-7
9.29 Changing Margins .. 11004204 44414 LL 4 4 A 44 A 44 Recrear oran e 9-8
9.2.10 Sctting Page Size . oe 9-8
9.3 VIRTUAL ARRAYŸ FILES. 1.201001 44 LA LA A4 ALL AL A4 144 4 1124 9-9
9.3.1 Dimensioning A Virtual Array File . . ... 4 LL LL LL 1140 9-9
9.3.2 Opening and Closing Virtual Array Files ©... .... .. .. .. ... 9-10 me
94 FILE RENAMING AND DELETION ©. oo A 4 La 1 LL 2 9-11
94.1 The NAME-AS Statement ......... ee 9-12
94.2 The KILL Statement ....... eee 9-12
CHAPTER 10 RECORD I/O ee 46 10-1
10.1 RECORD FILLES oe 10-1
10.1.1 File Organization ... 120120044044 1 4 4 A 44 4 4 4 A4 4 A 4 ALL LA 1114 0e 10-1
10.1.2 Access Methods. ........ ee 10-2
10.1.3 Record Format .. 11211110 1 LL LL LL LA 4 A LA A LL A A LL LR a 12 10-2 -.
10.1 4 Record Mapping ee A LL LVL 4 La LL 4 A A A 4 1114 10-3 |
10.2 FILE OPERATIONS © aaa econo nerarrn 10-5
10.2.1 Creating and Accessing a File .. 1.121200 100104 Le LL La LL LL LL 0 10-5
10.2.1.1 Opening a Sequential File ........... e rererered er ia0nrer. 10-8
10.2.1.2 Opening a Relative File... 0 0 oo aaa aone ne 10-9
10.2.1.3 Opening an Indexed File 1... 121001040141 L 4 LL LL LA LL LL 10 10-10
10.2.2 Closing Files... aaa aa aaa ea e nao a dea 10-10
10.2.3 Restoring a File ......... aaa aa ae nerom onda 10-11
10.24 Truncatinga File ......... L LL 4 LA AR LA LL A A AL 1142 10-11
10.3 RECORD OPERATIONS . 12111111 aaa aaa oo naa 10-11 „=
10.3.1 Sequential Record Operations... .. 0r2e0.reoa ne ndecndeoareno 10-12
10.322 Relative Record Operations . o.oo... earn an e 10-12
10.3.3 Indexed Record Operations .. eee 10-14
1034 Record Locking ......... 0 aero onon on adenda nena 10-16
10.4 DYNAMIC MAPPING OF ANT/O BUFFER ee 10-16
CHAPTER 11 PROGRAM SEGMENTATION ...... aaa aan. 11-1
11.1 SUBPROGRAMS © ee [1-1
11.1.1 The CALL Statement .. 1.111020 0 LL LL A4 LL LA 4 A A A AR 4 LA A A a a ea 1 1-2
11.1.2 Dummy And Actual Arguments .. 11200114 нева 4 A A a Va 4e 11-2
11.2 TRANSFLRRING CONTROL TO ANOTIIER PROGRAM —
THE CHAIN STATEMENT © oe. 11-4
11.2.1 Preserving Variables The COMMON Statement. ........ e. [1-5
APPENDIX A SUMMARY OF BASIC-PLUS-2 STATEMENTS,
FUNCTIONS AND OPERATORS 1121111111 LL LA LA A A LL A La aa aa 1 Le A-1 AW,
Vi
METE EL AXE БЫ
APPENDIX B
APPENDIX C
APPENDIX D
FIGURE
TABLE
>
1 1 1 I
a [J — —
+
Aa 8 BV NND NND N —
=> NM
1 i
>
t
10-1
10-2
11-1
A-1
A-2
A-3
B-1
CONTENTS (CONT.)
Keywords and Spaces... ................ ....
Number Notations ...... aaa
Arithmetic Operators ........ 1 LL LL LL
Relational Operators .. 1.111111 1101 LL LL 1110
String Relational Operators .... 111111111100 2 0
Logical Operators ..... ..............
Truth Tables ..... aaa
Operator Precedence . oo... LL
Format Characters for Numeric Fields ............
Format Characters for String Fields... ...........
Error Table aaa
The Date and Time Functions . .... as
OPEN Statement ..... ee
Arguments ©...
Arithmetic Operators ...... aa
Logical OperatOrs . LS
Relational Operators ©... ........ . .........
ASCII Table as
Vil
aaa 2-10
Page
aaa aaa aaa B-1
aaa C-1
aaa aa D-1
aaa a aaa aaa 2-14
EN EE a AE a PT ea « . deat
4 ww Se + 4 = « « + 2» ww +s ee «© : = = a — —
aaa 4-10
aaa A-14
Ce aaa aaa A-15
a A-15
aaa B-1
MSIE
A ri
PREFACE
Because EASIC-PLUS-2 has been implemented on more than one system, this manual describes only the language
elements and statement syntax of BASIC-PLUS-2. It does not discuss system-specific information. In order to use
BASIC-PLUS-2 on your particular system, you must also read one of the following:
RSX/TAS BASIC-PLUS-2 User's Guide
RSTS/E BASIC-PLUS-2 User's Guide
DECS YSTEM-20 BASIC-PLUS-2 User's Guide
This document is not a tutorial manual. If you are unfamiliar with the BASIC language, you should also read
Digital’s Introduction to BASIC.
In the following manual (BASIC-PLUS-2 Language Manual) Chapters 1 through 5 describe the essential parts of a
BASIC-PLUS-2 program. Almost any problem can be solved with the statements and features in these chapters.
Chapters 6 through 11 provide the advanced features of BASIC-PLUS-2, which allow the BASIC language to be a
useful tool for the more experienced programmer. For a quick reference to the BASIC-PLUS-2 language elements,
refer to Appendix A.
Throughout the manual, BASIC-PLUS-2 and BASIC are used interchangeably. The User’s Guide referred to is the
BASIC-PLUS-2 User's Guide for your system.
Symbol
CTRL/X
TAB
P
_6
=
|
Lower-case letters
———
UPPER-CASE LETTERS
Examples
Conventions Used in This Manual
Represents
The CTRL key and another key pressed simultaneously (i.e., CTRL/C).
The RETURN key (carriage-return/line feed).
The TAB key (CTRL/I on some terminals).
The SPACE bar.
Special brackets indicating optional information that can be omitted from a
command string.
Braces indicating a choice. Choose one from the enclosed.
Lower-case characters in a command string indicate variable information to be
supplied by you.
Upper-case characters in a command string indicate fixed (literal) information that
you must enter as shown.
On the DECSYSTEM-20, when you list a BASIC-PLUS-2 program (or line in a
program) from storage leading zeroes are added to the line numbers (e.g., 10
becomes 00010).
All examples were produced on the DECSYSTEM-20. Most of them were stored,
recalled, and printed. Therefore, the line numbers in these examples contain
leading zeroes.
Symbol
Contrasting Colors
Conventions Used in This Manual (Cont.) E
Represents
Red — Where examples contain both user input and computer output, the
characters you type are in red; the characters the computer prints are in black.
Gray — The text shaded in gray indicates the features available only on the
DECSYSTEM-20.
Е
MRE
ME TE ! id : oil Ha ie
CHAPTER 1
PROGRAMMING IN BASIC
1.1 INTRODUCTION
BASIC (Beginner’s All-purpose Symbolic Instruction Code) is a computer language developed at Dartmouth College
under the direction of Professors John G. Kemeny and Thomas E. Kurtz. It is one of several programming languages
used to translate symbolic language programs into machine language. Because the BASIC language is composed of
easily understood statements and commands, it is onc of the simplest programming languages to learn.
BASIC provides an interactive human/machine relationship by allowing you to communicate directly with the lan-
guage processor. It is a conversational programming language that uses simple English-like statements and familiar
math notations to perform operations.
The BASIC-PLUS-2 language is an outgrowth of Dartmouth BASIC. It encompasses both the clementary statements
uscd to write simple programs and many new and advanced features. These new features, not found in standard
Dartmouth BASIC, allow you to produce more complex and efficient programs.
Some of the special features of BASIC-PLUS-2 are:
Virtual Arrays — Section 9.3
Record File 1/0 -- Section 10.1
Extensive String Support — Sections 2.2.3 and 2.3.3
Full Matrix Package — Section 8.1
Long Variable Names — Section 2.3
IF... THEN... ELSE - Section 5.1.3
ON ERROR -- Section 5.6
Statement Modifiers — Section 6.1
User-Defined Functions -- Section 7.6.2
Multi-Statement Lines — Section 1.3.1
Multi-Line Statements — Section 1.3.1
1.2 STRUCTURE OF A BASIC PROGRAM
A BASIC program consists of a sct of statements constructed with the language elements and syntax described in the
following chapters. Expressions, line numbers, and statements are joined to solve a particular problem, with cach
line containing instructions to BASIC.
1.2.1 Character Set
BASIC-PLUS-2 uses the full ASCII (American Standard Code for Information Interchange) character set for its
alphabet. This set includes:
|. Letters À through Z
2. Numbers O through 9
3. Special characters (see the ASCII Table in Appendix B)
This character set enables you to include any ASCII character as part of a program. BASIC translates the characters
that you type into machine language; some characters are processed and some are ignored. When BASIC does ignore
an ASCII character, it prints a warning message to that effect. (Refer to the User's Guide for diagnostic messages.)
1-1
Programming in BASIC
BASIC translates characters in the following manner:
I. Letters A through Z - BASIC treats the sume alphabetic in upper-case and lower-case as the same char-
acter, e.g., I is the same as 1.
2. Non-printing characters (e.g., BEL) - BASIC interprets the code during input, prints a warning message,
then ignores them during execution.
3. NUL characters - BASIC interprets the code during input, prints a warning message. and ignores them
during execution.
String constants are a different matter (as described in Section 2.2.3). Everything you type into a string constant is
interpreted literally by BASIC. Consequently, in a string constant:
|. All lower-case alphabetics (a, b, ¢) remain lower-case.
2. All non-printing characters are processed.
3. All null characters are processed.
BASIC also ignores all characters in a REMARK during execution. Sec Section 1.4.
System editing characters affect terminal output format only. Therefore, you need not be concerned, at this point,
with the way BASIC handles them. System editing characters, such as Control/U (FU) are described fully in the
User's Guide for your system.
1.2.2 Line Format
The format of à program line is as follows:
line number keyword statement tine terminator
e UE . e ни мл ME
00010 PRINT К = SQOQRCX 2 + Y 2)
Most lines in a BASIC program must begin with a number. (Continuation lines are another matter. Sec Section
1.3.1.) This number must be a positive integer within the range of 1 to a limit set by your system. Refer to the
User’s Guide for this information. A BASIC linc number is a label that distinguishes one line from another within
a program. Consequently, each line number in the program must be unique.
Leading zeroes (as well as leading and trailing spaces) have no effect on the number. However, you cannot have
embedded spaces within a line number. For example, these numbers arc the same to BASIC:
ИНН =
00010
10
But this number is illegal:
01 0
BASIC ignores leading and trailing blanks, spaces, and tabs within a linc (unless in a string enclosed by quotation
marks). Therefore, you need not worry about leading and trailing blanks when typing in a program. For example:
10 LET A=R+C
can also be typed:
10 LET A=R+C
Both lines are the same to BASIC.
Programming in BASIC
However, embedded spaces in line numbers, keywords (Section 1.3), or variable names are illegal. For example,
BASIC rejects the previous statement if you type it as follows:
1 0 L E Y A = В + C
1.3 STATEMENTS
BASIC statements consist of English-like words called keywords (words recognized by BASIC) that you use in con-
junction with the elements of the language set: constants, variables, and operators. These statements divide into
two major groups: executable statements and non-executable statements.
At least one space or tab must follow all statement keywords in order for BASIC to recognize the keyword as such.
For example:
This is acceptable 10 FRINT À
This is not 10 FRINTA
Certain keywords consist of two or more English words. Some keywords allow an optional space between words
and some keywords require a space between words. Table 1-1 lists these keywords.
Table 1-1 Keywords and Spaces
Optional Space Mandatory Space No Space
GO TO MAT INPUT FNEND
GO SUB MAT PRINT SUBEND
ON ERROR MAT READ
INPUT LINE
Statement keywords are reserved, and therefore, cannot be used as variable names (see Section 2.3). Appendix C
contains a complete list of reserved keywords.
1.3.1 Single Statement, Multi-Statement, and Continuation Lines
You have the option, with BASIC-PLUS-2, of typing either one statement on one line, several statements on onc
line, or one or more statements on several lines.
A single statement line consists of:
À line number (from |! to a system maximum)
À statement keyword
The body of the statement
A linc terminator
This is a single statement line:
10 LET A=RXC
To enter more than one statement on a single linc (multi-statement line), separate cach complete statement with a
backslash (\). The backslash symbol is the statement separator (or terminator). You must type it after every state-
ment except the last in a multi-statement line. For example, the following line contains three complete PRINT
statements:
10 PRINT ASNFRINT Vs NFRINT G
1-3
Programming in BASIC
The line number labels the first statement in a line. Consequently, you should take this into consideration if you
plan to transfer control to a particular statement within a program. For instance, in the previous example, you
cannot execute just the statement
FRINT Vs
without executing PRINT A: and PRINT G.
Most statements can appear in a multi-statement line. The exceptions are noted in the discussion of individual state-
ments in this manual.
The rules for structuring a multi-statement line are:
|. Only the first statement in a series can have a line number.
2. Successive statements must be separated with a backslash (\).
BASIC also provides a continuation character. an ampersand (&), in case the length of the statement or multi-
statement line exceeds the line.
If you are at the end of a line, and you want to continue it, type an ampersand (&) and then a line terminator. The
next character you type prints in column one of the following line. The continuation line cannot have a line num-
ber. You reference the entire line by the original line number.
BASIC looks at the character immediately preceding the line terminator. If this character is an ampersand, BASIC
continues executing the linc as if all information were on the same line.
Consider the following example:
60 FRINT “ARC yy 2 &
rdy 3K22 +9
You can continue any statement including an IMAGE statement (see Section 4.5). However, you cannot continue a
comment field (see Section 1.4).
1.4 DOCUMENTING PROCEDURES — THE REM STATEMENT AND THE COMMENT
BASIC allows you to document your methods, insert notes and comments, or leave yourself messages in the source
program. This type of documentation is known as a remark or comment. There arc two ways of inserting com-
ments within a BASIC source program:
|. With the REM statement
2. With the comment field (!)
The REM statement has the following format:
REM comment
where:
comment is anything you want to write.
You may place a REM statement anywhere in your program because it does not affect program execution.
MEN
Programming in BASIC
The REM statement can be the only statement on the line
10 REM THIS IS AN EXAMPLE
or it can be one of several statements in a multi-statement line.
BASIC ignores anything in a line following the keyword REM including a backslash (\). The only character that ends
a REM statement is a line terminator. Therefore, a REM statement should be the only statement on the line or the
last staternent in a multi-statement line.
20 LET A=5XREM THE VALUE OF à 15 5
You can use the line number of a REM statement in a reference from another statement, i.c., GOTO; however, in
this case, BASIC ignores the REM statement and proceeds to execute the next non-REM statement following the
linc referenced. For example:
L. E NH
00010 REM SON FUNCTION EXAMPLE
00020 REAL AyRC
90030 FRINT "SENA" SENCA) SENCRII" SONCE) » "SENCC)I= "yt
00040 GOTO 10
00050 DATA -7 A 9.2770
00050 ENT
GN CC)
`
>
Line 40 sends BASIC back to line 10. (See Section 5.1.1 for the GOTO statement.) BASIC ignores the comment on
line 10 and continues execution at line 20.
Remember that BASIC prints the remakrs on the terminal only when you list the source program. (See the User's
Guide for the LIST Command.)
The second method for adding comments to a program is to use the comment field. You mark the beginning of the
comment with an exclamation point (!). For example:
10 A = E+C !THIS IS À TEST.
The comment has no effect on the execution of the statement. You can end the comment with either an exclama-
tion point (1) or a line terminator.
You can place a comment between statements on a multi-statement line if you terminate the comment with an
exclamation point. A backslash does not terminate a comment field because BASIC interprets it as part of the
comment.
Note that the DATA statement and the IMAGE statement (Sections 3.1.3 and 4.5 respectively) cannot have com-
ment fields. Each must be the only statement on its respective line.
Also, you cannot continue a comment field to another linc. You can, however, continue the statement preceding
the comment. For example:
10 IF A=E HIS IS A COMMENT 38
THEN В
F НТ
НЕ ‘RINT
BASIC does not generate any code for the comment but does continue the statement.
CHAPTER 2
ELEMENTS OF BASIC-PLUS-2
2.1 TERMINOLOGY
In order to write programs in BASIC, you must be familiar with the terms and phrases used to describe the program
clements. You will probably recognize most of these terms from previous experience; however, the following
sections define these terms within the context of BASIC-PLUS-2.
2.2 CONSTANTS
There are three types of constants in BASIC:
|. Numeric (real numbers, also called floating point numbers)
2. Integer (whole numbers)
3. String (alphanumeric and/or special characters)
2.2.1 Numeric Constants
A numeric constant fs one or more decimal digits, cither positive or negative, in which the decimal point is optional.
The following are all valid numeric constants (real numbers):
5 42861
74 -125
6. 95
BASIC accepts numeric constants within a certain range. Refer to your User's Guide for this information.
If you type a numeric constant into the source text that is outside the range of numeric values representable by the
hardware, BASIC prints a fatal error message to that effect. Your program will not execute until you replace the
numeric constant with one in the proper range.
However, you can input very large numbers and very small numbers (within this range) by using a method similar to
scientific notation. Use the following format:
+or- x.xxxxxE + or-n
5.24016E-3
where:
+ or- is the sign of the number. The plus sign (+) is optional with positive numbers; the minus sign ( ) is
mandatory with negative numbers.
is the number carried to six decimal places.
E represents the words “times 10 to the power ot”
п is the exponential value (the power of 10).
This method of mathematical shorthand is called E notation or floating point notation. It is BASIC's way of repre-
senting scientific notation. To use this format, append the letter E to the number. Then follow the E with an
optionally signed constant (sec Section 2.2.2). The constant is the exponent. It can be O but never blank.
2-1
Elements of BASIC-PLUS-2
Thus you can type:
6000000 as 6EG and .000005 as 51: 6
With E notation you are actually positioning the decimal point internally. A positive exponent moves the decimal
point to the right: a negative exponent moves the decimal point to the left. For instance, if you type the number
5.2041E-3
BASIC interprets it as 0052041.
Table 2-1 shows the different methods of writing numeric constants.
Table 2-1 Number Notations
Standard Notation Scientific Notation E Notation
1000000 1 X 1076 1 .00000Е+06
10000000 1 X 1077 1.00000E+07
100000000 1 X 1078 1.00000E+08
1000000000000 1X 10712 1.00000E+12
BASIC uses single precision floating point format when storing and calculating most numbers. Integers, however, are
handled in a slightly different manner. (Sec Section 2.2.2.
The tollowing are examples of numeric constants:
.84103E-06 - 377 - 12345
6.04 SE+03 8.0E-03
9.4177 6562 25
2.2.2 Integer Constants
An integer constant is a whole number (no fractional part) written without a decimal point. Type an integer
constant as one or more decimal digits terminated by a percent sign (%). For example, the following numbers are all
integer constants (whole numbers):
29% -8%
3432% 1%
12345% 205%
The following are not integer constants:
1.6 08%
754.2% 5.2041E+06
In BASIC. you can type integer constants within the range specified by your system. Sec the User's Guide for this
information. If you specify a number outside the range, BASIC prints a fatal error message telling you to replace
the number with one within the proper limits.
2.2.3 String Constants
A string constant (also called a literal) is onc or more alphanumeric and/or special characters enclosed by double
quotation marks (“text”) or single quotation marks (‘text’). You can include double quotation marks within a
9
во
Llements of BASIC-PLUS-2
string constant delimited by single quotation marks and vice versa. Include both the starting and ending delimiters
when typing a string constant in a source program. Thesc delimiters must be of the same type (both double
quotation marks or both single quotation marks).
Each character in a string constant can be a letter, a number, a space, or any ASCII character except a line termi-
nator. The value of the string constant is determined by all its characters. For example, because of the number of
spaces between the quotation marks and the characters:
“ DIGITAL is not the same as “DIGITAL”
BASIC prints every character between quotation marks exactly as you type it into the source program, including:
1. Lower-casc letters (a-z)
2. leading, trailing, and embedded spaces
3. Tabs
Note, however, that BASIC does not print the delimiting quotation marks when the program is executed.
00010 FRINT "DIGITAL"
00020 END
READY
RUNNH
OIGITAL
In order to make BASIC print quotation marks, you must enclose them within another pair of quotation marks,
either double or single.
Q0010 FRINT “HE SAILy "“GOOD MORNING! *
00020 ENT
RUNNH
HE SAIL» *“GOOnN MORNING!"
Here are some examples of string constants:
“This Is a String Constant.”
‘SO IS THIS.
“TONY'S TENNIS RACKET”
The following are examples of invalid string constants:
“WRONG TERMINATOR’
“SAME HERE”
“NO TERMINATOR
2.3 VARIABLES
Depending on the operations you specify in a program, the value of a variable may change from line to line. BASIC
uses the most recently assigned value of a variable when performing calculations. This value remains the same until
a statement is encountered that assigns a new value to that variable.
2-3
Illements of BASIC-PLUS-2
BASIC accepts threc types of variables:
[. Numeric
2. Integer
3. String
All statement keywords are reserved (see Appendix C) and, therefore, cannot be used as variable names. The follow-
ing sections describe the formation of legal variable names.
2.3.1 Numeric Variables
A numeric variable is a named location in which a single numeric value is stored. You name a numeric variable with
a single letter followed by 29 optional characters consisting of letters, digits, or periods. Therefore, the maximum
length of a numeric variable name is 30 characters:
| letter
29 optional characters
Do not embed spaces between characters. The following are numeric variables:
C L...5
Mi BIG47
F67T.J 72.
The following are not legal numeric variables:
6 225
A G*T ух
4D 8/3
Before program execution, BASIC sets all numeric variables to O except for thosc in virtual array, MAP, or
COMMON declarations (Sections 9.3. 10.14, and 11.2.1 respectively). If you require an initial value other than 0,
you can assign it with the LET statement (Section 2.5). Otherwise, you can declare the value implicitly by just
typing the variable in a program.
NOTE
Because other BASIC implementations may not set all PQ
variables to O before program exccution, you should not ВЕ
rely on this feature. Good programming practice dictates
that you initialize all variables at the beginning of the
program.
2.3.2 Integer Variables
An integer variable (like a numeric variable) is a named location in which a single value can be stored. Using an
integer variable in your program indicates that space is reserved for the storage of a whole number (no fractional
part).
You name an integer variable with a single letter followed by 29 optional characters consisting of letters, digits, or
periods and terminate the name with a percent sign (%). Therefore, the maximum length of an integer variable name
is 31 characters:
| letter
29 optional characters
| percent sign (%) ить
Ч J TTT EA: Be] ©
i
Elements of BASIC-PLUS-2
(No embedded spaces are allowed.) The following are integer variables:
ABCDEFG% C.8%
B% D6L7%
The tollowing are not integer variables:
A B2$
1B% 123%
If you include an integer variable in a program, then the value you supply for it must be an integer constant. Ша
numeric constant (real number) is assigned to an integer variable, BASIC drops the fractional portion of the valuc.
The number is not rounded to the nearest integer: it is truncated. Consider the following example:
В% = - 5.7
BASIC assigns the value -5 to the integer variable, not -6. This method of truncating can lead to serious inaccuracies.
If you assign an integer constant to a numeric variable, BASIC prints the integer value as an integer but stores the
real number internally.
2.3.3 String Variables
A string variable is a named location used to store alphanumeric strings. You name a string variable with a letter,
followed by 29 optional characters consisting of letters, digits, or periods, and terminate the name with a dollar
sign ($). (No embedded spaces are allowed between characters.) The dollar sign ($) must be the last character in the
name. Therefore, the maximum length of a string variable name 1s 31 characters:
| letter
29 optional characters
1 dollar sign ($)
The following are examples of string variables:
С1$ M$
L.6$ F34G$
АВС1$ Т..$
These are not string variables:
Cl 12345$
6.L$ $8
$56A AB
Strings have a value and a length. BASIC initializes all string variables (unless in a virtual array, MAP, or COMMON
area) to a length of 9 (null string) before the start of cach program execution. During execution, the length of a
character string associated with a string variable can vary from O (signifying a null or empty string) to a limit set by
your system. See the User’s Guide for this information. String variables can also be declared implicitly just by
appearing in a program.
Note that a simple numeric variable, an integer variable, and a string variable that begin with the same alphanumeric
characters represent three distinct variable names.
>
сл
Elements of BASIC-PLUS-2
The following names are all legal within a single BASIC program:
AS a simple numeric variable
AS% an integer variable
ASS a string variable
2.3.4 Subscripted Variables
A subscripted variable is a numeric, integer, or string variable with one or two subscripts appended to it. The
subscripts can be any positive expression type: a constant or a variable (integer or numeric), a letter or symbol,
or any combination of these. BASIC converts non-integer expressions to integer by truncating the fraction. The
value of the subscript can be O to a maximum defined by your system. Refer to the User's Guide for this
parameter.
The subscript in a subscripted variable is a pointer to a specific location in a list or table in which a value is stored.
(See Section 2.6 for more information on lists and tables.) You designate the pointer with cither one or two
subscripts enclosed by parentheses. If there are two subscripts, separate them with a comma. The value stored can
be numeric, integer, or string data.
To name a subscripted variable, start with a numeric, integer, or string variable name:
A А% AS
To refer to an clement in a list (one dimension), follow the variable name with one subscript within parentheses. For
example:
A(6) A%(6) А$(6)
A(6) refers to the seventh item in this list:
AO) A(1) AC?) AG) A4) AGS) AG)
10 20 30 40 50 60 70
To refer to an element in a table (two dimensions) follow the variable name with two subscripts. The first subscript
designates the row number, and the second subscript designates the column number. Separate the two subscripts
with a comma. For example:
A(7.2 А%(4.6) А$(17,23)
BASIC accepts the same alphanumeric characters for a simple numeric variable and a subscripted variable within the
same program. However, do not use the same alphanumeric characters for two arrays (Section 2.6) with a different
number of subscripts.
This is acceptable in the same program.
D simple numeric variable
D(8) subscripted variable
This is not acceptable in the same program:
D(8) one subscript
D(8.6) two subscripts
Elements of BASIC-PLUS-2
2.4 FORMING EXPRESSIONS
An expression can be numbers, strings, constants, variables, functions (Section 2.4.6), array references (Section 2.6),
or any combination of these, separated by any of the following:
Arithmetic operators
Relational operators
String operators
Logical operators
SUN —
2.4.1 Arithmetic Expressions
BASIC allows you to perform addition, subtraction, multiplication, division, and exponentiation with the following
operators:
** or “ Exponentiation
* Multiplication
/ Division
+ Addition, Unary +
- Subtraction, Unary -
Performing an arithmetic operation on two arithmetic expressions of the same data type yields a result of that same
type. For example:
A%+B% = an integer expression
G3*M5 = a numeric expression
AS+D$ a string expression
If you combine an integer quantity with a numeric quantity, the result will be numeric. For example:
A*B% = a numeric expression
6.83 + 5% = 34.15
Note that in general, you cannot place two arithmetic operators consecutively in the same expression. The
exceptions are the unary plus and unary minus. For example:
A* Bisvalid and A*( B) is valid.
Table 2-2 provides examples of arithmetic operators and their meaning.
Table 2-2 Arithmetic Operators
Operator Example Meaning
+ A+B Add Bto A
- A-B Subtract B from A
* A*B Multiply A by B
/ A/B Divide A by B
^ AB Calculate A to the power B
kx A**B Calculate A to the power B
Elements of BASIC-PLUS-2
2.4.2 String Expressions
BASIC provides the plus sign (+) (and the ampersand (&)) as an operator for string expressions. By using this „т
operator you can link one string to the end of another. This operation is called concatenation.
Consider the following example:
00010 СФ = "6000" + "BYE"
00020 FRINT C$
00030 ENT
During execution, BASIC prints the following:
GOOLEYE
AS + BS or AS £ BS mean concatenate or link string BS to the end of string AS.
2.4.3 Relational Expressions
A relational operator is a symbol used to compare the value of one variable or expression to another variable or «ть
expression within a BASIC program, thus creating a relational expression. As explained in Section 5.1.3, onc of the
uses of relational expressions is with the IF-THEN-ELSE statement to create conditional transfers.
It a relational operator is used on the right side ot an assignment, its value is - 1 if the relation is true, and O of the
relation is false.
NOTE
It is illegal to compare a numeric or integer expression to
a string expression using a relational operator. me.
Table 2-3 provides examples of relational operators and their meaning.
Table 2-3 Relational Operators
Operator Example Meaning
= A=B Á is equal to B
< A<B Á is less than B ;
> A>B A is greater than B
<=, = A<=B A is less than or equal to B
=, = А>= В À is greater than or equal to B
#, <>, >< A<>B À is not equal to B
== A==B À is approximately equal to B if the difference
between A and B is less than 107(-6).
2.4.4 Comparing Strings Using Relational Operators
When you usc a relational operator to compare the value of one or more alphanumeric characters, you create a
relational string expression. BASIC uses the ASCII character collating sequence to determine which character
is greater or lesser in value than the other. (See Appendix B for the ASCII Table.) The comparison is made, A,
character by character. left to right. by ASCII value until BASIC finds a difference in value.
Elements of BASIC-PLUS-2
When applied to strings, relational operators compare characters for alphabetic sequence. Consider the following
program:
00010 As = "AEC"
00020 R$ = "DEF"
00030 IF A#$<F$ GOTO 60
00040 FRINT A%
00050 FRINT ES
00060 ENT
When BASIC executes line 30, it compares string AS with B$ to determine if AS occurs first in alphabetic sequence.
In this case, it does, and the program transfers control to line 60 (sce Section 5.1 for transferring control of a
program). If string B$ occurred before string AS, program execution would continue to the next statement follow-
ing the comparison, i.c., line 40.
BASIC compares strings just as you compare words to be placed in alphabetical order. BASIC compares the first
character in each string, A and D. The letter A precedes the letter D in the ASCII table; therefore, string AS
precedes string BS in alphabetic sequence. If the first two characters are equal, BASIC proceeds to the second two
characters, until a difference is found. For example:
ABC
AEF
BASIC compares A to A and finds them equal in value. Then BASIC compares B and E and finds B less than E. The
comparison ends herc, and BASIC concludes that ABC occurs before AEF in alphabetic sequence.
Table 2-4 provides examples of string operators and their meaning.
Table 2-4 String Relational Operators
Operator Example Meaning
= AS = B$ Strings AS and BS are cqual after removing trailing blanks and
nulls.
< А$ < В$ String A$ occurs before string BS in alphabetic sequence.
> AS>BS | String AS occurs after string BS in alphabotie segeunce.
<=,=< AS<=BS String AS is equal to, or precedes, string BS in alphabetic sequence. a
>= => AS>=BS String AS is equal to, or follows, string BS in alphabetic sequence. a
#,<>>< AS<>BS$ String AS is not equal to string BS. a
== A$==BS Strings AS and B$ are identical (exactly the same length without a
padding and composition of all characters).
Note that the relational operator == has a different meaning when applied to strings than when applied to numbers.
When comparing strings of different lengths, BASIC treats the shorter string as if it were padded with trailing blanks
to the length of the longer string. In order to perform character-to-character comparison, BASIC needs two charac-
ters to compare, This is where the trailing blanks serve their purpose.
Elements of BASIC-PLUS-2
Consider the following example:
00010 A$ = "ANTONY"
00020 E$ = "CLEOFATRA"
00030 IF ASES GOTO 50
00040 AF: AS + ES
00050 FRINT AS
00060 ENT
BASIC compares the A in ANTONY and the C in CLEOPATRA. The ASCII value of Ais 65; the ASCII value of C
is 67. Therefore string A$ precedes string BS in alphabetic sequence. Control shifts to line 50. If A$ were greater
than BS, the program would continue to line 40. This is what happens when BASIC executes the program:
RUNNH
ANTONY
2.4.5 Logical Expressions
A logical expression consists of either onc operand preceded by a logical operator or two operands separated by a
logical operator. Logical expressions are used in statements like the IF-THEN-ELSE statement (Section 4.1.3) where
a condition is tested to determine subsequent operations within the program. The operands, in this case, are usually
relational expressions. Logical expressions can also be used with integer data. However, logical operations on strings
arc illegal.
BASIC determined whether the condition is true or false by testing the bit-wise result of the logical expression for
non-zero and zero, respectively. (That is, a non-zero result is true, and a zero result is false.) Notice that any non-
zero value is assumed to be true. BASIC supplies the value — 1 for true when it evaluates a logical or relational
expression but accepts any non-zero value when performing a test. Therefore:
A% = 10%
B% = NOT A%
Both A% and B% are true, c.g., A% = 10 and B% = ~ 11. Logical operators are reserved words. See Appendix C.
Table 2-5 provides a list of logical operators and their meaning.
Table 2-5 Logical Operators
Operator Example Meaning
NOT NOT A% The logical opposite of A%. If A% is false, NOT A% is true.
AND A% AND B% The logical product of A% and B%. A% and B% is true only if
both A% and B% are true.
OR A% OR B% The logical sum of A% and B%. A% or B% is false only if both
A% and B% are false: otherwise A% OR B% is true.
XOR A% XOR B% The logical exclusive OR of A% and B%. A% XOR B% is truc
if either A% or B% is true but not both; and false otherwise.
EQV A% EQV B% A% is logically equivalent to B%. A% EQV B% has the value
true if A% and B% are both true or both false; and has the
value false otherwise.
IMP A% IMP B% The logical implication of A% and B%. A% IMP B% is false if,
and only if, A% is true and B% is falsc; otherwise the value is
true.
Elements of BASIC-PLUS-2
Logical expressions are legal wherever numeric expressions are legal in BASIC. However, both operands must be
integers.
The following tables are called truth tables. They describe graphically the results of the above logical operations on
a bit-by-bit basis. Every possible combination of bits for A% and B% is given.
Table 2-6 Truth Tables
A% NOT A% A% B% A% OR B%
0 1 0 0 0
] 0 0 1
1 0 1
1 1 ]
A% B% A% AND B% A% B% A% EQV B%
0 0 0 0 0 1
0 1 0 0 1 0
1 0 0 1 0 0
1 1 1 1 1 ]
A% B% A% XOR B% A% B% A% IMP B%
0 0 0 0 0 ]
0 | ] 0 ]
1 0 1 ] 0 0
] 1 0 ] 1 ]
Notice that the two operators XOR and EQV are exact opposites.
2.46 Functions
Library functions are an integral part of the BASIC language. À function can be accessed in a program by stating its
name. À sequence of instructions is then performed automatically.
A function name is used just like a variable name. When you type a function into a program, you are actually calling
a pre-written routine. Consider the following example:
00010 FRINT SQAR(49)
00020 END
READY
RUNNH
7
SQR is the function that defines the square root of the number within parentheses, in this case 49.
Functions are fully described in Chapter 7. For a complete list of library functions, refer to Appendix A.
2.4.7 Evaluating Ex pressions
BASIC evaluates expressions according to operator precedence. Each arithmetic, relational, and string operator
joining an expression has a predetermined position in the hicrarchy of operators. The operator's position tells
BASIC when to evaluate the operator in relation to the other operators in the same expression. Parentheses may be
used to alter the order of precedence.
Elements of BASIC-PLUS-2
In the case of nested parentheses (one set of parentheses within another), BASIC evaluates the innermost expression
first. then the one immediately outside it. and so on. The evaluation proceeds from the inside out until all
parenthetical expressions have been evaluated. For example:
B = (25+(16*(9°2)))
Because (9°2) is the innermost parenthetical expression, BASIC evaluates it first, then (16*81), and then (25+1296).
Table 2-7 lists all operators in the order BASIC evaluates them:
Table 2-7 Operator Precedence
wx HIGHEST
- (unary minus) A
+,-
+ (concatenation)
all relational operators
NOT
AND
OR, XOR
IMP Y
EQV LOWEST
Operators shown on the same line have equal precedence. Except for the operators + and *, BASIC evaluates
operators of the same precedence level from left to right. The operators + and * are evaluated in any order that is
algebraically correct. Note that BASIC evaluates ABC as (AB) C on all processors.
All relational operators are on the same precedence level.
BASIC evaluates expressions enclosed in parentheses first, even when the operator enclosed in parentheses is on a
lower precedence level than the operator outside the parentheses. Consider the following example:
A = 1572+1272-(35*8)
BASIC evaluates this expression in five ordered steps:
1. 152 =225 Exponentiation (left-most expression)
2. 122 =144 Exponentiation
3. 35*8=280 Multiplication
4. 225+144= 369 Addition
5. 369-280= 89 Subtraction
2.5 ASSIGNING VALUES TO VARIABLES - THE LET STATEMENT
The LET statement enables you to assign a value to a variable. The LET statement has the following format:
LET variable(s) = expression
or
variable(s) = expression
tJ
tJ
Elements of BASIC-PLUS-2
where:
expression can be a string, numeric, or logical expression. (The keyword LET is optional.)
The LET statement replaces the variable on the left of the equal sign (=) with the value on the right. Hence. the
equal sign (=) signifies the assignment of a valuc and not algebraic equality. BASIC evaluates the expression from
left to right and assigns the values from right to left. Here is an example:
10 LET A = 482.5
This statement assigns the value 482.5 to the variable A. You can also write the statement this way:
10 A = 482.5
BASIC also evaluates any formula you assign:
10 A = (X+Y)-84
BASIC calculates the expression (X+Y)-84 and then assigns the resulting value to the variable A.
In addition, you can assign a value to more than one variable at a time, as in the following example:
10 А, ВС = 64X82
This statement has the same effect as:
10 С = $4X82
20 В = 64%82
30 A = 64x82
BASIC also converts the data type of the value to the data type of the associated variable, i.e., integer or real. In the
following example,
10 Ау, Со) = 9.5
is the same as
10 U = 95
20 CZ = 9
30 В = 9,0
40 A4 = Y
BASIC assigns the values from right to left. Refer to Section 2.3 for a description of variables.
Moreover, if you reference an array element as a variable (see Section 2.6) BASIC calculates the value of the
subscript before assigning values to the other variables in the list. For example, the following assigns the value 5 to
the list element A(2). Then the value of I changes to 5:
10 I = 22
2 ACT)» I =5
You can also assign a string expression to a variable as well as a numeric expression. However, you cannot mix
strings and numeric expressions in the same LET statement. If you do, BASIC prints an error message on the
terminal.
1-2
/
a
Elements of BASIC-PLUS-2
The following is an example of a string assignment:
10 A$= "HELLO"
20 FRINT A$
30 ENT
RUNNH
HELLO
Refer to Sections 2.2.3 and 2.3.3 for information on strings.
Note that you can place a LET statement anywherc in a multi-statement line:
10 DIM A(CZ)NT=42XFRINT I
2.6 ARRAYS
Basic automatically reserves storage space for arrays with maximum subscripts of 10, i.e., A(10) and A(10,10). If
you require a larger amount of reserved space, define the dimensions with the DIM statement (see Section 2.6.1).
Conversely, if you do not require the space BASIC supplics by default, save the space for your program by reserving
a smaller arca with the DIM statement.
When you establish the size of the array, BASIC stores the dimensions in a particular area for future reference.
BASIC starts counting elements from 0, not 1; therefore, you have an additional element for a list and an additional
row and column for a table.
For example, dimensioning the array A(6) gives you seven storage areas in the list, not six:
ROW 1 A(O)
2 A(1)
3 AQ)
4 A(3)
5 A(4)
6 A(S)
7 A(6)
Array B(3,3) contains storage space for 16 elements. This is the layout of array B(3,3): E
COLUMN ] 2 3 4
ROW | B(0,0) B(0,1) B(0,2) B(0,3)
2 B(1,0) B(1,1) B(1,2) B(1,3)
3 B(2,0) B(2,1) B(2,2) B(2,3)
4 B(3,0) B(3,1) B(3,2) B(3,3)
Figure 2-1 Array B
Note that if you reference an array with the wrong number of subscripts, BASIC prints an error message.
Remember that it is possible to use the same alphanumerics to name both a simple variable and an array within the
same program. But using the same name for two arrays with a different number of subscripts is illegal within the |
same program, i.e., A(5) and A(3 4).
2-14
Elements of BASIC-PLUS-2
2.0.1 The DIM Starement
The DIM statement allows you to define the dimensions of an array in your program. By using the DIM statement
you reserve storage space to be filled with valucs of cither numeric or string data.
5
The DIM statement has the following format :
DIM subscripted variable(s)
or
DIMENSION subscripted variable(s)
where:
subscripted variable(s) is one or more numeric, integer, or string variables separated with commas (see
Section 2.3.4). Subscripts must be numeric or integer constants.
Each subscripted variable name represents a distinct list or table. The subscripts must be constants and can range
from O to the system defined maximum. Because BASIC automatically reserves storage for arrays with maximum
subscripts of 10, i.e., A(10) and B(10,10), use the DIM statement to reserve storage for lists with more than 11
elements and matrices with more than 121 elements.
In the DIM list, you are specifying:
The name of the array
The number of subscripts (one or two)
The maximum value of each subscript
‘О о
Here is an example of a DIM statement :
10 DIM AC25)E6355)>CZ (7516) 08 (15)
No array can have more than two subscripts. If you do not specify a subscript in the second position, only one
subscript is permitted for that variable name in future references. When using the DIM statement to set the
maximum values for the subscripts, you are not obligated to fill every storage space you allocate.
Arrays are stored as if the rightmost subscript varied the fastest. For example:
10 DIM ACLS)
provides 12 contiguous areas of storage.
Because the DIM statement is not executed, you may place it anywhere in the program. It can also be one of
several statements in a multi-statement line.
The tollowing example sets up storage for a matrix with 20 elements:
10 LIM AC34)
The storage addresses look like this:
00 01 02 03 04
1,0 1,1 12 13 14
20 2,1 22 23 24
30 3,1 32 33 34
Llements of BASIC-PLUS-2
Notice that reading across left to right, the second subscript increases first.
As stated previously, the first element of every array begins with a subscript of 0. If you dimension a matrix
C(6,10), you set up storage for 7 rows and 11 columns. The 0 element is illustrated in the following program:
00010 REM MATRIX CHECK PROGRAM
00020 LIIM CC6y10)
90030 FOR I = О ТО ©
00040 LET CCI,09 = 1
00050 FOR J > O TO 19
00060 LET C(OyJ) = J
00070 FRINT CCTy2J)3
00080 NEXT J\FRINTNEXT 1
90090 ENT
REALY
RUNNH
O 1 2 3 4 5 E 7 8 7 190
1 90 0 0 0 0 0 0 0 О 9
2 0 0 0 0 60 0 0 O Y Y
3 0 0 0 0 0 0 0 0 0 Y
4 0 0 0 0 0 0 0 D. 6 Y
HE 0 0 0 0 à O O O 0 Y
6 0 0 0 0 0 0 0 O O 9
Notice that a numeric or integer variable has a value of 0 until you assign it another value. (A string variable is
considered a null string.)
You can also dimension string arrays with the DIM statement:
00010 DIM A$ C5)
00020 INFUT ASCII SAS C2 I ARC ARC 4) ABC
00030 MAT EFRINT “ABC
00040 ENT
READY
RUNNH
? HyEvyLrL 0)
CHAPTER 3
INPUT AND OUTPUT TO THE TERMINAL
3.1 SUPPLYING DATA
BASIC has three methods of supplying data to a program:
1. The INPUT statement -- requires that you interact with the computer while the program is running.
2. The READ, DATA, and RESTORE: statements — require that you build a data block within the source
program.
3. The file statements -- require that you manipulate files outside the main program. Sec Chapter 9 for
information on file input and output.
3.1.1 The INPUT Statement
The INPUT statement allows you to enter and process data while the program is running.
The INPUT statement has the following format:
INPUT variable(s)
where:
variable(s) is one or a list of numeric, integer, string, or subscripted variables or any combination of these
separated by commas.
Consider the INPUT statement as another means of assigning values to variables. When you run your program,
BASIC stops at the line designated by the INPUT statement and prints a space. a question mark (7). and a space.
BASIC then waits for you to type one value for each variable requested in the INPUT statement. When there is
more than one variable requiring a value, separate each value with a comma. Press a line terminator after you finish
typing all the values.
The following example requires that you type three values after the question mark (?).
00010 INFUT AsyEsC
00020 ENT
REALY
RUNNH
? 6977
The INPUT statement tells BASIC to accept the forthcoming data from the user terminal. BASIC accepts the values
left to right. After you type all the necessary data, type a line terminator. The program continues using the values
you supply. Therefore, in the previous example
A=5
B=6
C=7
3-1
Input and Output to the Terminal
You must supply the same number of values as there are variables in the INPUT request. If you do not type enough
data. BASIC lets you know by printing the message “INSUFFICIENT DATA AT LINE nn” and another question
mark (?) when you press the RETURN key.
O0010 INFUT AyE
00020 ENT
REALY
KUNNE
? E
THY Insufficient data st line 00010 of MAIN PROGRAM
P 6
READY
On the other hand, if you supply more values than there are variables to be defined, BASIC ignores the excess and
prints a warning message to that effect.
00010 INFUT Ak:
00020 FRINT А, Ву С
00030 END
READY
RUNNH
TT y ;6y/7 5
? 436 Too much dela eresent - isnored alt line 00010 of MAIN PROGRAM
J ó 7
READY
The extra value entered (8) is ignored.
The values you supply must be the same data type as the variables in the INPUT statement, ie, strings for string
variables, integers for integer variables. You can type strings with or without quotation marks in answer to the
question mark. If you include quotation marks, be sure to type both beginning and ending delimiters. If you
forget the end quotation mark, BASIC reads the rest of the line as the entire string, You will also receive an error
message.
Including a string constant in an INPUT statement allows you to see the results of your computations. You must
separate the string constant from the variable list with a comma or semicolon. For example:
00020 INFUT "FLEASE ТУРЕ 3 INTEGERS'" $ Ey Cy [1%
00030 AZ = RX + Cx + NX
00040 FRINT AX
00050 ENT
READY
FUNNH
FLEASE TYPE 3 INTEGERS ? «5,5075
150
READY
AE
EL
Input and Output to the Terminal
NOTE
The INPUT # statement (see Section 9.3.1) is used to input
values from a file. Logical unit O is the user terminal.
10 INFUT #0y XyYs2
is equivalent to
10 INFUT X» Yr£
The INPUT statement with a string constant but without a variable list has the same effect as the PRINT statement,
Section 3.2. For example:
10 INFUT "BASIC-FLUS-—2"
RUNNH
BASTC-FLUS-
READY
3.1.2 The INPUT LINE and LINPUT Statements
The INPUT LINE statement and the LINPUT statement have essentially the same function as the INPUT statement.
However, INPUT LINL and LINPUT are used exclusively for string data. Use the following format:
INPUT LINE string variable(s)
LINPUT string variable(s)
where:
A space is required between the keywords INPUT and LINE.
LINPUT is one word.
All variables must be string variables in INPUT LINE and LINPUT statements.
The INPUT LINE statement accepts and stores all characters including quotation marks and commas, up to and
including the first line terminator. LINPUT accepts all characters up to the line terminator, but does not include
the line terminator. For example:
00010 LINFUT ES
00020 FRINT E$
00030 END
READY
RUNNH
? "NOW: LOOK HERE!" ЗАТО JOHN
"NOWy LOOK HERET*" »SAIT JOHN
REALY
[f you try to type the string shown above, in response to an INPUT statement, you will receive a warning message.
The INPUT would take the comma after the word “HERE!”, as the delimiter of the string.
Both INPUT LINE and LINPUT can reference a terminal or a terminal-format file. See Chapter 9 for more
information.
3-3
Input and Output to the Terminal
3.1.3 READ, DATA, and RESTORE (RESET) Statements
Another way you can supply data to a program is to build a data block tor BASIC to read during execution. This
means that you do not interact with BASIC while the program is running. Instead, you supply a pool of data to the
program in advance. Two statement keywords are involved in this process: READ and DATA.
The READ statement has the following format:
READ variable(s)
where:
variables(s) is one or a list of variables consisting of numeric, string, subscripted variables, or a combination
of these. All variables should be separated by commas. For example:
10 READ Ay EX CBHyTI(5)yE
The READ statement directs BASIC to read from a list of values built into a data block by a DATA statement.
The DATA statement has the following format:
DATA constant(s)
where:
constant(s) is one or more numeric, integer, or string constants (quoted or unquoted) listed in the same
order of data type as the variable requested in the READ statement. All constants are
separated by commas. _—
The program runs faster with READ and DATA statements than with the INPUT statements because you do not
have to wait the extra time it takes for BASIC to stop and request data. The data is already within the program.
A READ statement causes the variables listed in it to be given the next available constants, in sequential order, from
the collection of DATA statements. BASIC has a data pointer to keep track of the data being read by the READ
statement. Lach time the READ statement requests data, BASIC retrieves the next available constant indicated by
the data pointer.
A READ statement is not legal without at least one DATA statement. However, you can have more than onc DATA
statement. Without a READ statement, BASIC ignores the DATA.
Q0010 READ AsRByCyDvE SF
00020 FRINT C
00030 DATA 1727.30
00040 DATA 439 7690 27
A RLAD statement can be placed anywherc in a multi-statement line. A DATA statement, however, must be the
last or only statement on a line. Each list of constants in a DATA statement is local to a program or subprogram
(see Section 11.1) and must be referenced by line number, not by order of appearance in a program.
If you build your READ statement with more variables than you include in the data block, you receive a warning
message from BASIC,
A».
Input and Output to the Terminal
You will receive error messages if:
1. You have a READ statement without a DATA statement.
2. You assign a string constant to a numeric variable.
3. You place more variables in the READ statement than you supply data to define them.
You can READ a numeric constant into a string variable. For example:
00010 READ AY
00020 FRINT AS
00030 DATA 8.205
00040 ENT
READY
RUNNH
8.20
REALY
The following is an example of a READ and DATA sequence.
00010 КЕАП А, В; СТ, ПО, А, ТВ, 221
00020 DNATA >. 3v-4.2554y3--;Svy129"CAT" > DOG» “MOUSE?
00030 FRINT ArEsC1ryL223:E47Y6b,7Z$,71%
BASIC assigns values as follows:
Z$=DOG
Z1$=MOUSE
RUNNH
2.3 -4.,2654 3-6 12 CAT DOG MOUSE
READY
In some programs you may need to read the same data more than once. BASIC provides the RESTORE statement
for this purpose.
The format of the RESTORE statement is:
RESTORE
The RESTORE statement resets the data pointer to the beginning of the first DATA statement in the program.
(The keyword RESET performs the same function.) The values are read as though for the first time; therefore. the
same variable names may be used the second time through the data.
Input and Output to the Terminal
Consider this example:
00010 READ В, С,
00015 FRINT В; Су
00020 RESTORE
00030 READ LyF 50
00035 FRINT Eyl 0
00040 DATA 6573904570572
00050 END
The READ statement in line 10 reads the first three values in the DATA statement, line 40:
=
fl
6
*“
J
rm
|
3
4
pr
Then the RESTORE statement on line 20 resets the pointer to the beginning of line 40, so that the second READ
statement on line 30 also reads the first three values. BASIC reads these values as though for the first time:
[If the RESTORE statement were not there, READ on line 30 would read the last three values:
Е=7
F=9
3=2
The RESTORE statement affects only the program or subprogram (see Chapter 11) in which it is contained. Also,
if vou have no DATA statements in your program, RESTORE has no effect.
NOTE
The RESTORE # statement (Chapter 9) is used to restore
files to their beginning.
3.2 CHECKING OUTPUT -- THE PRINT STATEMENT
Another useful statement to include in your program is the PRINT statement. The PRINT statement has the
tollowing format:
PRINT [[expression(s) [}
where:
expression(s) can be one or more numeric or string elements separated with commas or semicolons.
(Sce Section 3.2.1.)
The PRINT statement prints a list of elements on the terminal when you execute your program. In this way, you
can see the results of your computations or add comments to clarify your requests for input. (The PRINT statement
can be placed anywhere in a multi-statement line.)
You can include blank lines in your output for readability. Using the PRINT statement without arguments causes a
blank line to appear in the output:
3-6
Input and Output to the Terminal
00010 FRINT "THIS EXAMPLE LEAVES à BLANK LINE"
00020 FRINT
00030 FRINT "BETWEEN TWO LINES."
90040 ENT
READY
RUNNH
THIS EXAMPLE LEAVES A BLANK LINE
BETWEEN TWO LINES.
READY
When an clement in the list is an expression rather than a simple variable or constant, BASIC evaluates the expres-
sion before printing the value. Therefore, the PRINT statement performs two functions in one. calculates expres-
sions and prints the results. For example:
00010 À = 45\В = 55
00020 FRINT À + В
00030 END
READY
RUNNH
100
After running this program, BASIC prints 100 on your terminal, not 45+55. If you put quotes around the variables,
this is what happens:
00010 À = 45XE = 55
00020 FRINT "À + В"
Q0030 ENT
REALY
RUNNH
A + E
If you plan to have somcone else run your program, you can clarify your requests for input with a PRINT statement.
(Refer to Section 3.1.1 for more information on the INPUT statement.) Include literal strings (Section 2.2.3) as in
the following example:
00010 FRINT "WHAT ARE YOUR VALUES OF Xy Y,7"
QOORO INFUT X» Y Z
00030 LET R = SQRO”2 + YE + 272)
00040 FRINT “THE RALNIUS VECTOR EQUALS"
00045 PRINT R
00050 ENT
When you run this program, BASIC prints:
RUNNH
WHAT ARE YOUR VALUES ОР Ху)
? 29374050
THE RADIUS VECTOR EQUALS 68.73864
READY
3-7
Input and Output to the Terminal
Notice that you enclose the strings in quotation marks so that BASIC prints them exactly as you type them in. In
line 40 of the previous example, a semicolon separates the string from the variable name. Placing a semicolon or
a comma after the string makes BASIC print the value on the same line as the string. If the separator is not there, „=.
BASIC performs a carriage return/line feed and begins printing in the first column of the next line.
THE RADIUS VECTOR EQUALS
68.7386
3.2.1 Printing Zones -- The Comma and the Semicolon
A terminal line consists of an integral number of zones, each zone containing 14 spaces. When you use the PRINT
statement, you can control the placement of your output within these zones by using the legal separators, comma
(.) and semicolon (;).
The comma signals BASIC to start printing at the beginning of the next print zone. If the last print zone on the line
is filled, BASIC prints the output beginning at the first print zone on the next line. For example:
00005 INFUT AyByCyDskvF
00010 FRINT ArBryCryLryEyF -
00020 ENT
REALY
FUNNH
T 5s10;15, 20,25; 30
= 10 10 20 E
30
lt you place more than one comma between list elements, you will skip one print zone for cach extra comma. The
following example prints the value of A in the first zone and the value of B in the third zone: Fü
00010 A = 3B\R = 10
00015 FRINT "FIRST ZONE" » "THIRD ZONE"
00020 FRINT AyyE
00030 END
READY
RUNNH
FIRST ZONE THIRD ZONE
o 10 E.
To print an output line in a more compact format, use the semicolon (;) as the separator between variables. A
semicolon in a PRINT statement causes tight packing of the print line. Note that whenever BASIC prints a number
it is preceded by a space or a minus sign and followed by a space.
00010 FRINT 10720
00020 ENT
READY
RUNNH
10 20
MU
FEEL fa E
Input and Output to the Terminal
BASIC does not print a space before strings:
00010 FKINT 10520
00020 ENT
READY
RUNNH
10 20
Placing a comma or semicolon after the last item in a PRINT statement causes the terminal printer to remain at the
same print position in anticipation of another PRINT or INPUT statement.
In the following example, BASIC prints the current values of X.Y and Z on the same terminal line because a comma
appears as the last item in line 20:
00010 INFUT X»Y sl
00020 FRINT Ху Ху
00030 FKINT 2
00040 END
READY
RUNNH
T 5510515
J 10 1%
The following example illustrates the three options you have for placing either a comma, a semicolon. or a line
terminator after the last item of the PRINT statement:
00010 FOR I = 1 ТО 10
00020 FRINT I LA LINE TERMINATOR
00030 NEXT INFRENT
00040 FOR J = 1 TO 10
00050 FRINT J» lA COMMS
00060 NEXT JXFRINT
00070 FOR K = 1 TO 10
00080 FRINT Ki HA SEMICOLON
00090 NEXT K
00100 ENT
READY
RUNNH
1
OO NLD GIR
=
pu ON bt
PI
Od
>
¿a
an
\
Co
0
>
Oo ©
3
>
Input and Output to the Terminal
Commas and semicolons also allow you to control the placement of string output. For example:
00010 FRINT "FIRST ZONE" yy” THTRI ZONE" yy "FIFTH ZONE”
00020 ENT
READY
RUNNH
FIRST ZONE THIRD ZONE FIFTH ZONE
Because of the extra comma between strings, BASIC skips every other printing zone before stopping to print each
string.
3.2.2 Output Format for Numbers and Strings
BASIC prints numbers and strings according to a specific format. Strings are printed exactly as you type them in
with no leading or trailing spaces. (Quotation marks are not printed unless delimited by another pair.)
00010 FRINT “FRINTING "QUOTATION" MARKS”
00020 ENT
READY
RUNNH
FRINTING "QUOTATION" MARKS
BASIC precedes negative numbers with a minus sign and positive numbers with a space. A space is always placed
after the right-most digit of a number.
00010 FRINT —1
00020 FRINT 25550
90030 ENT
REALY
RUNNH
3 50
Leading and trailing spaces can be added within the quotation marks by using the keyboard space bar.
The number of spaces occupied by the decimal representation of a number varies according to the magnitude and
type of the number. BASIC prints the results of computations as decimal numbers (either integer or numeric) if
they are within the range
01<n<999999
where n is the number BASIC prints. Otherwise, BASIC prints them in E notation.
BASIC prints decimal digits as illustrated below:
Value You Type Value BASIC Prints
01 01
0099 9 .90000E-03
999999 999999
1000000 1.00000E06
3-10
Input and Output to the Terminal
If more than six digits are generated during a computation, BASIC prints the result of that computation in E
notation.
3.2.3 The TAB Function
Another method of positioning the terminal printer is to use the TAB function in conjunction with the PRINT
statement. (Refer to Chapter 7 for information on functions.)
This function has the following format:
PRINT TAB(n);
where:
n is an expression indicating the desired printing position. BASIC evaluates the expression and truncates
the result to an integer.
The TAB function does not cause characters to be printed: it returns a string of spaces. The PRINT statement then
prints those spaces returned by the TAB function. The number of spaces returned by TAB is n minus the current
column number. If nis less than the current column number, the TAB function returns a null string.
With the TAB function, you move the terminal printer to the right to any desired column. The first column at the
left margin is column O. Therefore, n can be 0 to whatever the right margin is on your terminal, or anywhere in
between.
The TAB function can only be used to position the terminal printer from left to right, not right to left. If you
specify a column that is to the left of the current column position, BASIC returns a null string.
You can use more than one TAB function in the same PRINT statement by placing them between clements.
The following examples contain several TAB functions in conjunction with one PRINT statement:
00010 FRINT "NAME" » TARCIO)s “ADDRESS" Y TARC30): "FHONE NO."
00020 END
READY
RUNNH
NAME ADDRESS FHONE NO.
Without tabs 15 and 30, BASIC would print
NAMEADDRESSFHONE NO,
Here is an example of printing numbers:
00010 À = 100XB = 29XC = 35
00020 FRINT As TAECLOyL; TAECIO) 3
00030 ENT
READY
RUNNH
100 2? A
Column 0 Column 15 Column 30
Input and Output to the Terminal
Notice that semicolons act as separators in the preceding example.
Compare the following examples. The first one uses commas as separators; the second one uses semicolons.
00010 A = 100
00020 В = 200
00030 C = 300
00040 FRINT Es TABC350)>By TAUC40)>C
J0050 FRINT As TARCIO?:Es TALC4039
90060 ENT
READY
RUNNH
100 200
300
100 200 300
The commas move the printer to the next zone, then BASIC executes the TAB function.
You can also place a TAB function outside a PRINT statement. However, the value of the function depends on
whether or not you did place it in a PRINT statement:
|. If TAB has not been executed in a PRINT statement then
TAB(n) = SPACES(n)
The SPACES function allows you to add spaces in a string, sec Section 7.3.6.
2. If a PRINT statement is executed with TAB. TAB(n) is a string of spaces whose length is equal to the
number of spaces between the last print position and n.
EEE УФ LE
CHAPTER 4
FORMATTED OUTPUT — THE PRINT USING STATEMENT
4.1 INTRODUCTION TO PRINT USING
When the format as well as the content of output is important, use the PRINT USING statement rather than the
PRINT statement. The PRINT USING statement allows you to control the appearance and location of data on the
output line thus enabling you to create formatted lists, tables, reports, and forms.
The following examples print a series of numbers. One program uses the PRINT statement and the other uses the
PRINT USING statement.
PRINT PRINT USING
00010 FRINT 1 00010 FRINT USING "4444444, FE" 71
00020 FRINT 100 00020 FRINT USING "FEFEERR. EF" »100
00030 FRINT 1000000 00030 FRINT USING "#F#FFF#.0#H" ; 1000000
00040 FRINT 100.3 00040 FRINT USING *“FEFTEER, EE" 100.5
00050 FRINT 0123456 00050 FRINT USING "44FFFFFFÆ" 7201234006
READY REALY
RUNNH RUNNH
1 1.00
100 100,00
1E+6 1000000.00
100.3 100.30
0401234756 0.01
READY READY
PRINT left-justifies numbers and outputs certain numbers in E (exponential) format. These characteristics make it
difficult to compare numbers. In contrast, PRINT USING allows you to format numbers so that the decimal points
are aligned, making it easier to compare the column of numbers.
You can designate the following formats with PRINT USING:
|. Numbers
Number of digits
Location of decimal point
Inclusion of symbols (trailing minus sign, asterisks, dollar sign, commas)
Exponential format
ao ow
2. Strings
Number of characters
Left-justificd format
Right-justified format
Centered format
Extended field format
© ao ow
4-1
Formatted Output - The PRINT USING Statement
The format of the PRINT USING statement is:
PRINT USING string, list
where:
string is a coded format image of the line to be printed, or the line number of an IMAGE statement. It is
called the format string. If it is a string constant, it must be enclosed in double quotation marks,
not single quotation marks.
list contains the items to be printed. Note that a comma or semicolon separating items in the list has
no effect on the output. However, a comma or semicolon placed after the last item in the list does
inhibit the movement of the terminal printer.
Consider the following example.
00010 FRINT USING "HI /LLLLL YOU WETON EE, $ LES, "y "FAUL" 714%
00020 ENT
The format string is:
“HI ‘LLLLL YOU WEIGH ###.# LBS.”
and the list contains two data items:
The string constant “PAUL”
The integer 145
In the format string, there are two fields corresponding to the two data items. The first field is "LLLLL which cor-
responds to the first data item, “PAUL”, and the second field is ###.# and it corresponds to the second data item,
145. When BASIC prints the line, it prints each data item in the position and format specified by the field. The
rest of the format string, namely “HI YOU WEIGH LBS.” is the printed message. The output of this
example is:
RUNNH
HI FAUL YOU WETGH 145,0 LES.
The way to write format strings is described throughout this chapter and is summarized in Section 4.4.
4.2 PRINTING NUMBERS WITH PRINT USING
4.2.1 Specifying the Number of Digits
With PRINT USING, you can specify the number of places reserved for digits in a field with a corresponding amount
of number signs (#).
For example:
00010 FRINT USING "###">123
00020 FRINT USING "+4+4+44", 12340
READY
RUNNH
123
12345
4-2
Formatted Output -- The PRINT USING Statement
If there arc not enough digits to fill the field specified, BASIC prints spaces before the first digit. For example:
00010 FRINT USING "#¥%¥¥"y1
00020 FRINT USING "##%¥#" +10
Q0030 FRINT USING "44444" 1709
00040 FRINT USING "EEEXEX", 1234%
READY
RUNNH
1
10 1709
12345
Note that spaces are printed before the number so that the entire field is filled. The number sign indicates where
BASIC prints a space. Placing a comma or semicolon after the list item (linc 20) causes the next item to be printed
on the same line.
BASIC rounds numbers printed with PRINT USING. For example ©
00010 FRINT USING "FER", 135,7
00020 FRINT USING "#"»5.9
00030 FRINT USING "#" 40504
READY
RUNNH
127
©
E
4.2.2 Specifying the Location of the Decimal Point
You can reserve any number of digits on both sides of the decimal point by placing a decimal point in the number
sign field. BASIC always prints the digits to the right of the decimal point, even if they are zeros. Consider the
following example:
00010 FRINT USING "#¥.¥¥#",5.72
00020 FRINT USING "EF, EXE" 739,3758
00030 FRINT USING "FE, EXE", 26
READY
RUNNH
34720
37.376
26.000
Note that BASIC prints spaces to the left of the decimal point, as necessary, but prints zeros to the right of the
decimal point. Also note that 39.3758 is rounded to 39.376.
[f there is more than one number sign to the left of the decimal point, at least one digit is printed to the left of the
decimal point. If there is only one # to the left of the decimal point and the number is negative and less than 1,
BASIC prints the minus sign to the left of the decimal point instead of a zero.
Formatted Output The PRINT USING Statement
For example:
и.
00010 FRINT USING "#%¥.4"y.99
00020 FRINT USING "EL. "v.1
00030 FRINT USING "EF. XE"'y-.1
READY
RUNNH
1.0
0.1
“ry 1
4.2.3 Printing a Number That is Larger Than the Field
If you have not reserved enough digits for a number, BASIC prints a percent sign (%) followed by the number and
ignores the format specified by the field. After BASIC prints the number, it completes the rest of the PRINT
USING statement, in the usual manner. Consider the following example:
Q0010 FRINT UOHING "FEF, EE" y 256.706 E
00020 FRINT USING "FER, FEF" y256.,786
READY
RUNNH
236.77
A 206.786
The number at line 10 is printed correctly (with rounding). In line 20, there are only 2 #’s to the left of the decimal
point; therefore, the number will not fit. The number is printed in the usual PRINT statement format, with a space x...
before and after it. But in this case, the number is preceded by a percent sign.
Be sure to enter one number sign for every number that will print on the left side of the decimal point. Add one
more number sign in case the number is negative. (For another method of reserving a place for the minus sign, sec
Section 4.2.4.1.)
Field There are cnough places for But not enough places for
FEA HA 100.569 7- 100.569
HH 1258 %-.12579 „=
À number can also be larger than its field, because -rounding increases the number of places needed. For example:
00010 FRINT USING *.##&"y . 997
00020 FRINT USING "FF" 52999
00030 FRINT USING "HO W#" 52997
READY
RUNNH
‚777
“ 0.999
1.00
4-4
ETE fs Еф оо
Formatted Output The PRINT USING Statement
4.2.4 Printing Numbers With Special Symbols
4.2.4.1 Printing Numbers With a Trailing Minus Sign - To print the minus sign for negative numbers after the
number instead of before it, specify a trailing minus sign in a field. The trailing minus sign is often used to indicate a
debit but can be used with any number. You must usc the trailing minus sign to print a number in an asterisk fill or
floating dollar sign field (see Sections 4.2.4.2 and 4.2.4.3).
If a ficld contains a trailing minus sign, BASIC prints a negative number as the number followed by a minus sign, and
prints a positive number as the number followed by a space.
Consider the following examples.
Standard Fields Fields with Trailing Minus Signs
00010 FRINT USING "###.4#";-10,54 00010 РЕТМТ USING "#¥.¥%-"y 10,04
00020 FRINT USING "4414.44" 10,54 00020 FRINT USING "EE. EF-"v»10.54
READY READY
RUNNH RUNNH
-10.54 10,54-
10.54 10.54
4.2.4.2 Printing Numbers in Asterisk Fill Fields - To print a number with asterisks (*) filling up any blank
spaces before the first digit, start the field with two asterisks. For example:
00005 PRINT USING "XX#¥.#%",1.2
00010 FRINT USING "XX¥¥.#%"y27.90
00020 PRINT USING "ЖЖ, $ # "#107
00030 FRINT USING "ЖЖ, ## "У 1007,5
READY
RUNNH
XXX1,20
KXKX27075
x107,00
1007.50
Note that the asterisks reserve two places as well as cause asterisk fill.
To print a negative number in an asterisk fill ficld, specify a trailing minus sign in the ficld. For example:
00010 FRINT USING *XX#¥F.¥##-"527.95
Q0020 FRINT USING "XX¥¥.#¥#-"»-107
00030 FRINT USING "XX#%,.%%#-"y-1007.5
READY
RUNNH
XX27495
x107,00-—
1007.50
If you attempt to print a negative number in an asterisk fill field without a trailing minus sign, BASIC prints a fatal
error message.
4.5
Formatted Output The PRINT USING Statement
4.2.4.3 Printing Numbers With Floating Dollar Signs To print a number with a dollar sign ($) before the first
digit, start the field with two dollar signs. If a negative number is desired, end the field with a trailing minus sign. =
Consider the following example:
20010 FRINT USING "$$FELF., EF" :77.,44
00020 FRINT USING "“$$EFEF, EX" 7304.55
00030 FRINT USING "$$FF., EX" y 2211,42
00040 FRINT USING "$HEF, EE-" y-125.6
O0050 FRINT USING "$$¥¥.¥%",127.82
READY
RUNNH
$77.44
$304.55
ZA 2211.42
$1253.60
- >
$127.82 т.
Note that $$ reserves places for the dollar sign and one digit; the $ is always printed. Contrast this with the asterisk
fill field where asterisks are printed only if there are leading spaces.
If you attempt to print a negative number in a dollar sign field without a trailing minus sign, BASIC prints a fatal
error message.
4.2.4.4 Printing Numbers With Commas - To insert commas in a number, placc a comma anywhere in the
format field, to the left of the decimal point (if present). There is one space allocated in the output field for each
comma, regardless of where the comma appears in the format field. BASIC then prints a comma every third digit to
the left of the decimal point. Commas, in the format field, to the right of the decimal point, are treated as literals. 1f
there is no digit to be printed to the left of the comma, BASIC does not print the comma. For example:
00010 FRINT USING "#¥,¥###4"510000
00020 FRINT USING "##, ### "759
00030 FRINT USING "434; FFF, FF" 5256069403
00040 FRINT USING "XX; FFF" » 7259
00050 FRINT USING "“FFF4; #42 #4#4" 525239
00060 ENT va
READY
RUNNH
10,000
759
$257674.,30
KX7 9 259
219 237.00
4.2.5 Printing Numbers In E (Exponential) Format
To print a number in E (exponential) format, place four circumflexes (°°°? also called up-arrows) at the end of the
field. The “7°” reserve space for the capital letter E followed by a space or minus sign (which indicates a positive or
negative exponent, respectively) and then the exponent. In exponential format the digits to the left of the decimal
point are not filled with spaces. Instead the first nonzero digit is shifted to the left-most place and the exponent is
adjusted to compensate.
MEE.
4-6
Formatted Output — The PRINT USING Statement
Consider the following example:
00010 PRINT USING "FEEL, EXT "y $
00020 FRINT USING "FFE 77"; LOOO
READY
RUNNH
4300, 00E-07
100.00E+O1
If you usc fewer than 4 carets, the number is not printed in E format but the carets arc printed as a literal. If you
use more than 4 carets, the number prints in E format but the extra carets are also printed. For example:
00010 FRINT USING "FEF, EX", 5
00020 FRINT USING "EEL, $7 ',5
READY
RUNNH
9.007”
500,00E—027
Exponential format cannot be used with asterisk fill, floating dollar sign, or trailing minus formats.
4.2.6 Fields That Exceed BASIC’s Accuracy
If a field contains more places than there are digits of accuracy, BASIC prints zeros in all the places following the
last significant digit. See the User’s Guide for the number of digits of accuracy in your system.
4.3 PRINTING STRINGS WITH THE PRINT USING STATEMENT
By using the PRINT USING statement, you can specify whether strings are printed in a left-justified, right-justified,
centered format or extended format. String fields start with a single quotation mark (’). The single quotation mark
is optionally followed by a contiguous series of uppercase L's, R’s, C’s, or E’s representing left-justified, right-
justified, centered, and extended string ficlds, respectively.
If a string is larger than the string field, BASIC prints as much of the string as fits and ignores the rest. The only
exception is extended fields, in which case BASIC prints the entire string.
4.3.1 One-Character String Fields
A string field consisting of only a single quotation mark or a single exclamation point is a 1-character string field.
BASIC prints the first character of the string expression corresponding to a 1-character string field and ignores all
following characters. For example:
20010 FRINT USING "’","*ARCDE"
READY
RUNNH
A
4.3.2 Printing Strings in Left-Justified Format
If you specify a left-justified field, BASIC prints the string starting at the left-most position. If there arc any unused
places, BASIC prints spaces after the string. If there are more characters than olaces, BASIC truncates the string and
does not print the excess characters.
4-7
Formatted Output - The PRINT USING Statement
À left-justified ficld is composed of a backslash or a single quotation mark followed by a series of capital L’s.
For example: E“
O0010 FRINT USING "”LLLLLL'" y "ARCT"
00020 FRINT USING "LEULL" > "ABC"
00030 FRINT USING "LLLL" »"12345678"
READY
RUNNH
ARCII
ARC
12345
4.3.3 Printing Strings In Right-justified Format
If you specify a right-justificd ficld, BASIC prints the string so that the last character of the string is in the right
most place of the field. If there arc any unused places before the string, BASIC prints spaces to fill the field.
A>.
A right-justified ficld is composed of a single quotation mark followed by a series of capital R’s. For example:
00010 FRINT USING ""RRRKRR">"ABCU"
00020 FRKINT USING "RÉRRKK">"A"
00030 FRINT USING "/RRRRERR" "XYZ"
READY
RUNNH
АВС
A min
XYZ
If there are more characters than places, BASIC left-justifies the string and does not print the excess characters.
4.3.4 Printing Strings In Centered Fields
If you specify a centered field, BASIC prints the string so that the center of the string is in the center of the field. If
the string cannot be exactly centered, such as a ?-character string in a S-character field, BASIC prints the string one
character off center to the left.
A centered field is composed of a single quotation mark followed by a series of capital C's. For example:
00010 FRINT USING "’CCECCCCC"»+ "A"
00020 FRINT USING " "CCCCCCC" "AE"
00030 FRINT USING “/CCCCCCC"y "ARC"
00040 FRINT USING " CCCCCCC" y "ARCT"
00050 FRINT USING *" CCCCCCO* y *ARCIE
READY
RUNNH
A
AR
ARC
ABCI
ABCTE
If there are more characters than there are places in the field, BASIC left-justifics the string and does not print the
excess characters.
4-8
EH TE E Tp 7
Formatted Output - The PRINT USING Statement
4.3.5 Printing Strings In Extended Fields
The extended field is the only field that automatically prints the entire string. If you specify an extended field,
BASIC left-justifies the string as it does for a left-justified field. But, if the string has more characters than there arc
places in the field, BASIC extends the field and prints the entire string. This extension may cause other items to be
misaligned.
An extended field is composed of a single quotation mark followed by a scries of capital ls.
Consider the following example that uses extended, left-justified, right-justified, and centered ficlds.
FRUS . B20
Friday Maw 20y 1977 174101540
00010 PRINT USING '"/LLLELLLEL"», THIS TEXT"
00020 FRINT USING "CLELLLLELALLLLAL" yy “SHOULD PRINT 7
00030 PRINT USING " LLLLLLLILLELLIL"» AT LEFT MARGINT
00040 FRINT USING "’RRER"9 "1020304"
00050 FPRINT USING '"/ RERR" y Ly 33"
00060 FRINT USINO "/RERR'"T y "ly"
00070 FRINT USING "/RRRR*y "ti"
00080 FRINT USING "’CCCCCCCCC Ts" A"
00090 FRINT USING "’CCOCCCCCCC" s "ABC"
00100 FRINT USING "/CCCCCCCCC"y "ARCDE"
00110 FRINT USING "’CCCCCCCCC" > "ABCDEFG"
00120 FRINT USING */CCCCCCCCC" y» "ASCOEFGHT "
00130 FRINT USING "/LLLLLLLLLLLLLLLLL* » "YOU ONLY SEE HALF OF THE LINCS
00140 FRINT USING "E" y "YOU CAN SEE ALL OF THE LINE WHEN EXTENDET"
00150 END
READY
RUNNH
THIS TEXT
SHOULD FRINT
AT LEFT MARGIN
17273
1,273
172
1
A
ABC
ABCDE
ABRECIEFG
AECIEFGHI
YOU ONLY SEE HALF
YOU CAN SEE ALL OF THE LINE WHEN EXTENDEL
READY
4.4 SUMMARY OF PRINT USING FORMAT
Table 4-1 Format Characters For Numeric Fields
Character Effect on Format
# number sign Rescrves place for one digit.
. decimal point (period) Determines location of decimal point.
Causes a comma to be printed between every third digit starting from the
decimal point and proceeding from right to left.
, comma
4-9
Formatted Output - The PRINT USING Statement
Table 4-1 (Cont.) Format Characters For Numeric Fields
A
Character Effect on Format
** two asterisks Cause leading asterisks to be printed before the first digit instead of spaces. The
ficld formed is called an asterisk fill field. They also reserve places for two digits.
$$ two dollar signs Cause a dollar sign to be printed before the first digit. The ficld formed is called
a dollar sign field. They reserve places for one dollar sign and one digit.
7777 four circumflexes Cause number to be printed in E (exponential) format. They also reserve four
(up-arrows) places for the E notation.
- minus sign Causes a trailing minus sign to be printed when number is negative. Printing a
negative number in an asterisk fill or a dollar sign field requires that the field also
have a trailing minus sign.
Note that neither $$ nor ** can be combined with =~" E.
For example:
Valid Fields Sample Output Description
SSHHF HR $1234.50 Dollar sign field
AHHH *#** |2 Asterisk fill field
EHHH 1,242 Comma in field
HEH 20.72E-02 E (exponential) format field a“.
Invalid Fields Reason
HE HO ** can not be combined with “777
Hit HH Comma is to the right of the decimal point
SS** HAH HH $$ can not be combined with **
String ficlds are composed of a single quotation mark optionally followed by a series of contiguous capital L's, R's,
C's, or E's. The effect these characters have on the format is described in Table 4-2.
Table 4-2 Format Characters for String Fields
Character Effect on Format
"single quotation mark or Starts string field and reserved place or one character.
! exclamation point (apostrophe)
L upper case L Causes string to be left-justified and reserved place for one character.
\\ or 2 backslashes
R upper case R Causes string to be right-justified and reserves place for one character.
C upper case C Causes string to be centered in field and reserves place for one
character.
E upper case E Causes string to be left-justified, expands field, as necessary, to print MR.
the entire string and reserves place for one character.
4-10
ENE +p EER up 17
Formatted Output - The PRINT USING Statement
4.5 THE IMAGE STATEMENT
The IMAGE statement has the following format:
-unquoted strin g Ш
or |
IMAGE unquoted string
where:
unquoted string is the format for printing characters listed in the PRINT USING statement.
: | are interchangeable.
IMAGE |
For example:
000103 $4.55 34.5%
00020 PRINT USING 10, 12,345,-12,5
READY
RUNNH
12,35 Z-12.5
All characters following the colon (or word IMAGE) except the line terminator are considered part of the output
image. | |
The IMAGE statement must be the only statement on a line. No comment fields are allowed. You can, however,
continue an image to another line with an ampersand (&) see Section 1.3.1. BASIC continues the line until it finds a
line terminator without an ampersand preceding it.
IMAGE is a non-executable statement, therefore, BASIC ignores the IMAGE statement until a PRINT USING state-
ment appears in the program. |
You can also use an IMAGE statement with string formats:
00010: ++ ‘CCCC ++ ‘LLLL
00020 INFUT A$
00030 IF A$ = "STOF" GOTO SO
00040 PRINT USING 10» AsshÂt
00050 ENT
READY
RUNNH
? ABCHUE
++ АВСПЕ ++ АВСПЕ
4.6 PRINT USING STATEMENT ERROR CONDITIONS
There are two types of PRINT USING error conditions, fatal and warning. When a fatal error occurs, BASIC stops
exccuting the program and prints a fatal error message. When a warning is present, BASIC continues to exccute the
program, although the resulting output may not be in the format intended.
Formatted Output The PRINT USING Statement
4.6.1 Fatal Error Conditions
A fatal error message is produced if:
The format string is not a legal string expression.
There are no valid fields in the format string.
A string is printed in a numeric field.
A number is printed in a string ficld.
À negative number is printed in a floating dollar sign or asterisk fill field that does not specify a trailing
minus.
NB WN
4.6.2 Warning Conditions
Warning error conditions are:
|. A number does not fit in the field. If à number is larger than the field allows, BASIC prints a percent sign
(%) followed by the number in the standard PRINT format.
2. À string does not {it in the field. If a string is larger than any field other than an extended field, BASIC
truncates the string and does not print the excess characters.
3. A field contains an illegal combination of characters. If a field contains an illegal combination of charac- A
ters, the first illegal character and all characters to its right are not recognized as part of the field. They
may form another valid ficld or they may be considered text. If the illegal characters form a new valid
field, this field may cause a fatal error condition.
Consider the following examples of illegal combinations of characters in numeric fields.
Ilegal Combinations
00010 FRINT USING "$$XXEL, ES" »5.4116.30
MÁ
READY
RUNNH
$5%X%k16.30
$$ are combined with **. $$ is a complete field and **##%.# forms a second valid field. $5 is printed by
S$ and **16.30 is printed by **####.
00010 FRINT USING "$$XXEL, EE ‘LLL"»5,41;"AEC"
REALY
RUNNH am“
$5
T 234 Numeric IMAGE srecified for a string at lime 00010 of MAIN FROGRA
M
The same illegal combination appears here, but the next data item is a string. BASIC produces the fatal
error message after trying to print the string “ABC in the numeric field **## ##.
00010 FRINT USING "##,#47"77";5,43E09
READY
RUNNH -
Z S.43E+9777
Field has only three not four. The number does not fit in the field ##.#, a % and the number are ,
printed followed by the °°°
р 2
4-12
Hill Bib ba Df 5
Formatted Output The PRINT USING Statement
00010 PRINT USING "‘LLEEE"y "VWXYZ"
READY
RUNNH
VWXEEE
Two letters can not be combined in one field.
ELL is printed as it is.
Attempting to print characters as text produces errors when the characters form a valid field. For example:
00010 FRINT USING "THERE ARE FEF # EF NAILS" ,123s4.,16,6
is an attempt to print
THERE ARE 123 + 4 NAILS
THERE ARE 16 + 6 NAILS
but instead produces
THERE ARE 123 4 16 NAILSTHERE ARE ©
To correctly print characters that form a valid field, use a string field and place the characters as a string constant in
the list. For example:
00010 A$="THE BALANCE OF ACCOUNT 44## IS 933444, 44"
O0020 FRINT USING AS: "F"y55634107.56
REALY
RUNNH
THE BALANCE OF ACCOUNT #5634 18 $107.96
This is also the only way to print a single or double quotation mark character with the PRINT USING statement.
4-13
A,
AWE,
TEE BH PERT St
SRT ЩЕ A
CHAPTER $
CONTROL STATEMENTS
5.1 TRANSFERRING CONTROL OF THE PROGRAM
The following sections describe the statements that allow you to transfer control and change the sequence of
execution.
5.1.1 Unconditional Transfer — The GOTO Statement
The GOTO statement causes control to be transferred to the statement that it identifies.
The format of the GOTO statement is:
GOTO line number
where:
line number is the next line to be executed.
This line number can be smaller or larger than the line number of the GOTO statement. Therefore, you have the
option to skip any number of lines in either direction.
BASIC executes the statement at the line number specified by GOTO and continues the program from that point.
Consider the example:
30 GOTO 110
When BASIC executes line 30, it branches control to line 110. BASIC interprets the statement exactly as it is
written; go to line 110. It is a simple imperative instruction.
Consider the following sample program with a GOTO statement:
00010 A = 2
00020 GOTO 40
00030 À = SORCA+14)
00040 FRINT AsAXA
OCOSO END
READY
RUNNH
2 4
In this program, control passes in the following sequence:
BASIC starts at line 10 and assigns the value 2 to the variable A.
Linc 20 sends BASIC to line 40.
BASIC executes the PRINT statement.
BASIC ends the program at line 50.
Bw
Notice that linc 30 is never executed.
5-1
Control Statements
Make sure that the GOTO statement is either the only statement on the line or the last statement in a multi-
statement line. If you place a GOTO in the middle of a multi-statement line, BASIC does not execute the rest of
the statements on the line. For example:
25 A = ATNCE?INGOTO SONFRINT A
BASIC never executes the PRINT statement on line 25 because the GOTO statement transfers control to line 50.
If you specify a non-executable statement in a GOTO statement such as a REM statement, BASIC transfers control
to the next executable statement after the one specified. For example:
00010 REM THIS IS AN EXAMFLE OF A GOTO
00020 INFUT AsH
00030 C = AXE
00040 FRINT "С = AXE THE ANSUWUER IS ">C
00050 GOTO 10
00060 END
READY
RUNNH
? 2592
C = AXB THE ANSWER IS 50
At line 50, BASIC transfers control to line 10. (Refer to Section 5.1.3 for the IF-THEN-ELSE statement.) Because
line 10 is a non-executable statement (a remark), BASIC ignores it and transfers control to line 20.
NOTE
Before you use the GOTO statement, be sure you know
how to stop your program from running in an infinite
loop. Refer to your User's Guide for this information.
5.1.2 Multiple Branching — The ON-GOTO Statement
The ON-GOTO statement is another means of transferring control within a program. Like the GOTO statement,
ON-GOTO allows you to transfer control to another line of the program; however, ON-GOTO also allows you to
specify several line numbers as alternatives, depending on the result of a numeric expression.
The ON-GOTO statement has the following format:
ON numeric expression | EA linc number(s)
where:
numeric expression is any legal BASIC numeric expression.
NN are interchangeable keywords.
line number(s) must be separated by commas.
The ON-GOTO statement is also known as a computed GOTO because of its dependency on the value of the
numeric expression. When BASIC executes the ON-GOTO statement, it first evaluates the numeric expression. The
value is then truncated to integer (if necessary). If the value of the expression is equal to 1, BASIC passes control to
the first line number in the list; if the value of the expression is equal to 2, BASIC passes control to the second line
number in the list; and so on. This process continues until the list is exhausted, or there are no more values. lí the
value is less than 1 or greater than the number of line numbers in the list, BASIC prints an error message.
Control Statements
The following examples illustrate the ON-GOTO statement:
() 10720730740
507607407100
В+
+В GO
OT y 110
O ON A
O ON JZ G
Notice that the line numbers in the list can be in any order. The numeric expression is evaluated, and if the value of
the expression is:
1. control branches to the first linc number specified.
2. control branches to the second line number specified.
3. control branches to the third number specified.
Consider this example:
200 ON À GOTO 5072071007300
If A=1, GOTO line 50 (first line number in the list)
If A=2, GOTO line 20 (second linc number in the list)
If A=3, GOTO line 100 (third line number in the list)
If A=4, GOTO line 300 (fourth line number in the list)
If A<1
or BASIC prints an error message
If A>4
5.1.3 Conditional Transfer — The IF-THEN-ELSE Statement
The [F-THEN-ELSE statement provides a transfer of control depending on the truth of a conditional expression (sec
Section 2.4.3).
The format of the IF-THEN-ELSE statement is:
THEN |}
GOTO line number
IF conditional expression
or
IF conditional expression THEN statement(s)
or
THEN
. line number
ELSE
toro line number S | |
IF conditional expression
statement(s)
IF conditional expression THEN statement(s) ELSE fon number |
statement(s) f
where:
conditional expression can be any expression. It can also be a variable where the value O is false and any-
thing else is truc.
statement(s) can be one or more BASIC statements including IF-THEN-ELSE.
The IF-THEN-ELSE statement gives you several choices: you may specify a conditional transfer of control to
another statement line, or you may causc another statement to execute without transferring control, depending on
the truth of a conditional expression.
A
! .
Ad
Control Statements
If the value of the conditional expression is true, BASIC transfers control to the specified line number (as in the first
format) or executes the statements following the THEN (as in the second format). If the relation is not true, the
next executable statement following the IF-THEN-ELSE statement is performed. For example:
20 IF A = 3 THEN 200
If A is equal to 3 (the relation is true), control passes to line 200. If A is not equal to 3, control docs not pass to line
200. Instead, control passes to the next sequential instruction after line 20.
Here is a complete program illustrating the IF-THEN-ELSE statement:
00010 FRINT *INFUT VALUE OF A"?NINFUT A
00015 FRINT “INFUT VALUE OF E", INFUT E
00020 IF A = O ANT E = O THEN 90
00030 IF A = E THEN PRINT "А EQUALS E"NGOTO 78
00040 IF A « E THEN 60
00050 FRINT "E TS LESS THAN A"XGOTO 75
00060 FRINT “A IS LESS THEN E
00075 IF AXE *=EXCER-+1) THEN LET L4 = D4+ANGOTO 106
00080 END
READY
RUNNH
INFUT VALUE OF A?
INFUT VALUE OF E 7
A IS LESS THEN В
25
43
If you include the ELSE clause, as in the third format, BASIC executes the ELSE clause if, and only if, the THEN or
GOTO clause preceding it is not executed. This means that if the conditional expression is false, BASIC executes the
ELSE clause.
The following example illustrates the ELSE clause:
10 IF A-:=90 THEN ($ = "AA
ELSE IF AX=80 AND A990 THEN G% = "EE
ELSE IF Ax=70 AND A<80 THEN G4 = "C"&
ELSE IF AX=60 ANL A:70 THEN G% "Ti" E
ELSE G$ = "Fe
You can also use string expressions as in this example:
300 IF C$ = "QUTFUT" GOTO 10
If the value of the string variable CS is equal to the string “OUTPUT”, control passes to line 10. Sec Section 2.4.2
for string expressions.
Care should be taken placing the IF-THEN-ELSF statement in a multi-statement line. The following rules govern the
transfer of control:
1. Execution of the physically iast THEN or ELSE clause determines the exccution of the rest of the state-
ments on the line. If the THEN or ELSE clause is executed, the next statement or statements following it
are executed. If the THEN or ELSE clause is not executed, the statements following it are not executed,
and control passes to the next line number.
5-4
ERE Ea RR ET tg С
Control Statements
For example:
00005 INFUT A
00010 IF A = 1 THEN FRINT A\FRINT "TRUE CASE*\NGOTO 20
00015 PRINT "NOT = 1°
00020 END
If A is equal to 1, BASIC prints:
RUNNH
? 1
1 TRUE CASE
Because the relation is true, BASIC exccutes the rest of line 10, which includes a branch to line 20.
If À is not equal to 1, BASIC prints:
RUNNH
NOT = 1
Because the relation is false, BASIC skips the rest of the statements on line 10 following the keyword
THEN and proceeds to execute line 15.
2. All other THEN or ELSE clauses are considered to be followed by the next line of the program:
00010 ТЫРОТ А; В; С
00020 IF AR THEN IF RIC THEN PRINT "E-C"\GOTO 30
00025 FRINT "AE"
00030 ENT
The statement GOTO 30 is executed only if A is greater than B and B is less than C. If À is either less than
or equal to B or B is greater than or cqual to C, then line 25 is executed:
RUNNH
? 1071520
AR
3. If the statement following the THEN or ELSE clause is a FOR statement (FOR modifier is not permitted,
Section 6.1.5), you must include the corresponding NEXT statement in the same THEN or ELSE clause.
For example:
10 IF A = 3 THEN FOR X = 1 TO L1ONROX)=RIXDIXKANNEXT X 8
ELSE FÜR X = 1 TO 10ХВСХ) =В (СХ) +СУМЕХТ X
5.2 EXECUTION OF LOOPS
A loop is the repeated execution of a set of statements. Placing a loop in a program saves you from duplicating and
enlarging a program unnecessarily. The following section describes how to build a loop with the FOR and NEXT
statements.
5.2.1 The FOR and NEXT Statements
Without some sort of terminating condition, a program can run through a loop indefinitely. The FOR and NEXT
statements allow you to design a loop wherein BASIC tests for a condition each time it runs through the loop. You
decide how many times you want the loop to run, and you set the terminating condition.
5-5
Control Statements
The FOR statement has the following format:
FOR variable = num expr 1 TO num expr 2 [STEP num expr 3]
where:
variable is a numeric variable known as the loop index.
num expr 1 is the first numeric expression - the initial value of the index.
num cxpr 2 is the second numeric expression — the maximum value of the index.
STEP and num expr 3 arc the incremental value of the index. The STEP size is optional, if specified, it can be
positive or negative. If not specified, the default is +1.
BASIC evaluates all numeric expressions in the FOR statement before assigning a value to the loop variable. For
example:
10 T = 3 A
20 FOR M = 10XT TO 30XT STE T
30 NEXT M
M is given the initial value of 30, and BASIC tests to determine 1f Mis less than or equal to the terminating value of
90. The loop is executed because M is less than 90. When the NEXT statement is encountered, the value of M is
incremented by 3. BASIC tests again to sce if M is greater than or cqual to 90. When the value of M is greater than
90. control passes to the statement following the NEXT statement.
The NEXT statement has the following format: an.
NEXT numeric variable(s)
where:
numeric variable(s) must be the same variable named in the corresponding FOR statement. With multiple
variables, the last loop variable must be specified first. Refer to Section 5.2.2 for
nested loops.
The FOR and NEXT statements must be used together. If you use one without the other, an error condition results. нь.
The FOR statement defines the beginning of the loop: the NEXT statement defines the end. You are actually
building a counter into your program to determine the number of times the loop is to execute.
Place the statements you want repeated between the FOR and NEXT statements. Consider the following example:
00010 FOR I = 1 TO 10
00020 FRINT I
00030 NEXT I
00040 FRINT 1
00050 ENT
In this program, the initial value of the index variable is 1. The terminating value is 10, and the STEP size is +1
(the default).
MER.
Control Statements
Every time BASIC goes to line 30, it increments the loop index by 1 (the STEP size) until the terminating condition
is met. Therefore, this program prints the values of 1 ten times. When the loop is completed, execution proceeds to
line 40. The following is the resulting output.
RUNNH
1
NON UDWMN
10
10
Notice that when control passes from the loop, the last value of the loop variable is retained. Therefore, I equals 10
on line 40.
You can modify the index variable within the loop:
10 FOR I = 2 TO 44 STEF 2
20 LET I 44
30 NEXT I
40 ENT
|
The loop in this program only executes once because at line 20, the value of 1 is changed to 44 and the terminating
condition is reached.
If the initial value of the index variable is greater than the terminal value and the step size is positive, the loop is
never executed.
10 FOR I = 20 TO 2 STEF 2
This loop cannot execute because you cannot decrease 20 to 2 with increments of +2. You can, however, accom- *
plish this with decrements of 2.
10 FOR I = 20 TO 2 STEF —2
The STEP size can also be a number with a fractional part:
10 FOR K = 1.5 TF 7.7 STEF 1432
NOTE
You should not transfer control into a loop that has not
been initialized with a FOR statement. The results will
be unpredictable. The following is not recommended in
a BASIC program:
10 REM THIS IS A POOR FROGRAM
20 GOTO 40
30 FOR I = 1 TO 20
40 FRINT I
50 NEXT I
60 END
5-7
Control Statements
Line 20 transfers control to line 40, bypassing line 30. This is illegal in BASIC.
You can place the FOR and NEXT statements anywhere in a multi-statement line. For example:
10 FOR I = 1 TO 10 STEF SX\FRINT "I = "37 INNEXT I
20 END
RUNNH
1
I
1
ó
The calculation of the index values (initial, final, and step size) is subject to precision limitations inherent in the
computer. These index values are represented in the computer by binary numbers. When the values arc integer,
they can be represented exactly in binary; however, it is not always possible to represent decimal values exactly
in binary when they contain a fractional part. Consider the following example:
00020 FOR X = 0 TO 10 STEF 0.1
00030 A = 75\F = 473\ C = A/E a.
00040 FRINT “THE ANSWER IS "#C
00050 NEXT X
00060 END
The loop established in line 20 excecutes 100 times instead of 101 because the internal value of 0.1 is not exactly 0.1.
After the 100th execution of the loop, X is not exactly equal to 10. Itis slightly larger than 10, so the loop stops.
Whenever possible, it is advisable to use indices that have integer values which ensure that the loop is exccuted the
correct number of times.
Note that changing the termination value of a loop within the loop has no effect. For example: mito.
00010 K = 10
00020 FOR I = 1 TO K
00030 К = 5
00040 PRINT Is
00050 NEXT I
READY
RUNNH
1 2 3 4 5 6 7 8 7 10
READY
5.2.2 Nested Loops
A loop can contain one or morc loops provided that each inner loop is completely contained within the outer loop.
Using one loop within another is called nesting. Fach loop within a nest must contain its own FOR and NEXT state-
ments, and the inner loop must terminate before the outer loop, i.e., the onc that starts first must be completed last.
Loops cannot overlap.
5-8
ETE TRE 77
Control Statements
The following example shows legal and illegal forms of nested loops:
LEGAL LEGAL
—10 FOR A = 1 TO 10 — 10 FOR A
[20 FOR E = 2 TO 20 | [20 FOR E
30 NEXT E 30 NEXT E
40 NEXT A — 40 FOR C = 3
50 FOR D = 4
[40 FOR E = 5
70 NEXT E
80 NEXT I
— 90 NEXT ©
L— 100 NEXT A
HoH
1
ge
e
The following is a program with a nested loop:
00010 FRINT * LT", "JA
00015 FRINT
00020 FOR I = 1 TO 2
00030 FOR J = 1 TO 3
00040 FRINT Iv.)
00050 NEXT J
00060 NEXT I
00070 ENT
READY
RUNNH
I J
1 1
1 a
1 3
= 1
и 2
a 3
TO
TO
TO
TO
TO
30
430
En
anf
E
ILLEGAL
10 FOR M =
: À
20 FOR № = 2
30 NEXT M
40 NEXT N
FOR and NEXT statements arc commonly used to initialize arrays as illustrated in this example:
00005 DIM XC5>10)
00010 FOR A = 1 TOS
00020 FOR E = 22 TO 10 STEF 2
00030 X(ArB) = A+
00040 NEXT BsA
00055 FRINT X(510)
00060 ENT
REALY
RUNNH
15
59
Control Statements
5.2.3 The Conditional FOR Statement
Another method of creating loops in a program is by using the Conditional FOR statement. The Conditional FOR
statement has the fellowing format:
- STEP WHILE
FOR variable=num expr | Ё “ , num expr | | | conditional expr
UNTIL
where:
variable is a numeric variable
num expr! is the first numeric expression which determines the initial value of the index.
STEP num expr increments the value of the index variable. This is optional. The default is +1.
WHILE is the condition tested. The expression can be a relational or logical expression.
UNTIL
This form of loop is similar to the normal FOR statement. The difference lies in the termination test for the loop.
Each time the loop is about to begin, BASIC evaluates the conditional expression and tests it for its truth value. The
loop terminates if the conditional expression is true and the clause is an UNTIL clause, or if the conditional expres-
sion is false and the clause is a WHILE clause. The NEXT statement is also required with this form of the FOR
statement.
When BASIC exits from the conditional loop, the value of the loop variable is the value that terminates the loop.
When the normal FOR-NEXT loop terminates, the value of the loop variable is the last value used in the FOR state-
ment, not the terminating value. Consider the following example:
LIST
y-12.,B20
Tuesday, May 24, 1977 15:55:20
00010 FOR I = 1 TO 10
00015 FRINT 1; INORMAL. FOR LOOF
00020 NEXT I
00025 FRINT "I = "sl
00030 FOR I = 1 UNTIL 1710 !CONDITIONAL FOR LOOF
00035 FRINT Is
00040 NEXT I
00045 FRINT "I = "vi
00050 ENT
READY
RUNNH
1 2 3 4, 5 6 7 8 9 10 I = 10
1 2 3 84 9 6 7 8 9 10 I = 11
READY
Both loops print the numbers 1 through 10. Notice, however, the difference in the values of I. When the first loop
terminates, the loop variable is set to the last value BASIC used (10). In the second loop beginning on line 30, the
loop variable is set to the value which caused the loop to terminate (11).
Control Statements
The following example illustrates the WHILE clause:
00010
00015
00020
00025
00030
READY
RUNNH
il 2
FOR I = 1 WHILE 1-10
FRINT 15
NEXT I
FRINT "I "ai
ENT
3 4 5 6 7 8 % 1 10
5.24 The FOR Statement With Additional Test
The FOR statement with an additional termination test has the following format:
BY UNTIL
TED ,
FOR variable=num expr 1 TO num expr 2 e El | num expr 3 | WHILE
| conditional expr
where:
variable
num expr 1
num expr 2
STEP num expr 3
BY
WHILE conditional expr
UNTIL
is a numeric variable (loop or index variable).
is the initial value of the index variable.
is the terminating value of the index variable,
is the increment value of the index. This is optional; the default is +1.
is a logical or relational expression. This is the additional termination test.
This type of loop is equivalent to the normal FOR-NEXT statements except for the addition of the conditional test.
Each time BASIC encounters the NEXT statement, the loop variable is incremented. After incrementing the loop
variable, BASIC checks the index variable to sce if the TO expression has been exceeded. If the TO expression has
not been exceeded, BASIC checks the conditional expression. The termination test on the conditional expression is
the same as on the Conditional FOR statement, Section 5.2.3.
Consider the following example:
00010
00020
000630
90040
00050
00060
00070
00080
00070
00100
00110
00120
REATIY
RUNNH
12
1
tat
Y = ©
FOR I =
FRINT Is
Y = I
NEXT I
PRINT "I
ГОК ОТ
PRINT 13
Y = IX?
NEXT I
PRINT
END
"1
CH CA
Hb
1 TO 10
| NORMAL. FOR LOOP
"УТ
1 TO 10 UNTIL. Y 10 1FOR WITH ADDITIONAL TEST
“I
87 8 2 10 I = 10
6 0 1 = /
Control Statements
5.2.5 WHILE And UNTIL Statements
The WHILE and UNTIL statements have the following format:
WHILE conditional expression
UNTIL conditional expression
where:
conditional expression is any numeric, logical, or relational expression.
Like the FOR statement, the WHILE and UNTIL statements require a corresponding NEXT statement. However,
the NEXT statement, in this case, docs not contain a variable.
The expression is evaluated before each loop iteration. If the expression is true, BASIC exccutes the statements
within the loop. If the expression is false, BASIC executes the statement following the NEXT statement. For
example:
00010 WHILE AX lO
00020 LET AZ = AX{IX
00030 FOR IZ = 1 TO $
00040 NEXT IX
00045 NEXT
00050 FRINT AX
00060 ENT
As long as A% is less than 10%, BASIC will execute the statements within the loop.
With the UNTIL statement, the loop executes until the expression is true. For example:
00010 I = 12
00020 UNTIL I = ©
00030 FRINT 1;
00040 I = I-1
000350 NEXT
5.3 TIME LIMITS
BASIC provides statements to suspend program execution for a specified amount of time. These statements are
SLEEP and WAIT.
5.3.1 The SLEEP Statement
The SLEEP statement has the following format:
SLEEP numeric expression
where:
numeric expression is the number of seconds to delay further execution of the program or subprogram
(Chapter 11).
For example:
10 SLEEF 120X10
Control Statements
At the end of 1200 seconds (20 minutes) BASIC continues execution.
To awaken a job from a SLEEP state before the specified number of seconds has clapsed, type a line terminator.
5.3.2 The WAIT Statement
The Wait statement has the following format:
WAIT numeric expression
where:
numeric expression specifies the maximum number of seconds allowed for all future input from the
terminal before an error condition is signalled.
For example:
10 WAIT 60
BASIC will wait 60 seconds for input before issuing an error message.
The WAIT statement is used in conjunction with the INPUT statement so that you can set time limits for responses
to your program.
A WAIT statement with a value of 0 or no value, indicates that no WAIT error condition exists no matter how long
it takes for a response. Thus, WAIT O turns off a previous WAIT.
You must place the WAIT statement before the respective INPUT statement. For example:
00010 WAIT 15
00020 INFUT ArByC
00030 D = AXE/C
00040 FRINT Ii
BASIC waits 15 seconds for a response to the INPUT statement. If no response is typed, BASIC prints an error
message.
5.4 STOPPING PROGRAM EXECUTION — THE STOP AND END STATEMENTS
There are three methods of halting program execution:
1. Executing all the statements
2. Using the STOP statement
3. Using the END statement
The first method is shown in the following example. The program executes completely and then BASIC closes all
files:
10 FOR I = 1 TO 10
20 FRINT |
30 NEXT I
The STOP statement has the following format:
STOP
5-13
Control Statements
This statement causes program execution to halt, at which point BASIC prints a message:
STOP AT LINE n
where:
n is the line number of the STOP statement.
You can place several STOP statements at various points in a single program. The flow of logic can then be seen
throughout the program. This is a uscful debugging tool in determining program flow in large programs.
The STOP statement halts execution but it does not close files. To cause BASIC to close files at program termina-
tion. use the END statement.
The END statement has the following format:
END
The END statement is optional unless subprograms are in the same program. Sec Chapter 11 for information on sub-
programs. If you include an END, it must have the largest line number in the main program. Any reference to an
END statement via a GOTO or IF-THEN-ELSE statement terminates program exccution and closes all files.
An END statement does not cause BASIC to print a message on the terminal. If a message is desired, use the STOP
statement.
If you do not include a STOP or an END statement in a program, the execution of the last statement of the program
terminates program exccution and closes all files.
The following examples show all three options of ending a program:
00010 READ Ay С
00020 FEKINT "A == "ЗА
0030 FRINT "E == "Tí BASIC executes all statements
00040 FRINT "UC = "al and closes all files.
00050 LATA 10073007450
READY
RUNNH
A = 100
В = 300
C = 450
00010 READ AsLyC
00020 FRINT "A = "A
00030 PRINT "It = "gl BASIC executes all statements
00040 FRINT "С = "+#C and stops execution at line 60.
00050 DATA 1003005450 Files are not closed.
00060 STOF
READY
RUNNH
A = 100
E = 300
С = 450
STOF at lime 00060 of MAIN FROGRAM
5-14
AMR
Control Statements
00010 READ A+R С
00020 PRINT "A = "sf
90030 FRINT "В "y E BASIC executes all statements
00040 FRINT "С = "С and closes all files.
00050 ПАТА 100,300,450
00060 END
В
READY
RUNNH
A = 100
E 300
С 450
{i
As you can see, the first and third examples have the same output. END is only necessary when you plan to refer-
ence the end of the program with a transfer statement.
5.5 SUBROUTINES
Subroutines are like functions (Section 2.4.6) in that you reference them in another part of the program. However,
unlike functions, you do not name a subroutine or specify an argument. Instead, you include the GOSUB state-
ment, which transfers control of the program to a subroutine, and the RETURN statement, which returns control
from that subroutine back to normal program execution.
in BASIC, you can enter more than one subroutine in the same program. Subroutines are casier to locate (for
debugging purposes) if you place them ncar the end of the program, before any DATA statements, and before the
END statement (if present). Also, assign distinctive line numbers to subroutines. For example, if the main program
has line numbers ranging from 10 to 190, begin the subroutines with line numbers 200, 300, 400 and so on.
The first line of a subroutine can be any legal BASIC statement including a REM statement. Note that you do not
have to transfer to the first line of the subroutine. Instead, you can include several entry points and RETURNS in
and out of the same subroutine. Similarly, you can nest subroutine calls (one subroutine within another) up to a
system defined limit. See your User’s Guide.
The following sections describe the building of subroutines with the GOSUB and RETURN statements.
5.5.1 The GOSUB and RETURN Statements
When BASIC begins executing a program, it continues until it encounters a GOSUB statement. The GOSUB state-
ment has the following format:
GOSUB line number
where:
line number following the keyword GOSUB can be the first line of the subroutine or an entry point
within the subroutine.
BASIC transfers control to that line. For example:
10 GOSUE 200
BASIC stops execuring sequentially at line 1O and transfers control to line 200. BASIC executes the subroutine
until it encounters a RETURN statement, which causes BASIC to transfer control back to the statement immedi-
ately following the calling GOSUB statement. (A subroutine can exit only through a RETURN statement.)
Control Statements
The RETURN statement has the tollowing format:
RETURN
Before transferring control to a subroutine, BASIC internally records the next sequential statement following the
GOSUB statement. The RETURN statement is a signal to BASIC to return to the statement previously recorded.
Ín this way, no matter how many subroutines there arc or how many times they are called, BASIC always knows
where to transfer control. For example:
00010 INFUT Asis:
009020 GOLUR 40
00030 FRINT Ii
00035 GOTO 76
00040 KEM THIS IS A SUERQUIINE
00050 II = A X I « LC
00060 RETURN
QO070 EN
[ine 20 sends BASIC to line 40; then line 60 returns execution to line 30. The resulting output is:
RUNNH
T 5910415
SU
The following is an example of several calls to the same subroutine:
00010 DIM ECIOO)
00020 GOSUR 60 er
90030 GOSUE 60
00040 GOSULE 50
00050 GOTO 110
00060 LET A = O
90070 FOR I = 1 То 2
90080 LET À = A+ECI)
00090 NEXT 1
00100 RETURN
00110 ENT ME“
The same subroutine on line 60 is called three times. Notice that only one RETURN statement is necessary.
5.5.2 The ON-GOSUB Statement
The ON GOSUB statement is used to conditionally transfer control to one of several subroutines or to onc of
several entry points into one or more subroutines. The ON-GOSUB statement has the following format:
ON numeric expression GOSUB line number(s)
where:
numeric expression is any legal BASIC numeric expression.
line number(s) a list of line numbers contained in the program, separated by commas.
The ON-GOSUB statement works like the ON-GOTO statement (Section 5.1.2). When BASIC executes the
ON-GOSUB statement. it first evaluates the numeric expression. The value is then truncated to integer, if pr
necessary.
Control Statements
If the value of the expression is
|, control passes to the first line number specified.
2, control passes to the second line number specified.
3, control passes to the third line number specified.
and so on. If the expression is less than 1 or greater than the number of line numbers in the list, BASIC prints an
error message to that effect. The following is an example of an ON GOSUB statement:
20 ON A+R COSUE 20053005120
When A+B=1, go to the subroutine on line 200, (first line number in the list)
A+B=2, go to the subroutine on line 300, (second line number in the list)
A+B=3, go to the subroutine on linc 120, (third line number in the list)
(A+B)<1, print error message,
(A+B)>4, print error message.
The line numbers to which BASIC branches can be cither the first linc of a subroutine or an entry point to a
subroutine.
5.6 ERROR CHECKING
Normally, BASIC detects errors while executing a program and either terminates exccution or prints a warning mes-
sage. These errors fall into two general categories:
|. Computational errors
2. Input and output errors
However, if you plan ahead, you can prepare alternatives which can save you time in the event of an error. You can
build an error-handling routine that is activated when, and if, BASIC finds an error. This routine takes control away
from the normal system crrors and gives it to your crror-handling routine.
5.6.1 ONERROR GOTO and RESUME Statements
The ONERROR GOTO statement provides the means for trapping errors. This statement has the following format:
ONERROR GOTO line number
where:
line number after the keyword GOTO specifics the beginning of the error-handling routine.
This statement tells BASIC that a user error-handling routine exists beginning at the specified line number. The
routine analyzes any input-output or computational error the program encounters and tries to recover from it.
If an crrer occurs before BASIC executes the ONERROR GOTO statement, BASIC proceeds with normal system
error handling.
If an error occurs after the ONERROR statement has been executed, program execution is interrupted. and BASIC
transfers control to your error routine.
Control Statements
During the execution of the error-handling routine. the variable
ERR is set to one of the values listed in the error table (Table 5-1).
ERL is set to the line number where the error occurred.
ERNS is set to the name of the program or subprogram being executed.
If an error occurs within the user error-handling routine, the system error handler takes over. Within the error-
handling routine. the ONERROR GOTO 0 returns error processing to the system.
The ONERROR GOTO statement is Jocal to the program, subprogram (Chapter 11), or function in which it is con-
tained. However, a special keyword can alter this situation:
ONERROR GO [[TO]] BACK
With this statement, if an error occurs in a function (Chapter 7) or subprogram (Chapter 11), BASIC can check the
caller of the function or subprogram for a user error-handling routine. (ONERROR GO [то] BACK does not
extend across a CHAIN boundary, Section 11.2.) em
You place the RESUME statement at the end of the error-handling routine. The RESUME statement has the follow-
ing format:
RESUME [line number []
The RESUME acts like the RETURN statement. It returns to the program line that caused the error. A RESUME
statement without a line number resumes execution at the beginning of the line where the error occurred. If the line
contains multiple statements, BASIC usually resumes execution at the beginning of the line. However, if you have a
DEF, FNEND. DIM. FOR. or NEXT statement in a multi-statement line, exccution resumes:' “mn
|. Right before the DEF statement
2. Right after the FNEND statement
3. Right after the DIM statement
4. Right after the FOR, WHILE, or UNTIL statement. (The loop will not be reinitialized.)
5. Right after the NEXT statement
[If you have two or all five of these statements in a multi-statement line, exccution resumes at the last one
encountered. A
[f you specify a line number after the RESUME statement, BASIC resumes execution at the beginning of that line.
For example, the following illustrates both methods:
200 RESUME
200 RESUME 25
If the error-handling routine is in a multi-line function or subprogram, then the line number in the RESUME state-
ment must refer to a line within the function or subprogram.
5.6.2 Error Table
The following table lists the values of the variable ERR and the corresponding error messages.
On the DECSYSTEM-20, execution resumes at the beginning of the line. a
Control Statements
Table 5-1
Error Table
ERR
Message Printed
Meaning
BAD DIRECTORY FOR DEVICE
The directory of the device referenced is in an unread-
able format.
ty
ILLEGAL FILE NAME
The filename specified is not acceptable. It contains
embedded blanks or unacceptable characters.
ACCOUNT OR DEVICE IN USE
The specified operation cannot be performed because
the file is already open by someone else. This message
has a general “file in use” meaning.
NO ROOM FOR USER ON DEVICI:
Storage space allowed for the current user on the device
specified has been used or the device as a whole is too
full to accept further data.
CANT FIND FILE OR ACCOUNT
The file specified or current user account numbers were
not found on the device specified. This message has a
general “not here” meaning.
NOT A VALID DEVICE
Attempt to use an illegal or non-existent device.
1/0 CHANNEL ALREADY OPEN
An attempt was made to open one of the 1/0 channels
which had already been opened by the program.
DEVICE NOT AVAILABLE
The device requested is currently reserved by another
user.
1/0 CHANNEL NOT OPEN
Attempt to perform 1/0 on one of the channels that
has not been previously opened in the program.
PROTECTION VIOLATION
The current user is not allowed to perform the
requested operation on the specified file. Input may
have been requested from an output-only device or
vice versa. This message has a general “can’t do that”
meaning.
END OF FILE ON DEVICE
Attempt to perform input beyond the end of a date file.
FATAL SYSTEM I/O FAILURE
An 1/0 error has occurred on the system level. The
user has no guarantee that the last operation has been
performed.
13
USER DATA ERROR ON DEVICE
One or more characters may have been transmitted in-
correctly due to a parity error, bad punch combination
ona card, or similar error.
14
DEVICE HUNG OR WRITE LOCKED
Check hardware condition of device requested. Pos-
sible causes of this crror include a linc printer out of
paper or high-speed reader being oft-line.
5-19
Control Statements
Table 5-1 (Cont.) Error Table
ERR Message Printed Meaning
15 KEYBOARD WAIT EXHAUSTED Time requested by WAIT statement has been
exhausted with no input received from the specified
keyboard.
16 NAME OR ACCOUNT NOW EXISTS An attempt was made to rename a file with the name
of a file which already exists. or an attempt was made
by the system manager to insert an account code that
is already within the system.
17 TOO MANY OPEN FILLES ON UNIT Only one DECtape output file is permitted per
DEC ape drive. Only one open file per magtape drive
1s permitted.
28 PROGRAMMABLE °C TRAP ON ELRROR-GOTO subroutine was entered through a
program trapped by means of control C.
30 DEVICE NOT FILE-STRUCTURED An attempt is made to access a device, other than a
disk as a file-structured device. This error occurs, for
example. when the user attempts to gain a directory
listing of a non-directory device.
31 ILLEGAL BYTE COUNT FOR I/O The buffer size specified in the RICORDSIZE option of
the OPEN statement docs not match the I/O attempted.
43 VIRTUAL ARRAY NOT ON DISK À non-disk device is open on the channel upon which
the virtual array is referenced.
44 MATRIX OR ARRAY TOO BIG In-core array size is too large.
45 VIRTUAL ARRAY NOT YET OPEN An attempt was made to use a virtual array before
opening the corresponding disk file.
46 ILLEGAL I/O CHANNEL Attempt was made to open a file on an 1/0 channel
outside the range of legal channel.
47 LINE TOO LONG Attempt to input a line longer than the buffer.
48 FLOATING POINT ERROR Floating point overflow or underflow. If no transfer
is made to an error handling routine, a 0 is returned as
the floating-point value for underflow and the maxi-
mum positive number for overflow.
49 ARGUMENT TOO LARGE IN EXP Value is outside of legal range.
50 DATA FORMAT ERROR
51 INTEGER ERROR Attempt to usc a number as an integer when that num-
ber is outside the allowable integer range. If no transfer
1s made to an crror handling routine, a Ô is returned as
the integer value.
Control Statements
Table 5-1 (Cont.) Error Table
ERR Message Printed Meaning
52 ILLEGAL NUMBER Improperly formed input. For example, “1,.27 is an
improperly formed number.
53 ILLEGAL ARGUMENT IN LOG Negative or zero argument to log function. Value
returned is the argument as passed to the function.
54 IMAGINARY SQUARE ROOTS Attempt to take square root of a number less than O.
If no transfer is made to an error handling routine, the
value returned is the square root of the absolute value
of the argument.
55 SUBSCRIPT OUT OF RANGE Attempt to reference an array element beyond the
number of elements created for the array when it was
dimensioned.
56 CANT INVERT MATRIX Attempt to invert a singular matrix.
57 OUT OF DATA A READ requested additional data from an exhausted
DATA list.
58 ON STATEMENT OUT OF RANGE The index value in an ON GOTO or ON GOSUB state-
ment is less than 1 or greater than the number of line
numbers in the list.
59 NOT ENOUGH DATA IN RECORD An INPUT statement did not find enough data in onc
line to satisfy all the specified variables.
60 INTEGER OVERFLOW, FOR LOOP The integer index in a FOR loop attempted to go
beyond implementation defined limits.
61 DIVISION BY 0 Attempt by the user program to divide some quantity
by 0. If no transfer is made to an error handling
routine, the largest positive number is returned as the
result.
521
"лай
A,
ЗМ 1,
MES,
FE EEE
CHAPTER 6
STATEMENT MODIFIERS
6.1 MODIFYING STATEMENTS
Another useful tool for building programs is the statement modifier. In BASIC, the statement modifier qualifies or
restricts the execution of a statement; thus allowing you to:
1. Indicate conditional execution of a statement
2. Create an implied loop
An implied loop built with a statement modifier iterates only one statement on a line. In cases where the FOR-
NEXT statement loop is extremely simple, the necessity for both the FOR and NEXT statements is eliminated.
BASIC provides five statement modifiers:
IF
WHILE
UNTIL
UNLESS
FOR
NS N —
These statement modifiers cannot stand alone; they must be appended to a statement. Most BASIC statements can
be modified. There are some, however, that cannot be modified, and some that do not nced to be modified. Table
6-1 lists the various statements.
When using statement modifiers with the various forms of the IF statement, the following rules apply:
1. Append statement modifiers to either the THEN clause or the ELSE clause of an IF statement.
2. The statement modifier applies only to the clause it is appended to and not to the statement as a whole.
If you have more than one statement on a line, the modifier applies only to the statement immediately preceding it.
You can also append more than one statement modifier to a single statement. In this case, BASIC processes the
modifiers from right to left. Sce Section 6.1.5. Statement modifiers are reserved words. Sec Appendix С.
6.1.1 The IF Modifier
The IF modifier has the following format:
statement IF condition
where the condition can be any numeric expression.
BASIC tests to sce if the condition is true or false. The statement executes only if the condition is true.
For example:
10 FRINT X IF X <= O
6-1
Statement Modifiers
Table 6-1 Statements
Can Have Modifiers Cannot Have Modifiers
CALL DATA
CHAIN DEF
CHANGE DIM
CLOSE END
GOSUB FNEND
GOTO FOR
IF-THEN-ELSE NEXT
INPUT REM
KILL SUB
LET SUBEND
MAT INPUT UNTIL
Matrix Initialization WHILE
MAT PRINT
ON GOSUB
ON GOTO
ONERROR
OPEN
PRINT
RANDOMIZE
RESTORE
RESUME
RETURN
SLEEP
STOP
EN
BASIC prints the value X only if X is not equal to 0. The example is the same as using the IF-THEN-ELSE
statement:
10 IF X <= O THEN FRINT X
Note that you cannot add an ELSE or a THEN clause to the IF modifier. However, you can use the IF modifier in
a THEN or ELSE clause:
10 IF A=R THEN FRINT RB IF E<100
The IF modifier in this example applies only to the statement PRINT B. BASIC prints the value of B when both the
following conditions are true.
|. If AiscqualtoB
2. If Bis less then 100
6.1.2 The UNLESS Modifier
The UNLESS modifier has the following format:
statement UNLESS condition
where the statement executes only if the condition is false. For example:
10 FRINT A UNLESS A=0
6-2
Statement Modifiers
BASIC prints the value of A only if A is not equal to O.
The following examples produce the same results as the UNLESS modifier:
10 FRINT A IF NOT A=0
20 IF NOT A=0 THEN FRINT A
30 IF A <x О THEN FRINT А
The UNLESS modifier simplifies the negation of a logical condition.
6.1.3 The WHILE Modifier
The WHILE modifier has the following format:
statement WHILE condition
where the statement executes repeatedly as long as the condition is truc.
For example:
00010 Y=2
00020 Y=Y"(2) WHILE Y<1ES
00030 FRINT Y
Line 20 executes over and over as long as X” (2) is less than 1E6. When X”(2) is greater than or equal to 1E6. BASIC
executes line 30.
The WHILE modifier sets up a loop wherein one statement executes iteratively if the condition is true. There is no
formal control variable, i.e., I=1 TO 10, as in a FOR-NEXT loop. Instead, the structure of the loop modifics the
values which determine loop termination.
The previous example is equivalent to:
00010 Y=2
00020 V=Y7 (2)
00030 IF Y7CZI<1E6 GOTO 40 ELSE GOTO $
00040 FRINT Y
00050 END
Be careful not to create an infinite loop with the WILLE modifier. The following sequence never terminates
properly:
10 X=X+1 WHILE I<1000
Lis set to 0 at the beginning of program exccution; therefore lis less than 1000. The condition of the WHILE
modifier is unrelated to the assignment X=X+1.
Because CO is always less than 1000, the statement causes an infinite loop.
Consider the following example:
Q0010 READ 7 WHILE Z < 10
00020 IF 7 == 10 THEN PRINT *7WHILE ON REAL FAILET., "
00030 DATA 1929394959 by/ 9899910
00040 END
6-3
Statement Modifiers
Line 10 reads the data in line 30 until it reaches 10. Then the WHILE condition is no longer true, and line 20
executes.
RUNNH
PWHILE ON READ FAILED.
6.1.4 The UNTIL Modifier
The UNTIL modifier has the following format:
statement UNTIL condition
where the statement executes repeatedly as long as the condition is false. For example:
00005 X = 40
00010 X = X + 1 UNTIL X > 79%
00020 FRINT X
Line 10 executes repeatedly as long as X is less than or equal to 795. The statement continues until the condition
becomes true.
The UNTIL modifier is similar to the WHILE modifier in that it does not need a formal control variable to deter-
mine loop termination.
The previous example is equivalent to:
00005 X = 7
00010 X = X
00015 FRINT
00020 IF X <:=795 GOTO 10
Be careful not to create an infinite loop with the UNTIL modifier.
Consider the following example:
00010 A=1\B=2\C=3
00020 LET N=C+2XA UNTIL D.-=50
00030 IF D>-=50 THEN FRINT Г
Line 20 continues to execute as long as D is less than 50. Once D is greater than or equal to 50, BASIC proceeds to
line 30.
6.1.5 The FOR Modifier
The FOR modifier has the following format:
statement FOR variable = num expr | { SEP num expr 2 em conditional expr
BY UNTIL
or
statement FOR variable = num expr! TO num expr2 [STEP num expr3]]
The FOR modifier is uscd to create an implied loop on a single line.
6-4
6 Вор
Statement Modifiers
For example:
10 PRINT I» SQR(I)> FOR I = 1 TO 10
is equal to
10 FOR I = 1 TO 10
20 PRINT I» SORCI)D
30 NEXT I
By using the FOR modifier for simple loops, you eliminate the need for the FOR-NEXT statement. Notice that the
FOR modifier applies only to one statement on the line. Hence, it iterates only one statement. You can have many
FOR modifiers in a single program.
The STEF and BY clauses increment the index variable just as they do in the FOR statement. The default is +1.
10 FRINT A=EXC FOR I = 1 TO SO STEF 3
If you use the WHILE or UNTIL option, the loop continues as long as the WHILE condition is true: the loop con-
tinues as long as the UNTIL condition is false.
The following is an example of a FOR modifier and an IF modifier:
10 LIM XC100)
20 PRINT Ir» XI) IF X(I) <x O FOR I = 1 TO 100
With more than one modifier, BASIC reads from right to left. Therefore, the implied loop, I=1 TO 100, exccutes
first, then the IF modifier is tested. Appending more than onc modifier to a statement is known as nesting modifiers.
Consider the following examples:
10 LET A=A+J FOR J=1 T0 10 IF A+J<10
20 LET E::E-J FOR J=1 TO 10 UNLESS E=10
30 LET C=C+JIX2 FOR J=1 TO 4 WHILE C:10
40 LET L=0-) FOR J=2 TO 10 STEF 2 UNTIL [=-10
50 LET F:=I+J4 FOR I=1 TO $ FOR J=2 TO 6
60 ENT
In cach case, the modifiers are tested from right to left. If the first modifier fails, BASIC continues exccution at the
next statement of the program (not the next modifier on the same line).
6-5
AE,
CHAPTER 7
FUNCTIONS
7.1 TYPES OF FUNCTIONS AVAILABLE
Functions perform a series of numeric or string operations on the arguments you specify and return a result to
BASIC (see Section 2.4.6). You can use functions which return numeric values in numeric expressions and func-
tions which return string values in string expressions. BASIC provides numeric functions, string functions, con-
version functions, date and time functions, and user-defined functions. BASIC-PLUS-2 library functions are
reserved words. See Appendix C.
7.2 NUMERIC FUNCTIONS
The BASIC-PLUS-2 numeric functions perform standard mathematical operations.
BASIC provides the following trigonometric functions:
SIN — sine
COS — cosine
TAN — tangent
ATN — arctangent
BR N —
In addition, BASIC has a special function, PI, which returns the value of a transcendental number frequently used as
a trigonometric constant.
BASIC also has algebraic functions:
SQR — the square root of a number
EXP — the value of e, an algebraic constant, raised to any power
LOG and LOG10 — the logarithm of a number
INT — the integral part of a number
ABS — the absolute value of a number
FIX — the truncated value of a number
SN ER 0 VO
All BASIC numeric functions return real numbers (internally) as opposed to integer values. Note that a numeric
argument to a function is converted to integer by truncation.
7.2.1 Trigonometric Functions (SIN, COS, TAN, ATN, and PI)
BASIC provides functions, SIN and COS, to find the sine and cosine of an angle in radians. In addition, you can
use the ATN function to find the arctangent of a number, the angle whose tangent is equal to the number. The
format of these functions is:
SIN(ex pression)
COS(expression)
TAN(expression)
ATN(expression)
7-1
Functions
The PI function returns a numeric constant, 3.141593. The accuracy of this number depends on your system. a
Because Pl is a transcendental number, the value the PI function returns is only an approximation. The format
of the PI function is:
PI
PI can be used in any expression.
Do not include an argument with PI; if you do, BASIC prints an error message.
Consider the following example:
00010 REM CONVERT ANGLE (X) TO RADIANSy AND
00020 REM FIND SIN ANT COS
00025 FRINT "DEGREES" "RADIANS" y "SINE" y» "COSINE"
00030 INFUT X“NGO TO 100 IF X<O
00040 LET Y=X%FI1/180
00050 FRINT Xy Y »SINCY):COSY) -
00060 GOTO 30
00100 ENT
READY
KUMNH
DEGREES RADIANS SINE COSINE
т о
О О О 1
7? 10 AT.
10 О, 1745529 О,1736482 0. 7343078
? 20
20 O. 347085583 O. 34720701 0. 7390726
т 30
30 0. 5235983 0.5 O. 3556054
? 360
360 6.283180 O 1
T 45
45 0.7853982 0.70710468 0.7071068
? -1 о
Note that in this example, PI is used to convert degrees to radian measure (line 40).
The TAN function returns the tangent of the argument you supply. The TAN function has the following format:
TAN(expression)
where:
expression must be given in radians.
The ATN function returns the valuc in radians of the angle whose tangent is equal to the argument. The format
of the ATN function is:
ATN(expression)
NS EEE dj
Functions
The value BASIC returns is also in radians.
The ATN function returns a value in the range +P1/2 to -PI/2.
The following example tests the ATN function. The program inputs an angle in degrees, converts it to radians,
and calculates the tangent of the angle according to this formula:
TAN(X) =SIN(X)/COS(X)
Then the program converts the tangent to an angle using the ATN function and prints the results. The angles
returned by the ATN function should be the same as the angles you supply.
00100 PRINT "SUFPLY AN ANGLE IN DEGREES"
00110 FRINT "ANGLE" » "ANGLE" » * TAN CX)" y» "АТАМСХ ) " » "АТАМСХ ) *
00120 FRINT “(DEGS) "y " CRALS) "y y " CRALS)" y» (DEGS)"
00130 INFUT X\GO TO 200 IF X<0
00140 Y=XXFI/180
00150 Z=SIN(CY)/COSCY)
00160 PRINT XsY» Z»ATNCZ)sATN(Z)X180/FI !COMPUTE ARCTANGENT
00170 PRINT
00180 GOTO 130
00190 GOTO 130
00200 END
READY
RUNNH
SUFFLY AN ANGLE IN TEGREES
ANGLE ANGLE TANCX) ATAN(X) ATAN(X)
(DEGS) CRALS) (RADS) (DEGS)
то
О О 0 О 0
4% O, 7853787 1 0.7853982 45
? 10
10 0.1745329 0.176327 0.1745329 10
? 1
7.2.2 Algebraic Functions
BASIC has several algebraic functions that you can use in calculations:
SQR Square root function
EXP Exponential function
LOG Logarithm function
LOG10 Common Logarithm function
INT Integer function
ABS Absolute Value function
SGN Sign function
FIX Fix function
—
1
2
Functions
7.2.2.1 Square Root Function (SQR) — The SQR function returns the square root of the expression you specify. —
The format of the SOR function is:
SQR(expression)
If the value of the expression is negative, BASIC prints a warning message and the function returns the square root
of the absolute value of the expression.
00010 INFUT X“NGOTO 100 IF X0
00020 LET Z=SQRCX)
00030 FRINT Z
00040 GOTO 10
00100 END
READY
RUNNH
? 16 PE.
4
T 1000
31.462278
? 12345
111.1081
? 25E2
50
? 1970
44, 38468
? 1 a
7.2.2.2 Exponential and Log Functions (EXP, LOG, and LOG10) - The exponential function, EXP, returns e,
an algebraic constant, raised to the power specified by the expression, where e is the base of the natural logarithm
system. The value of e is approximately 2.71828. The accuracy of this number is system-dependent.
The format of the exponential function is:
EXP(expression)
The logarithm function LOG returns the logarithm to the base ¢ of the expression.
The format of the LOG function is:
LOG(expression)
EXP and LOG are related functions. Specifically, EXP is the inverse of LOG. The following formula describes
their relationship:
LOG(EXP(X)) = X
Consider the following examples. Note that the output from one example is used as the input for the other.
AMEN
7-4
IE FT Ea E с E Bol EEE En Ми
Functions
EXP Function
00010 INFUT X\GOTO 100 IF X-0
00020 FRINT EXF(X)
00030 GOTO 10
00100 END
READY
RUNNH
? 4
54,59815
? 10
22026,47
? 9,42190
12344,92
? 4, 60517
99,99998
? 25
7.20049E+10
? —1
LOG Function
Q0010 INPUT X\GO TO 100 IF Х-0
00020 FRINT LOGCX)
00030 GOTO 10
00100 ENT
READY
FRUNNH
T 54.579815
4
? 2206.47
74697149
? 12344,92
9.421
т 99,99998
4, 690517
? 7,20049E+10
25
dos
? 1
The LOG10 function returns the common logarithm (base 10) of the specified value. The form of the LOGIO
function is:
LOG10(expression)
Programs that require the computation of logarithm (base 10) do not have to use the conversion formula described
above. For example:
00010 INFUT X
00020 FRINT "X" y "LOG1O(X)*
00030 FOR I = 1 TO 5
00040 FRINT XxX I,LOGÍO(X T)
00050 NEXT I
READY
RUNNH
T 5.732
X LOGLOCX)
44732 0.7583062
32.85582 1.516612
188.3296 2.274919
1079, 505 3.033225
6187.724 3.791531
If the expression supplied for the LOG or LOG 10 function is equal to or less than zero, BASIC prints a message,
and the function returns a value of zero.
7.2.2.3 The Integer Function (INT) -- The integer function returns the value of the greatest integer that is less
than or equal to the expression you specify. The format of the integer function is:
INT(expression)
7-5
Functions
For example:
00010 FRINT INT(34.47)
00020 FRINT INT(33000.9)
READY
RUNNH
34
33000
The INT function always returns the value of the greatest integer that is less than the specified integer; however,
when you specify a negative number, INT produces a number whose absolute value is larger. For example:
00010 FRINT INT(-23.45)
00020 FRINT INT(-14.7)
00030 FRINT INT(-11)
READY
RUMNNH
24
E.
1%
Note that the value returned by INT is a real number.
You can use the INT function to round off numbers to the nearest integer by adding 0.5 to the argument. For
example:
00010 FRINT INT(34,467+.5)
00020 FRINT INT(-G.14+.5)
READY
RUNNH
35
You can also use INT to round off a number to any given decimal place or any integral power of 10. Do this by
using the formula:
rounded off number = INT(number*10”P+.5)/10”P
where P represents the number of places of accuracy and is positive for accuracy to the right of the decimal point
and negative for accuracy to an integral power of 10.
7-6
00050
00100
00110
00115
00120
00130
00140
00150
00160
00170
001890
01000
Functions
Consider the following example, which rounds numbers to the number of decimal places specified (line 150):
REM FROGRAM TO ROUND OFF DECIMAL NUMBERS
FRINT
INPUT
IF N
FRINT
INFUT
PRINT
LET A
FRINT
FRINT
GG TO
END
"WHAT NUMBER DO YQU WISH TO ROUND OFF"
N
-9999 THEN 1000
"TO HOW MANY FLACES";
P
yy
ia
=INT(NX10"F+.5)/(107F)
Ns "="57A "TO"yFy "DECIMAL FLACES, *
100
READY
RUNNH
WHAT NUMBER DO YOU WISH TO ROUND OFF 7 96.1237
TO HOW MANY FLACES 7 2
LP |
es
= 96.12 TO DECIMAL FLACES.
WHAT NUMBER LO YOU WISH TO ROUND OFF 7 8.449
TO HOW MANY FLACES 7 1
8,449 = 8.4 TO 1 DECIMAL FLACES.
OFF ? 79999
WHAT NUMBER DO YOU WISH TO ROUND
7.2.24 The Absolute Value Function (ABS) - The ABS function returns the absolute value of the specified
expression. The form of the ABS function is:
ABS(ex pression)
The absolute value of a number is always positive. If the expression is a positive number, the absolute value is equal
to that number. If the expression is a negative number, the absolute value is equal to -1 times the number. For
example:
00010
00020
00030
00040
00100
READY
INFUT XANGO TO 100 IF X=0
X=ARS (X)
FRINT X
GOTO
END
10
7-7
Functions
RUNNH MM.
? - 3 + 7
35.7
>
1
259120
2 + УЕ. +21
? 10555567
1, 05555/7E+7
? 10.12345
10.12345
P -44,5956568
44,55567
т о
Note that the ABS function returns a real number even if the argument is an integer.
ME
7.2.2.5 The SIGN(SGN) And FIX (Fix) Functions -- The sign function determines whether an expression is
positive, negative or equal to 0. The format of the SGN function is:
SGN(expression)
If the expression is positive, SGN returns a value of +1. If the expression is negative, SGN returns a value of - 1. If
the expression is equal to zero, SGN returns a value of zero. For example:
00010 A=-7,32
00020 E=,44 a
00030 C=0
00040 FRINT *A="yAy"E="y Ey "C="yC
O0050 FRINT "SGNCA)=" SGNCA):,
00060 FRINT "SGNCB)=" 3 SGNCR) »
00070 FRINT "SONCC)="ySENCC)
00080 ENT
READY
RUNNH Re,
A=-7432 E: 0.44 = O
SONCA)I=-1 SGN(R)= 1 SGNCC)= O
Note that the SGN function returns the values as a real number.
The FIX function has the following format:
FIX(expression)
The FIX function returns the truncated value of the argument y ou supply as a real number not an integer. For
example:
FIX(-.5)=0
FIX(2.6)=2
The FIX function is equivalent to:
MONEY
SGN(X)*INT(ABS(X))
7-8
Functions
7.2.3 Random Numbers (RND And RANDOMIZE)
The RND function supplies a series of random numbers to a BASIC program. This function is useful if you want
to simulate a situation that involves input of an unknown quantity, i.e., a roll of the dice. When you include the
RND function in a program, it produces a predictable sequence of numbers that are seemingly unrelated. Because
a computer always produces the same results given the same starting conditions, the RND function does not create
a truly random series of numbers. Every time you execute the same program you will receive the same series of
random numbers. Therefore, the RND function is known as a pseudorandom number generator.
The RND function has the following format:
RND
The RND function returns a random number between 0 and 1 but never returns the extremes of the range, O and 1.
(This kind of range is called an open range, or open interval.) For example:
00010 FRINT RNIDyHRNIs KNIIy KN
00020 END
READY
RUNNH
O, 17491837 O. 7324536 0, 5087399 O. 3225784
The program requests 4 random numbers so BASIC prints 4 numbers in the open range 0 to 1.
The RND function has the same starting location each time you run the same program. However, you can change
the starting point by adding the RANDOMIZE statement before the RND function in the program. Each time
BASIC executes the RANDOMIZE statement, it starts the RND function at a new unpredictable location in the
series. This location is determined by the current time of day according to the computer’s clock.
NOTE
You should not include the RANDOMIZE statement
until you have debugged your program. If you do, you
will not know if changes in the results are caused by
changes in the program or changes in the starting loca-
tion of the random number generator.
The RANDOMIZE statement has the following format:
RANDOM [[1ZE]]
Consider the following examples which contrast RND without and with RANDOMIZE.
RND without RANDOMIZE
00010 FRINT RNDyRNIy RNIN Кр
00020 ENT
READY
RUNNH
0.1924818/ 07324656 O. 6037399 O. 3325784
READY
7-9
Functions
RUNNH
0.17481897 04734636 0.6087399 O. 3225784
REALY
RUNNH
0.1948187 0.73244636 0.6087399 0.3225784
Notice every time the program without RANDOMIZE is run, RND produces the same series of values.
RND with RANDOMIZE
00005 RANDOMIZE
00010 FRINT RNDyRNDyRNDsRNI
00020 ENT
READY
RUNNH
O. 7734626 0,08921584 0.9579798 01569555
READY
RUNNH
0.6524263 0.8212112 041403020 0469475236
READY
RUNNH
0.2330611 0.4360573 0.3879883 0.3611355
Each time the program with RANDOMIZE is run, RND produces a different random series of numbers.
You can also use the RND function to produce a series of random numbers over any given open range. To produce
random numbers in the open range À to B, use the following general expression:
(B-A) * RND+A
For example, to produce 10 numbers in the open range 4 to 6, use this program
00010 FOR I = 1 TO 10
00020 FRINT (6-4) X RND+4y
00030 NEXT I
00040 ENT
READY
RUNNH
4, 389637 Ve 464927 4421748 4.645157 4.216904
4.376965 4.123446 9.426511 9.275825 4.097507
READY
Note that in line 20 of the program the general expression is used with a value of 4 for B and a value of 6 for A.
7.2.4 The MOD Function
The MOD function has the following format:
MOD%(A,B)
Or
MOD(A,B)
7-10
Functions
where:
AB represent numeric constants you supply.
MOD%(A,B) returns the integer result of A mod B, which is the remainder of A/B.
MOD(A,B) returns the real result of A mod B. which is equal to A-B*INT(A/B).
7.3 STRING FUNCTIONS
BASIC provides string functions that allow you to modify strings. With these functions you can:
1. Determine the length of a string (LEN)
2. Trim off trailing blanks from a string (TRMS)
3. Search for the position of a set of characters within a string (POS, INSTR)
4, Extract a segment from a string (SEGS,MID,LEFT$,RIGHTS$)
5. Create a string of a certain length (STRINGS)
6. Insert spaces into a string (SPACES)
7. Alter the contents of a string (EDITS)
Another group of BASIC string functions allows you to convert strings to numbers and numbers to strings. In
particular, you can convert:
1. Character to ASCII code (ASCII)
2. ASCII code to character (CHRS)
3. String representation of a number to a number (VAL)
BASIC's relational operators allow you to concatenate and compare strings (Section 2.4.4), but with string functions
you can also analyze the composition of a string. The following sections describe these functions.
The functions LEFTS, RIGHTS, MID, and SEGS all return the null string if their string argument is null. No
further range checking is done in this case.
7.3.1 Finding the Length of a String (LEN)
The LEN function returns an integer equal to the number of characters in the specified string (including trailing
blanks). The format of the LEN function is:
LEN(string)
For example:
00010 A$="ABCDEFGHIJKLMNOFAQRSTUVWXYZ*
QO0020 FRINT LEN(A$)
00030 END
READY
FKUNNH
26
7.3.2 Trimming Trailing Blanks (TRMS)
The TRMS function returns the specified string with all trailing blanks removed. The format of the TRMS function
15:
TEMS (string)
Functions
Consider the following example in which two strings are concatenated and printed, both before and after trailing «тв.
blanks have been trimmed:
00010 A$="ARCD "
00020 B$="EFG"
00030 FRINT "BEFORE TKIMMING:"sA$tE4$
00040 FRINT "AFTER TRIMMING:" >» TRMS$ CAS) +B4$
000530 END
READY
RUNNH
BEFORE TRIMMING: ARCL EFG
AFTER TRIMMINGS ABCLDEFG
7.3.3 Finding the Position of a Substring (POS, INSTR)
Use the POS or INSTR function to find the position of a group of characters, a substring, in a string. The form of
the functions are: a
POS(stringl, string?, expression)
or
INSTR(expression string! string?)
where:
stringl is the string being searched.
string? is the substring. a
expression is the character position at which BASIC starts the search.
These functions search for and return the position of the first occurrence of string? in stringl, starting with the
character position specified by expression. If the specified substring is found, the character position of the first
character of the substring is returned. If the specified substring is not found, the function returns O.
You can use these functions to map a string of characters to a corresponding integer which can then be used in
calculations. This technique is called a table look-up: the table string is stringl and the string to be mapped is
string? in the POS function. Consider the following example which translates month names to numbers. A,
00010 REM FROGRAM TO TRANSLATE MONTH NAMES TO NUMBERS
20020 T$ :: *JANFERMARAFRMAYIJUNJULAUGSEFOCTNOVOEC" !TAELE STRING
00030 FRINT “TYFE THE FIRST 3 LETTERS OF A MONTH." !INFUT THE STRING
00040 L'INFUT M$
00050 IF M8 = "" THEN 99999 IF THE STRING IS NULL THEN ENT
00060 IF LENCM$) <> 3 GOTO 120 !CHECK IF THE STRING IS 3 CHARACTERS
00070 M = (CFOSCT$yM$E7121422)/73
00080 KEM CHECK IF MONTH IS SPELLED CORRECTLY
00090 IF M <> INT(M)Y GOTO 120
00100 FREINT Ms" IS MONTH NUMBER“sM !FRINT NUMBER IF IT IS CORRECT
00110 GOTU 30
00120 FEINT "INVALID ENTRY - TRY AGAIN. "NGOTO 30
00670
799995 END
READY
7-12
hee EH = TT
di FT
Functions
RUNNH
TYFE THE FIRST 3 LETTERS OF A MONTH.
7? NOV
NOV IS MONTH NUMBER 11
TYFE THE FIRST 3 LETTERS OF A MONTH.
? LEC
LEC IS MONTH NUMBER 12
TYPE THE FIRST 3 LETTERS OF A MONTH,
? JAN
JAN IS MONTH NUMBER 1
TYFE THE FIRST 3 LETTERS OF A MONTH.
? AUD
INVALIL ENTRY - TRY AGAIN.
TYFE THE FIRST 3 LETTERS OF A MONTH.
? AUG
AUG IS MONTH NUMBER $
TYFE THE FIRST 3 LETTERS OF A MONTH.
?
There are certain possible error conditions dependent on the values of the strings and the expression.
If string], the table string, is null, an error is given.
If stringl is non-null and string? (the substring) is null, 1 is returned.
If neither 1. nor 2. holds, and if the value of the expression is greater than the length of string! or less than
1, an error is given.
(WD RI
7.3.4 Extracting a Segment from a String (SEGS)
The SEG$ function is used to extract a segment (substring) from a string. The original string remains unchanged.
The format of the SEG$ function is:
SEGS (string, expression 1, expression?)
where:
string is the string from which the segment is copied.
expression] specifies the starting character position of the segment.
expression? specifies the last character position of the segment.
For example:
00010 FRINT SEG$(*ARCIDEF"y3:5)
00020 ENT
REALY
RUNNH
CDE
If expression] equals expression2, SEG$ returns the character at expression.
Functions
There are several error conditions based on the values of the expressions and the string:
1. If expression] <= 0, an error is given.
2. If expression2 > = the length of the string, an error is given.
3. If expression] > expression2, an error is given.
By using the SEG$ function and the string concatenation operator (+), you can replace a segment of a string.
Consider the following example:
it
00010 A$ "АВСОЕЕРС"*
00020 C$ SEG$ELAS» 1172) + "XYZ"+ SEGECAS 677)
00030 FRINT C$
00040 ENT!
READY
RUNNH
AEXYZFG
Line 20 replaces the characters CDE in the string A$ with XYZ.
Examine line 20:
20 C$ : SEG$ CAS 17 2)+"XYZ" +SEGECLAFA$ 6,7)
Y ou can use similar string expressions to replace any given characters in a string.
A general formula to replace the characters in positions n through m of string AS with BS is:
C$ = SEGS(AS,1,n- 1)+B$+SEGS(AS m+1,LEN(AS))
For example, to replace the 6th through 9th characters of the string “ABCDEFGIIJK” with 123456”, enter the
following program:
00010 A$ = *“ABRCDEFGHTJR"
00020 R$ = "123456"
00030 СФ = SEG$(A$-175)+ E$ + SEGE(A$s10sLEN(AS))
00040 PRINT C$
00050 ENI
READY
RUNNH
ABRCLE 123456 JR
7.3.5 The MID Function
The MID function has the following format:
MID(string.expression 1 %,expression2%)
7-14
AE
FERRER IRL
Functions
where:
string is a string constant or string variable.
expression 1% is a positive integer designating the starting position of the substring.
expression2% is a positive integer designating the number of characters in the substring.
Starting with the character at expression1%, the MID function returns a substring with a length of expression2%.
For example:
90010 ALFHAS="ARCHEFGHIJKLMNOFQRSTUVWXYZ"
00020 FRINT MILCALFHA$ 15% »5%)
020030 FRINT
20040 FRINT MIDC"ENCYCLOFENIA" »3%»6%)
00050 END
<E AL Y
FUN
/-17.B20
Monday», May 23» 1977 16:04:41
OFQRS
CYCLOF
The following error conditions apply to the MID function:
|. If expression2 is zero, BASIC returns the null string.
2. IH expression? is less than zero, an error message is given.
3. If expression 2 is greater than zero, then
MID(string,expression 1 ,expression?2) is equivalent to
SEG Ystring,expression 1 expression 1 +expression2- 1).
7.3.6 The LEFTS and RIGHTS Functions
The LEFTS$ function has the following format:
LEFT[[S]] (string, expression)
where:
IST the dollar sign is optional but preferred.
string represents the string that contains the substring.
expression represents an integer constant denoting the character position where the copying should
stop.
7-15
Functions
BASIC returns a substring of the string you specify, from the first character in the string to the character position
you specify in the expression. For example:
00010 PRINT LEFT$C"ABCHEFG" »4%)
00020 END
READY
RUNNH
ABCD
The RIGHTS function has the following format:
RIGHT [SI] (string, expression)
where:
Is1 the dollar sign is optional but preferred.
string represents the string that contains the substring.
expression represents the character position where the copying begins.
BASIC returns a substring of the string you specify, starting with the character position in the expression up to the
last character in the string. For example:
00010 FRINT RIGHT$("ABCDREFG® »&6X)
READY
RUNNH
FG
In general, if expression is less than 1 or greater than the length of the string, an error is given. However, these two
particular cases cach return the null string:
LEFTS(string,0) and
RIGHTS(string, 1+LENGstring))
7.3.7 The STRINGS and SPACES Functions
The STRINGS function has the following format:
STRINGS(expression 1%,expression2%)
where:
expression 1% is a positive integer constant representing the length of the string you want to create.
expression 2% is a positive integer constant representing the decimal ASCIT value of the character you
want in the string.
BASIC creates a string of length expression1% with characters whose ASCII value is expression2%. For example,
to create a string consisting of 10 upper case A's, use the following:
00010 FRINT STRINGEC10%717 65%)
READY
RUNNH
AAAAAAAAAA
7-16
Functions
The SPACES function has the following format:
SPACES(expression%)
where:
expression% is an integer constant representing the number of spaces you want to add to a string.
For example:
00010 A$="ABRC"+SFACES (5%)
00020 FRINT A$+"DEF"
READY
RUNNH
ARC DEF
7.3.8 The EDITS Function
The EDITS function has the following format:
string var = EDITS(string,expression%)
where:
string var contains the new string after alterations,
string is a string constant or string variable representing the original string.
expression% is one of the integers in the following table, or a sum of the integers.
Table 7-1 EDITS Conversions
Expression% Effect
2% Discard all spaces and tabs.
4% Discard excess characters: CR, LF, FF, ESC, RUBOUT, and NULL.
8% Discard leading spaces and tabs.
16% Reduce spaces and tabs to one space.
32% Convert lower-case to upper-case.
64% Convert | to ( and | to).
128% Discard trailing spaces and tabs.
The EDITS converts the source character string according to the decima! value of the integer represented by
expression%.
Functions
For example: „ить.
00010 E$="DISCARLU ALL SFACES AND TABS."
00020 A$=EIIT$(B$»2%)
00030 FKINT B$
00040 FRINT A$
00045 FRINT
00050 C$="RETUCE SFACES ANT SPACE."
00060 D$=EDIT$(C$»716%)
00070 FRINT C$
00080 FRINT U$
90070 ENT
READY
RUN
EDIT$.R20
Mondays» May 23» 1977 16:07:58 «ту
DISCARD ALL SFACES AND TARS.
DISCARDALLSFACESANIDTARS.
REDUCE SFACES ANT TARS TO ONE SPACE.
REDUCE SFACES ANT TAES TO ONE SFACE.
You can also specify the sum of 2 or more integers in the table for a multiple effect. For example:
ARE,
00010 FRINT “TYPE THE INFUT STRING" ?NINFUT LINE A$
00020 RBR$=EDIT$(A$,80%)
00030 FRINT "B$ = ";В%
00040 ENT
READY
RUN
ELNIT$1, BO
Mondays May 23» 1977 16:08:39
ТУРЕ THE INPUT STRING ? “THIS IS MY CFFNI,"
B$ = "THIS IS MY (FFN)."
In line 20, the expression%, 80% is a combination of 16% and 64%.
74 CONVERSION FUNCTIONS
BASIC provides several string functions to do string to numeric and numeric to string conversions. ASCII and CHRS
allow you to convert a one character string to the character’s ASCII number and vice versa. These functions are
often useful in analyzing the characters in a string. The VAL and STRS functions convert a string representation of
a number to the number and vice versa. You should use them when you want to input a numeric value as a string
or to print a number without the spaces around it.
7.4.1 Character and ASCIH Code Conversions (ASCH and CHRS)
The ASCII function has the following format:
р шах
ASCII(string)
7-18
TADA uE VE RRR WF
Functions
where:
string is either a string constant, a string variable, or string expression.
The ASCII functions returns the decimal ASCII value of the first character in the string specified. For example,
ASCII (“D”) is equal to 68, the decimal ASCII value of D.
You can also use a string variable as an argument:
00010 A$="I0G"
00020 FRINT ASCIICAS)
READY
RUNNH
58
This program prints the value of the first character in AS.
The ASCII function returns an integer value.
7.4.2 Converting the ASCII Code to a Character
The CHRS Function - Use the CHRS function to create strings from ASCII values. The CHRS function returns
a 1-character string having an ASCII value of the specified expression. The format of the function is:
CHRS (expression)
Only one character is generated at a time.
The expression must be zero or greater, and arguments greater than 255 are treated modulo 256.
Consider the following example:
00010
00020
00030
00040
00050
00055
00040
00070
00080
00090
00100
00110
00120
00130
00150
00160
00190
00210
00999
READY
REM THIS FROGRAM WILL RETURN AN INFUT LETTER ANID
THE 2
REM FOLLOWING IT ALFHARETICALLY
FRINT
FRINT
INFUT
IF X$
IF X$
IF X$ =:
FOR F
IF CHR&CF
ENTER END WHEN FINISHED."
LETTER"
"ENTER A LETTER À THROUGH 2,
"LETTER" » "NEXT LETTER", "3RD
Xt
= "ENT" GOTO 7999
"A" GOTO 190
"2" GOTO 190
2 ASCIICX$) TO ALCTY(X$)+2
"Z" GOTO 150
'RETURNS ASCII VALUE OF X$
FRINT CHR$(CF)y
NEXT F
FRINT
GOTO 50
PRINT
GOTO
FRINT
"END OF ALFHARET®
30
"ENTRY IS NOT A LETTER A THROUGH Z°
GOTO 30
ENT
7-19
Functions
RUNNH
ENTER A LETTER A THROUGH Zr ENTER END WHEN FINISHED.
LETTER NEXT LETTER SRD LETTER
7? E
E F G
та
A B C
? Y
Y Z END OF ALFHARET
? 3
ENTRY IS NOT A LETTER A THROUGH Z
ENTER A LETTER A THROUGH 7, ENTER END WHEN FINISHED,
LETTER NEXT LETTER IRD LETTER
? ENT
7.4.3 Converting an Integer to RADIX-50 (RAD)
The RAD function has the following format:
RA D(expression%)
where:
expression% represents an integer constant that you supply.
The RAD function converts the integer you specify to RADIX-50. RADIX-50 is a character set similar to the ASCII
code. See the User's Guide for more information on RADIX-50.
7.4.4 The CHANGE Statement
The CHANGE statement converts a string of alphanumeric characters into their ASCII decimal values and a list of
decimal numbers into a string of alphanumeric characters (see Appendix B for the ASCII Table).
The CHANGE statement has the following format:
CHANGE list TO string variable
or
CHANGE fume variable TO list
string expression
where:
list is a numeric or integer variable representing a 1- or 2-dimensional array of decimal values.
In the first format, the CHANGE statement converts a list of integers (real numbers are truncated) into a string of
characters. The length of the string is determined by the value found in element 0 of the list. For example:
00010 FOR I = 0 TO 5
00020 READ ACI)
00030 NEXT I
00040 DATA 5965766967168» 69
00050 CHANGE A TO A$
00060 PRINT A$
00070 ENT
REALY
7-20
A.
MRE.
Functions
RUNNH
ARCDE
The CHANGE statement uses the first value in the list (5) to determine the length of the character string. It then
converts the next 5 values into their ASCII representations (see Appendix B).
In the second format, the CHANGE statement converts a string of characters into a list of integers. The length of
the string determines the value placed in element O of the list. For example:
00010 DIM A(SO)
00020 REAL A$
00030 CHANGE A$ TO A
00040 FOR I = O TO ACO)
00050 PKINT ACID»
00055 NEXT I
00060 DATA AECDEFGHIJKLMNOPORSTUVWXYZ
00070 END
READY
RUNNH
26 65 66 67 68 69 70 71 72 73 74 75 76 77 78 77 80 81
82 83 84 85 86 87 88 89 90
Notice that A(0) is equal to 26 because there arc 26 characters in the string.
7.4.5 Numbers and Their String Representation (VAL and STRS)
Two functions VAL and STRS convert numbers to their string representation and vice versa.
Consider these programs:
String Representations Numbers
00010 FRINT “25° 00010 FRINT 25
00020 FRINT "2541" 00020 FRINT 25+1
READY READY
RUNNH RUNNH
25 2
29+1 26
The program on the left prints the string representation of numbers, but the program on the right prints the
numbers themselves. Note how ““25+1” on the left is printed as it is, while the 25+1 on the right is evaluated
as 26.
The VAL function returns the number represented by the specified string. The format of the VAL function is:
VAL(string expression)
where:
may contain the digits O through 9, the letter E (for E format numbers) and the symbols
“+7 <=” and “.”, and must be a string representation of a number.
string expression
7-21
Functions
The STR$ function converts a number to its string representation. The format of the function is: A“
STRS(expression)
The STRS function returns the value of expression as it would have been printed by a PRINT statement, but
without a leading or trailing space.
Consider the following example:
00005 FRINT "FKOGRAM TO CALCULATE 5% INTEREST"
00010 FRINT "TYFE IN AMOUNT";
00020 INFUT M$
O0030 IF POSCM$, "$" ,1)-:1 THEN 1000
00040 A$=SEG$SCMS$ » 2,LENCM$ ) )
00050 M = VALLAS)
00060 I = .05% X M
00070 1$ STRECI) an.
00080 1% SEGS$CIS515 24FOSCISy "+" »1)) a
00090 FRINT "S% INTEREST OF ":M%$s
01000 FRINT " IS $"51I$
79777 END
HH
READY
RUNNH
FROGRAM TO CALCULATE 5% INTEREST
TYFE IN AMOUNT ? $100.00
34 INTEREST OF $100.00 IS $5 «и
7.5 DATE AND TIME FUNCTIONS
The following table describes the various date and time functions (24 hour clock) available in BASIC.
Table 7-2 The Date and Time Functions
Function Meaning Example
CLKS returns the current time of day as an 8-character stringof | 10 FRINT CLKS$ а
the form hh:mm:ss. RUNNH |
16:43:53
DATS returns the current date as dd-mmm-yy. 10 FRINT DATS
RUNNH
17- Jun-77
DATES(0%) | returns the current date in the form mm/dd/yy. 10 FRINT TATESCOZ)
RUNNH
6/17/77
DATES(n%) | returns a specific day you specify with the integer con- 10 FRINT LATE$S(12?6)
stant supplied for n%. The formula for n% is n% = the 20 PRINT DATES (5168)
day of the year + (the number of years since 1970* 1000). | EUNNH
If you only specify the day of the year, the date will 65-Maw-70
be 1970, unless n%=0. 1l6-Jun-76
E {I Е aug г
Functions
Table 7-2 (Cont.) The Date and Time Functions
Function Meaning Example
TIMES(n%) returns a string corresponding to the time of day n% minutes | 10 FRINT TIMES (1)
before midnight, unless n%=0. 20 FRINT TIME$(1440)
30 PRINT TIME$(721)
KUNNH
23:57
00:00
11:57
TIMES(0%) returns the current time of day as a character string of 10 FRINT TIMES (OZ)
the form hh:mm. RUNNH
16:45
TIME(D) returns the clocktime, in seconds, since midnight, as a 10 FRINT TIMECO)
floating-point number. КЦОНМН
50349
TIME(1%) returns the CPU time used by the current job, in 10 FRINT TIMECI1Z)
tenths of seconds. RUNNH
28
TIML(2%) returns the connect time (during which you are 10 FRINY TIME (2X
logged-in) for the current job, in minutes. RUNNE
27
7.6 USER-DEFINED FUNCTIONS — THE DEF STATEMENT
In some programs you may want to execute the same sequence of statements in several places. You can define a
sequence of operations as a user-defined function and usc this function like you use the functions BASIC provides,
such as SIN and SEGS. There are two ways of defining functions:
1. single-line DEF statement
2. multi-line DEF statement
7.6.1 Single-Line DEF
Single-line DEFs have a function name consisting of the letters FN followed by 1 to 29 letters, digits, or periods
optionally followed by a % or a S. If the function name ends in a %, then it returns an integer. If the function name
ends in a $, then it returns a string. If the function name does not end in either a % or a $, then it returns a floating
point number. Therefore, the function name can have a total of 33 characters.
Legal User-Defined Illegal User-Defined
Function Names Function Names
FN МЕ!
FNC% FN A2
FNR.B$ FNAZS
The format of the single-line DEF statement is:
DEF FNa [1 b2,b3,.. bn) ]] =expression
Functions
where: Ay.
a is 1 to 29 letters, digits, or periods followed by an optional percent sign (%) or dollar
sign ($) to represent an integer or string value.
(b1,b2,b3,...bn) These can be integer, floating point, or string variables.
expression is evaluated every time the function is used. It may contain any of the dummy variables
or any other variables in the program.
Ensure that the expression is the same data type, string or numeric, as indicated by the function name. If the
expression is floating point and the function name is integer or vice versa, then the expression is converted to the
type specified by the function name.
After the function has been defined, it can be called, or evaluated. The format for calling the function is:
%
FNa $ (expression 1 [[expression2, Ca ‚expression5 ]])
where the number of expressions must be the same as the number of dummy variables in the DEF statement.
When the function is evaluated, BASIC substitutes the values for the dummy variables in the DEF statement and
then evaluates the expression and returns the result.
Consider the following two programs:
Program #1 Program #2
A
00010 DEF FNS(A) = ATA 00010 DEF FNSCX) = XX
00020 FOR I = 1 TOS 00020 FOR I = 1 TO 5
00030 FRINT I»FNSCTI) 00030 FRINT IsFNSCI)
00040 NEXT I 00040 NEXT I
00050 ENT 00050 END
READY READY
RUNNH RUNNH
1 1 1 1 —
2 4 2 4
3 27 3 27
4 256 4 296
3 3125 = 3125
These two programs produce the same output. The actual names of the arguments in the DEF statement have no
significance; they are strictly dummy variables. But the data types of the variables are significant. If the DEF state-
ment specifies a string variable, then the corresponding argument must be a string. If the DEF statement specifics
a numeric variable, then the corresponding argument must be numeric. BASIC converts, as necessary, a numeric
argument to the type (floating point or integer) specified by the variable in the DEF statement.
The defining expression can contain any constants, variables, BASIC-supplied function. or any other user-defined
function except the function you are defining. For example:
10 DEF FNA(X) = X"2+3%X+4
20 DEF FNE(X) = FNACX)/2 + FNA(X)
30 DEF FNCCX) = SQRCX+44)=1 E
7-24
Functions
You can include any variables in the defining expression. If the expression contains variables that are not in the
dummy variable list, they are not dummy variables. That is, when the user-defined function is evaluated, the vari-
ables have the value currently assigned to them.
Consider the following example:
00010 DEF FNBCA,B)=AFX"2
00020 X = 1 ASSIGN VALUE TO X
00030 FRINT FNE(14,87) 'EVALUATE FUNCTION
00040 X = 2 ! CHANGE VALUE OF X
00050 FRINT FNEC25» 32)
99999END
READY
RUNNH
15
27
Note that in this example the second argument (the dummy variable B and the actual argument 87) is unused.
The expression does not have to contain any of the variables. For example:
00010 DEF FNACX) = 4+2 1NOTE THIS FUNCTION ALWAYS RETURNS
00020 LET R = FNACLO)+1 A VALUE OF 6 NO MATTER WHAT
00030 FRINT RK 'THE VALUE OF THE ARGUMENT IS.
00040 ENT
READY
RUNNH
7
Consider the following example:
00001 REM MODULUS ARITHMETIC FROGRAM
00005 REM FIND X MOD M
00010 DEF FNM(XsM)=X-MKINT(X/M)
00020 REM FIND A+k MOD M
00025 DEF FNACAsBsM)=FNM(A+RsM)
00030 REM FIND AXE MOD M
00035 DEF FNECA:»ErM)=FNMCAXER:M)
090045 FRINT
00050 FRINT "ADDITION AND MULTIFLICATION TABLES MOD M"
00055 FRINT "GIVE ME AN M"ININFUT M
00060 FEINTNFRINT *ADDITION TABLES МОД УМ
00065 GOSUEB 800
09070 FOR IT = O TO M-1
00075 FRINT Is" "5
02080 FOR J = © TO M-1
00035 FRINT FNACI» JyM?:
00090 NEXT JNFRINTNNEXT 1
QO100 FRINTNFRINT
092110 FRINT "MULTIPLICATION TARLES МОД" М
00120 GOSUE 800
Continued on next page
00130
00140
00150
00160
00170
00180
00800
00810
00820
00830
Functions
FOR I = 0 TO M-1
FRINT Ty" "5
FOR J = O TO M-1
FRINT FNR(Iy JrM)
NEXT J\PRINT\NEXT I
GOTO 99999
REM SUBROUTINE FOLLOWS
PRINTNERINT TAR(A)s
FOR I = O TO M-1
FRINT IsNNEXT INFRINT
00840 FOR I = 1 TO 3XM44
00850 PRINT "—"#\NEXT INFRINT
00860 RETURN
99999 ENT
RUNNH
ALLITIÓON ANT
GIVE ME AN M 7 7
ALLITION TABLES MOD 7
0 1 2 3 4 5 4
о O 1 2 3 4 5 6
1 1 2 3 4 5 6 0
2 2 3 4 5 6 0 1
3 3 4 5 6 0 1 2
4 à 5 6 0 1 2 3
+ > 6 0 1 2 3 4
6 6 0 1 2 3 4 5
MULTIFLICATION TARLES MOD 7
O 1 2 3 4 5 6
О O 0 0 0 0 O 0
1 0 1 2 3 4 5 6
2 O 2 4 6 1 35
3 O 3 6 2 5 1 4
4 O 4 1 5 2 6 3
oO 5 SA E 4 2
6 O 6 5 4 3 2 1
MULTIFLICATION TABLES
7.6.2 Multi-Line Function Definitions
Some calculations may require more than a one line arithmetic expression as in the single line DEF statement.
BASIC's multi-line DEF statement allows you more tlexibility in defining complicated function values.
The multi-line DEF statement has the following format:
DEF FNa [J(b1.62.b3. NM) [let 2.03. . ]
7-26
Functions
where:
a represents 1 to 29 letters, digits, or periods followed by an optional percent sign (%) or
dollar sign ($) to represent an integer or string function value.
(b1.b2.b3,...) represents the dummy argument list.
cl,e2,e3,... represents a list of variables local to the function definition. This list is optional.
Single and multi-line DEF statements are similar in format. However, multi-line DEFs do not have the cqual sign
expression on the first line. Instead, the function name must appear in a defining position (such as an assignment
statement) within the function definition. Otherwise. the function value will be set to 0 or null string.
Multi-line functions can have from zero to any number of parameters.
The variables specified in the function definition (or DEF statement) can be used only within the body of the func-
tion. Any variable referred to in the definition that is not a local variable, refers to the variable of the same name
outside the body of the DEF. This means that variables in the main program are global as opposed to variables
specified in the DEF statement.
The FNEND statement signals the physical and logical end of the function definition. The FNEND statement has the
following format:
FNEND
When BASIC executes the FNEND statement, it returns the function value to the calling statement.
You can also end a function definition with the FNEXIT statement. FNEXIT has the following format:
FNEXIT
The FNEXIT statement is equivalent to a GOTO n where n is the line number of the FNEND for the current multi-
line DET. The FNEXIT statement is legal only inside a multi-line DEF.
Most statements can be used within the function definition (between the DEF and FNEND statements). However,
multi-line DEFs are local to the main program or subprogram (Chapter 11) in which they are contained. No transters
are allowed into or out of a multi-line DEF. If you attempt to transfer into the body of a multi-line DEF. BASIC
will execute the next statement following the FNEND statement and issue a warning message.
DATA statements are global throughout the program. Therefore. even though they may reside within a function
definition, the main program can still access them and vice versa. DIM statements within a function are local to the
function definition if they apply only to local variables.
You can place a multi-line DEF anywhere in a program. The entire body of the multi-line DEF, as well as the single-
line DEF, does not produce code in straight-line execution until it is called.
You call à function into action by using its name in a statement expression. With the name. you must include the
actual argument list, one with the same number of arguments as in the DEF statement. The actual arguments can be
constants, variables, array elements, or expressions. They must be the same data type as the dummy arguments they
replace. (Whole arrays are not legal arguments.)
BASIC uses the actual arguments within the function to define the function value. Using dummy arguments in the
multi-line DEF statement allows you to use the function definition many times with a different set of actual
arguments.
7-27
Functions
The following example illustrates the use of the multi-line DEI statement:
00010 DEF FNXZ(AB)»C
00020 IF AB THEN C = 3.4
00030 REM C WAS INITIALIZED TO ZERO
00040 FNXX = AXB+C
00050 FNENT
00060 PRINT FNXZC3.172.3)
00070 END
READY
RUNNH
10
BASIC ignores the function definition, lines 10 through 50, and begins execution at linc 60. The PRINT statement
calls the function with actual arguments to be substituted in the definition. A is larger than B; therefore, C is set
equal to 3.4. At linc 40, BASIC calculates the value to be 10.53. Because the function name is integer (%), the value
returned to FNX% is 10.
7.6.2.1 Multi-Line DEF* — With the standard multi-line DEF argument passing mechanism, you cannot transfer
into and outof a function definition retaining global values for variables. There is another method of writing multi-
line DEFs that allows you to transfer from a function with global variables. This method also uses the DEF state-
ment. however, an asterisk (*) has been added to the keyword.
DEF* FNa [[b1.652,b3...J)]]. [e1,c2,c3, .. J]
The asterisks (*) tells BASIC that the BASIC-PLUS compatible form of the function definition is being used. This
form allows you to include the GOTO, ON-GOTO, GOSUB, and ON-GOSUB statements within the body of the
function to transfer outside the function definition. The variables you define during execution of the function are
global while the function is still open (before BASIC reaches the FNEND statement).
The following example illustrates the DEF* method of multi-line DEF s:
00010
00020
00030
00040
00050
00060
900070
00080
00070
00100
00110
DEFX FNXCA)
IF A<3 GOTO 40
LET A=6\GOTO 100
FNEND
LET A=3
LET C=FNX(4)
LET D=FNX(2)
FRINT A
STOF
FRINT A
GOTO 40
—
REALY
RUNNH
6
3
STOF at line 00090 of MAIN FROGRAM
Notice that the values printed for A are 6 and 3 rather than 3 and 3. Line 60 calls the function FNX with an actual
argument of 4 to replace the dummy argument A. A is greater than 3 (condition tested on line 20); therefore, À 1s
Functions
assigned a new value of 6 (line 30). Then BASIC transfers out of the function definition to line 100 and prints the
current value of A within the function, 6. Exccution continues at the next line following the function call.
The second function call (on line 70) sends BASIC back to the function definition. This time, because A is less
than 3 (2), BASIC transfers to the FNEND statement. Once the function ends, the value of A is no longer global.
BASIC prints the value of A outside the function, 3, and then stops.
You can define multi-line functions either the standard (DEF) or BASIC-PLUS Compatible (DEF*) way." However,
all DEFs in the same program must be written the same way throughout. Functions defined either way must have
argument lists agreeing in both data type and number.
NOTE
Although transfers into and out of a multi-line DEF*
(BASIC-PLUS compatible) are permitted. random trans-
fers may produce unpredictable results.
‘Version 1 of BASIC-PLUS-2 on RSTS/E supports BASIC-PLUS compatible DEF* only for compatibility with
RSTS/E BASIC-PLUS. Version 2 will support both.
7-29
A >,
A A pued FOR E 327
TL RE ИА
CHAPTER 8
ARRAYS
8.1 DIMENSIONING AN ARRAY
Operations on arrays occur frequently: therefore, BASIC provides a special set of statements for array computations.
These statements cach contain the keyword MAT. The MAT statements apply to both lists and matrices, except
where noted in the text. If you specify an array without subscripts (MAT A), the default is 2 dimensions.
Although every list has an clement 0, and every matrix has a row 0 and a column 0, the MAT statements ignore these.
In a BASIC program, you reserve storage space in one of two ways:
I. Explicitly - with a DIM statement (2.6.1)
2. Implicitly - including an array in a program without the DIM statement
The MAT statements allow you to alter the number of elements in each row and column of an array as long as the
total number of elements does not exceed the number previously defined. Changing the size of an array in this way
is called redimensioning an array.
In addition to this capability, you can:
Perform arithmetic operations
Input array elements or entire arrays from the terminal
Read array elements from a DATA statement
Print array elements or entire arrays
X LD N —
8.2 INITIALIZING AN ARRAY
The MAT statements allow you to assign values to individual array elements. The values can be set to all O’s, all 1’s,
or O's with 1's along the main diagonal.
This statement has the following format:
MAT name=value [[ (DIM 1,[DIM2] ) |
where:
name is an array dimensioned cither implicitly or explicitly.
(DIM1,DIM2) are new dimensions for the array. These dimensions are optional.
value is one of the following:
VALUE MEANING
ZER sets the value of all elements in the array to 0. This condition is truc of all arrays (except for
those in a virtual array, MAP, or COMMON area, Scctions 9.3, 10.1.4, and 11.2.1 respec-
tively) when first created. (Does not set row 0 and column 0.)
CON sets the value of all elements in the array to 1. (Does not set row 0 or column 0.)
Arrays
IDN sets the value of all elements in the array to 0 except for those on the diagonal, which are mt
set to 1. This is called an identity matrix. The matrix must be square. (Does not set row О
or column 0.)
NULS sets the value of all elements in a string array to null string. (Does not set row 0 or
column 0.)
The first three values apply to numeric and integer arrays, and the fourth applies to string arrays.
If you do not specify new dimensions with the (DIM 1,DIM2) option, the existing dimensions remain unchanged.
Consider the following examples:
00010 TM AC1O0,10), BC1D)» CC20420)
00020 MAT A = ZER !ISETS ALL ELEMENTS OF A = O
00030 MAT В = CON(10) !ISETS ALL ELEMENTS OF E = 1 AND REDIMENSIONS
00040 MAT C = IINC10y10) CREATES AN IDENTITY MATRIX 10X10 mi
00050 MAT FRINT A?
00060 MAT FRINT Ez
00070 MAT RINT (3
==
09080 ENT
REALY
KUNRH
9 0 0 0 0 0 O O 0 0
oO 0 0 0 OO D O О 0
9 0 0 O 0 O O Y O O0 зи
0 9 0 Oo 0 Y 0 D о 0
O O 0 9 O 0 0 O 0 0
O O 0 0 0 0 O 0 О Q
oO 0 0 9 Oo O 0 0 0 Y
O 0 0 0 0 O O oO O Y
O O O 0 0 0 O Оо O Y
O 0 0 0 0 0 0 O0 0 0
pt
pb
++
+
=
pb
pb
—
>
Pr
à
1 0 0 0 0 0 0 O D ©
O 1 0 0 0 0 O O 0 D
O 0 10 0 0 O UU О ©
O O 010 0 oO 9 Y 0
O 0 0 0 1 0 O 0 оО Y
O O 0 O O 1 _O 9 0 0
oO 0 O O O O 1 0 O 0
O 0 0 0 0 0 0 1 0 O
O 0 O O 0 € O O 1 о
O 0 0 0 0 0 0 0 О 1
To create an identity matrix with IDN, the array must be a square matrix.
8-2
> EU
|
Arrays
8.3 MATRIX OPERATIONS
With the MAT statement, you can perform the following operations with arrays:
I. Assignment
2. Addition
3. Subtraction
4. Multiplication
5. Transposition
6. Inversion
Each MAT operation statement begins with the keyword MAT followed by an expression to be evaluated. You can
assign the value of one array to another as in the following example:
10 MAT A=R
This statement sets each entry of array A equal to corresponding entry of array B. A is redimensioned to the size of
array B.
You can also add and subtract arrays:
10 MAT A=E+C
20 MAT A=E-C
The first statement assigns the sum of arrays B and € to array A. The second statement assigns the difference
between arrays B and C to array A. B and C can be cither lists or matrices; however, they both must have identical
dimensions.
The following statement multiplies two arrays:
10 MAT A=BXC
This statement causes array A to be set equal to the product of arrays B and C. A, B. and C must all be
2-dimensional arrays, and the number of columns in array B must be equal to the number of rows in C. BASIC
redimensions A to the number of rows in B and the number of columns in C.
The following statements are illegal in BASIC:
10 MAT A=AXA
20 MAT A=AXD
30 MAT A=RXA
Components of array A are needed for the calculation of the expressions after they have already been destroyed.
These illegal statements cause BASIC to print an error message.
However, this statement
10 MAT C=AXA
is legal if A is a square matrix.
You can also perform scalar multiplication of a matrix:
10 MAT A=(K) XE
8-3
Arrays
where cach entry in array B is multiplied by the value of K. K is any arithmetic expression and must be enclosed in
parentheses.
Array A is redimensioned to array B provided enough space is reserved.
8.4 ARRAY INPUT AND OUTPUT
Elements in an array can be accessed with the following statements:
|, MAT INPUT
2. MAT PRINT
3. MAT READ
8.4.1 MAT INPUT Statement
The MAT INPUT statement enters values for cach element of a list or matrix. The MAT INPUT statement has the
following format:
MAT INPUT array(s)
where:
array can be onc or several lists or matrices separated by commas.
The keyword MAT INPUT must have a space between the two words.
BASIC reads data from the terminal as with the normal input statement. The question mark (?) signals that BASIC
is ready to accept input.
Unlike the INPUT statement, the MAT INPUT statement allows you to enter a variable number of values into an
array. You need not supply the same number of elements requested in the MAT INPUT statement; you can include
fewer elements but not morc than requested.
You can also continue typing data on more than one line with the continuation character, the ampersand (8%). You
terminate the input stream with a line terminator.
The values you type are entered into successive array clements in row order starting with the first clement. If you
type a variable number of values, you can determine the number of rows and columns you filled with the two
variables NUM and NUM”.
If the array is a list, NUM is set equal to the number of elements you enter. If the array is a matrix, NUM is the
number of rows you enter and NUM? is the number of elements in the last row. By printing these variables, you
can see the size of the array.
If you specify more than one array in the MAT INPUT statement, only the last one can have a variable number of
elements. You can also redimension an array by specifying a new size in the MAT INPUT statement.
The following is an example of the MAT INPUT statement:
00010 TIM ACT)
00020 MAT INFUT À
ВАО
NUNAH
Ф 179290357470
8-4
SE.
HERE YEE Bey URC
Arrays
You cannot include a string constant within the MAT INPUT statement as you can in the INPUT statement. You
can print the results of your input with the MAT PRINT statement,
8.4.2 MAT PRINT Statement
The MAT PRINT statement has the following format:
MAT PRINT array(s)
where:
array(s) without subscripts causes the printing of the entire array. Subscripted array causes the maximum
size of the array (defined by the subscript) to be printed. (It does not redimension the array.)
MAT PRINT must have a space between the two words.
If you follow the array with a semicolon(;), the data values print in a packed fashion. If you follow the array with
a comma (,), the data values print across the line with one value per print zone. If neither character follows the
array, cach clement prints on a separate line. All but the last array in a list must have a comma or a semicolon,
separating it from the next array on the list.
Each row of a matrix starts printing on a new line. You can print one-dimensional arrays (lists) in cither row or
column format. For example:
09010 DIM ACS5
00020 MAT INFUT A
09030 MAT FRINT A
00040 MAT FRINT A
00050 MAT FRINT A
9060 END
READY
RUNNH
5
о
0
0
0
5 о 0 0 о
5 0 0 0 Y
Notice that only one valuc was typed in responsc to the MAT INPUT, The remaining elements retain a value of 0.
When you specify more than one array, BASIC begins printing cach array starting on a new line. (BASIC never
prints rew 0 and column 0 when using the MAT PRINT statement.)
8.4.3 MAT READ Statement
The MAT READ statement reads the values into elements of a 1- or 2-dimensional array from DATA statements.
The MAT READ statement has the following format:
MAT READ array(s)
8-5
Arrays
where: «о,
array(s) without subscripts indicates that the entire array is read. Arrays with subscripts cause the array to
be redimensioned.
MAT READ must have a space between the two words.
The maximum size of the array cannot exceed the previous dimensions.
BASIC reads the values from DATA statements in the same manner as the READ statement. (Row 0 and column 0
are not affected.) The DATA statement must contain enough data. You cannot input a variable number of elements.
Consider the following example:
00010 DIM В(2,2), С(2,2)
00020 MAT READ E
00030 MAT READ C
00040 MAT A=R4(C
00050 MAT PRINT А;
00060 MAT FRINT Hs
00070 MAT FRINT Cs
00080 LATA 172»3v475677,9
READY
RUNNH
& 8
10 17 „=
1 2
3 4
> ó
7 8
8.4.4 MAT Functions TRN, INV, DET
The TRN function has the following format:
MAT array=TRN(array)
The function interchanges the dimensions of an array and renames it. A matrix with m rows and n columns will
be renamed and redimensioned to n rows and m columns. For example:
00010 DIM EC3»5)
00020 MAT READ E
00030 MAT A=TKNCH)
00040 DATA 172737475
00050 DATA 671778797710
00060 DATA 11,12513514,15
00070 MAT FRINT Hs
00080 MAT FRINT А;
READY a
8-6
Arrays
RUNNH
1 2 3 4:
é 7 8 9 10
11 12 13 14 15
1 6 11
2 7 12
3 8 13
4 9 14
> 10 15
Note that MAT A=TRN(A) is illegal.
If you want to find the determinant of a matrix, you must first find the inverse. Usc the INV function for this
purpose. The INV function is used as in the following example:
10 MAT A=INV(R)
The INV function allows matrix À to be the inverse of matrix B. (B must be a square matrix.) BASIC redimensions
À to be the same size as B.
NOTE
Although matrix inversion does not operate on the cle-
ments of row 0 and column 0 of a matrix, BASIC does
store intermediate results in these elements of an
inverse.
Therefore, the values of the elements in row 0 and
column 0 of an inverse matrix may change.
The function DET is available after the inversion. You can then use DET as a variable set equal to the value of the
determinant of B. Consequently, you can obtain the determinant of a matrix by inverting the matrix and then
noting the value of DET. For example:
i
INV (XO DLE DET
02 THEN FRINT "RELATIONSHIF TRUE"
00010 MAT A
00020 MAT E
00030 IF Di
00040 FRINT D1
i
NOTE
If you specify a list rather than a matrix, BASIC cannot
complete the inversion. Therefore, DET is set equal to
0.
8-7
ME —
TR RUNES eC
CHAPTER 9
WORKING WITH FILES
9.1 FILES
There are threc types of files in BASIC:
1. Terminal-Format files
2. Virtual Array files
3. Record files
To distinguish one file from another, you must label it with a file specification. The file specification usually con-
tains the device name, the file name, and the file type. Because each system has its own constraints, refer to your
User's Guide for details.
The following sections describe terminal-format and virtual array files. Record files arc described in Chapter 10.
9.2 TERMINAL-FORMAT FILES
A terminal-format file is a collection of ASCII characters stored in lines of various lengths. The end of a line is
determined by a line terminator, i.c., linc feed. BASIC stores these ASCII characters, including spaces and line
terminators, exactly as they would appear on the terminal; hence the name terminal-format file.
Terminal-format files are sequential access files. Sequential access files are those files that contain information that
must be read or written one item after another from the beginning of the file. This means that you cannot retrieve
an item from the file without first retrieving all the items preceding it.
BASIC has a file pointer that kecps track of where you are in the file. To add new items to an existing file without
overwriting current information, you must read the entire file. This action places the file pointer at the end of the
file where you can add data. Section 9.2.1 describes your options.
9.2.1 Opening Terminal-Format Files
Before you can access a terminal-format file, you must open it. The OPEN statement allows you to open a new file,
or an existing file, and associate the file with a file number.
The OPEN statement has the following format:
OPEN filename exp [For dou UT y AS [еше] [+] expression
OUTPUT
‚ACCESS | READ ALLOW ot
WRITE | READ
MODIFY
SCRATCH
APPEND
[[.INVALID line no. ]] - [[, LOCKED line no. ]
9-1
Working with Files
where:
filename exp is a file specification.
FOR INPUT specifies an existing file.
FOR OUTPUT specifies creation of a new file. If a file exists with the same file specification, the existing
file is superseded.
expression is the file number. It can be any numeric or integer expression with a value between | and
the maximum allowed by your system.
FOR INPUT and FOR OUTPUT are both optional. If you omit this part of the statement from the OPEN state-
ment, BASIC checks first for an existing file (FOR INPUT). If no file exists with the name specified, BASIC opens
for the creation of a new file (FOR OUTPUT).
The ACCESS, ALLOW, INVALID, and LOCKED clauses arc optional attributes that you can specify (in any order)
when opening a file. The ACCESS clause defines both the position of the file pointer and the operations you can
perform:
READ The file pointer is at the beginning of the file. You can only read the file.
WRITE The file pointer is at the beginning of the file. You can only add data to the file.
MODIF Y This is the default. The file pointer is at the beginning of the file. You can read and write
to the file.
SCRATCH The file pointer is at the beginning of the file. You have complete access to the file; read,
write, and truncate the file.
APPEND The file pointer is at the end of the file. You can only write to the file at this point.
The ALLOW clause defines what you allow other users to do to the file while you are using it.
NONE is the default. No onc can read or write data while you have the file open.
READ allows others to read the file while you arc using it.
Note that you cannot specify an ALLOW clause if you ACCESS SCRATCH.
The INVALID clause specifies the line number of an error-handling routine. This routine takes effect if the OPEN
fails, i.e., you specified an illegal file specification. If you do not include INVALID, BASIC takes over the error
handling.
The LOCKED clause also specifies the line number of an error-handling routine. This routine takes effect if the file
is locked because another user specified ALLOW NONE. If you do not specify LOCKED, BASIC takes over the
error handling.
Table 9-1 describes the results of specifying the keywords in the OPEN statement.
TE SETS
Working with Files
TABLE 9-1 OPEN Statement
Access Initial File Position I/O Operation
READ beginning read only
WRITE beginning write only
MODIFY beginning read or write
SCRATCH beginning read, Write, truncate
APPEND end write
Consider the following example:
O0010 OFEN "DLATA1" FOR INFUT AS FILE 1» ACCESS APFEND
00015 N=5
00020 OFEN "MONEY" FOR QUTFUT AS FILE N
00030 END
Line 10 opens an existing file at the end and associates it with file 1. Line 20 creates a new file specified by MONEY
and associates it with file 5. If a file named MONEY already cxists, BASIC supersedes it with the new request. When
you open a file and associate a file number to it, you usc that number when referencing the file, e.g., DATAL is #1,
MONEY is #5.
To save files for future use, you must close them. Sec Section 9.2.2.
9.2.2 Closing Terminal-Format Files
All programs that open files should close them before terminating execution. Most systems do not save files unless
they are closed. An existing file with the same file specification may not be superseded until the new file is closed.
Refer to your User's Guide te determine what happens on your system.
BASIC closes all files:
1. when exccuting a CHAIN statement Section 11.2
2. when executing an END statement
3. after executing the highest numbered line in the program.
Note that BASIC does not close files after executing a STOP statement.
A more specific way to close files is with the CLOSE statement. The CLOSE statement closes the files you specify
and disassociates them from their file numbers. After you close a file, you cannot access it without rcopening it.
Unlike the first three methods, the CLOSE statement allows you to specify which files you want closed.
The CLOSE statement has the following format:
CLOSE L [+] expression(s) []
where:
expression(s) specifies one or more file numbers, separated by commas.
If no expressions are specified, BASIC closes all open files.
9-3
Working with Files
The following examples illustrate the CLOSE statement: —.
00010 CLOSE #1 !'CLOSES FILE ASSOCIATED WITH FILE 1
00020 В=4
00030 CLOSE 2,Re6+1 ICLOSES FILE NUMBERS 2,417
00040 CLOSE !ICLOSES ALL FILES
9.2.3 Reading Data From A Terminal-Format File
The INPUT £ statement reads data stored in a terminal-format file and assigns a value to each variable listed.
The INPUT # statement has the following format:
INPUT # expression, variable(s)
where:
expression is the file number of the terminal-format file. If the value of the expression is zero,
data arc input from the terminal rather than a file. The comma is required. a
variable(s) is one or more variable names separated with commas.
The INPUT # statement acts very much as the INPUT statement described in Section 3.1.1. However, the INPUT #
statement requests data from a terminal-format file rather than from you. In order to INPUT # from a file. you
must OPEN for ACCESS READ, MODIFY, or SCRATCIL If you OPEN with ACCESS APPEND, you must
RESTORE +# the file before you can read it. Sec Section 9.2.5.
Consider the following example:
00010 OFEN "NAMES" AS FILE #2, ACCESS REAL 'OFENS EXISTING FILE
00020 INFUT #2>AÂ$;E !REALS A STRING AND A NUMERIC FROM FILE
00030 PRINT A$sE !FRINTS RESULTS ON TERMINAL
00040 GOTO 20
00050 END
READY
RUNNH
SARAH 137 e. | —
TONY 117,45
LORRAINE 200
JAY 89
T 11 End of file found on INFUT at Lire 00020 of MAIN PROGRAM
[f this example had been written with an INPUT statement, BASIC would have stopped and printed a question mark
to request data from you. Instead, the INPUT # read the data into the program from a previously stored terminal-
format file.
BASIC starts reading data from the beginning of the file. If the linc of data in the file contains more data than there
are variables in the INPUT # statement, BASIC ignores the excess data. However, if there is not enough data on the
line, BASIC looks for more data on the next line of the file. If you try to INPUT # from a new file or a file OPENED
with cither ACCESS APPEND or ACCESS WRITE, BASIC prints an error message.
A
9-4
Working with Files
9.2.3.1 The INPUT LINE # and LINPUT # Statements The INPUT LINE # and LINPUT £ statements have
the following format:
INPUT LINE + expression, variable (s)
LINPUT # expression, variable(s)
where:
expression is the file number of the file where the data resides. If the number is zero, BASIC inputs
data from the terminal. The comma is required.
variable(s) onc or more string variables separated by commas.
The INPUT LINE # statement reads a string of characters from a terminal-format file into each respective string
variable in the list. All characters on the input line including commas, quotation marks, and the line terminator are
assigned to the string variable.
The LINPUT # statement also reads an entire line of data into the program: however, it does not include the line
terminator,
The following example illustrates both statements:
00010 OFEN "TEST" AS #1
00020 FRINT Ely "LATA, FOR A FROGRAM."
00030 FRINT #1; "SECOND LINE"
00035 RESTORE #1
00040 INFUT LINE #1, A$
00050 FRINT A$
00060 LINPUT #1; A$
00070 FRINT A$
00075 CLOSE #1
00080 END
READY
RUNNH
DATA» FOR A FROGRAM.
SECOND LINE
Linc 10 opens a file named TEST and associates it with FILE 1. Lines 20 and 30 write data into the file. The
INPUT LINE # statement requests a line of data from the program. BASIC reads the entire line. including the line
terminator, into the program. If an INPUT # statement had been used, BASIC would have read only “DATA” into
the string variable AS.
The LINPUT # statement on line 60 requests another line of data. This time BASIC reads all characters into the
program except for the line terminator.
9.2.4 Writing To A Terminal-Format File
The PRINT # statement writes data into the specified terminal-format file. The PRINT # statement has the follow-
ing formar:
PRINT # expression, list
9-5
Working with Files
where: A
expression is the file number of the terminal-format file. If the value of the expression is zero, BASIC
prints the data on the terminal.
list contains the items you want printed. The items can be any numeric, integer, or string
expressions. Separate the items with commas or semicolons. The resulting ouptut format
is the same as the simple PRINT statement.
If there are no items in the list, BASIC prints a blank line to the file. To PRINT # to a file, you must OPEN with
ACCESS WRITE, MODIFY, SCRATCH or APPEND.
The PRINT # expression USING statement prints formatted data to a file (see Section 4.4).
Consider the following example that creates a terminal-format file from data stored in DATA statements:
00010 OFEN "NAMES" FOR QUTFUT AS FILE 1
00020 READ A$» A IREADN DATA FROM FROGRAM a
00030 IF A$="" THEN 100 !CHECK FOR LAST ITEM
00040 FRINT #1s A$s"» "5A !FRINT TWO ITEMS
00050 GOTO 20
00060 DATA "SARAH" 187.2 "TONY" y117.45
00070 LATA "LORRAINE" » 200," JAY" У ВЯ
00080 ПАТА ""rO
00090 CLOSE #1
00100 END
After you run this program, the file NAMES contains the following: „т
SARAH 187.2
TONY 117.45
LORRAINE 200
JAY 89
9.2.5 Restoring A Terminal-Format File
The RESTORE # statement resets the specified terminal-format file to its beginning from the current position of the
file. т.
The RESTORE # statement has the following format:
RESTORE # expression
where:
expression is the file number of the terminal-format file.
After printing into a file, you can bring the file pointer back to the beginning with the RESTORE # statement.
A
9-6
Working with Files
00010 OPEN "NEW" AS E 1
00020 FRINT Ely EL" y9"5309",9"795
00030 RESTORE #1
00040 INFUT f1rAhÂ;BsC
00050 FRINT AsBsC
00060 CLOSE #1
00070 END
READY
RUNNH
bb 80 9
9.2.6 Checking for the End ofa Terminal-Format File
The IFEND # statement has the following format:
IFEND # expression - THEN statement
| yO {ne number
IFEND # expression GOTO line number
where:
expression a ) is the file number associated with the file.
With the IFEND 4 statement you check for the end of the file. If the file pointer is at the end, you can transfer
control to another r line of the program or execute a statement.
9.2.7 The IFMORE Statement
The IFMORE statement has the e following. format:
IFMORE #exp pression THEN statement | фонт
“line number line number
Or
[FMORE expression GOTO line number
where: ВЕ
file exp N ‘ is a file number of a terminal format file,
“statement isany legal BÄSIC statement except DATA, DEF, DIM, END, FNEND, IMAGE, NEXT,
A REM, SUB, SUBEND, UNLESS, UNTIL, WHILE.
line number Ls any valid line number in the program.
IFMORE tests whether the file pointer is sal the end of the file specified. If NOT at the end, BASIC exccutes the
statement. or goes to the line number T specified.
9.2.8 The NODATA Statement - ‚
The NODATA statement has s the e following format:
NODATA ге expression, line number
where: | |
[+] expression, is a terminal format file number.
line number ‘is any valid line number in the program.
9-7
Working with Files
When you specify NODATA with a file number: mer,
NODATA #6, 45
BASIC checks for the end of the file, i.e., no data. If at the end of the file, BASIC transfers control to the specified
line number.
If you do not specify a file number, (e.g., NODATA 110) BASIC tests to sce if all the DATA for that program or
subprogram has been exhausted. If there is no data left, control passes to the line specified in the NODATA
statement.
9.2.9 Changing Margins
The MARGIN statement allows you to modify the margin setting of a terminal-format file or the margin setting of
your terminal. The MARGIN statement has the following format:
MARGIN [FT] expression, num exp
where:
file exp — is the file number of the terminal-format file. If you do not specify this argument, your
o terminal margin is changed.
num exp is the numeric expression that determines the margin. (If it is a real number, it is truncated.)
The default margin is the current terminal width for the terminal,
Consider these examples:
00010 MARGIN 5
00020 FRINT *#*5 FOR I = 1 TO 10
00030 ENT |
— REALY
RUNNH
4...
EEE
FE a“
This example changes the terminal width to 5. To change back to the default, type:
. 10 MARGIN O
The following example changes the margin of a terminal-format file:
10 MARGIN #4, 132
9.2.10 ‘Setting Page Size
Normally, output to a terminal-format file and to a terminal are not divided into pages. The PAGE statement allows
you to set a page size of any positive number of lines.
The PAGE statement has the following format:
~~ PAGE [[#]] expression, num exp
ARG»,
9-8
Working with Files
where:
file exp is the file number of a terminal-format file. If omitted, the PAGE setting affects the
terminal, | |
num exp is any numeric expression. It is truncated before the page size is set.
The page size remains in effect until:
1. The page size is set again with the PAGE statement,
2. Execution ends. |
3, The file is closed.
“
At the end of program execution, the terminal is reset to its mode at program entry.
When a PAGE statement is executed, BASIC ends the current output line (if necessary) outputs a form-feed, and
starts counting lines beginning with the next line of output. As soon as a new page is necessary, a form-feed is
output. | |
9.3 VIRTUAL ARRAY FILES
A virtual array file, like a terminal-format file, is information stored on a system device (disk). Once you open a
virtual array file, the similarity with terminal-format files ends. There is no need for the INPUT #, INPUT LINE #,
LINPUT # PRINT #, or RESTORE # statements with virtual array files. You access elements in a virtual array
exactly as you access elements in an array in memory. (See Sections 2.6 and 2.6.1.) In fact, you can use virtual
arrays just as you would regular arrays, sce Chapter 8.
Virtual array files are random access files. You can read or write any clement in the file no matter where it is
located. The last element in a virtual array can be accessed as quickly as the first. Contrast this with a terminal-
format file where you must read the entire file to get to the last element.
When BASIC stores data in a virtual array file, it does not convert them to ASCII characters but rather stores them
in the internal binary representation. Consequently, there is no loss of precision caused by data conversion.
You must define storage space for a virtual array file just as you do for a regular array. The DIM # statement
(Section 9.3.1) allows you to set parameters for the file. Unlike arrays in memory, you must specify the maximum
character length of strings in a virtual array file. Strings longer than the maximum arc truncated. Strings shorter
than the maximum are padded with trailing nulls.
9.3.1 Dimensioning A Virtual Array File
To use a virtual array file, you must first define its size with a DIM # statement. The DIM # statement has the
following format:
DIM + num constant, array(s) [[=number]]
where:
num constant is the file number associated with the virtual array file.
array(s) is once or more 1- or 2-dimensional arrays separated by commas.
=number is the maximum length of a string array if any are specified. The default is 16 characters.
For example:
10 DIM #2» AC1S,20)>B(30)>C$C18)=10
9-9
Working with Files
The DIM # statement establishes the number of subscripts allowed for each virtual array, and the maximum values
for cach. In addition, the DIM # statement allocates all space for the virtual arrays associated with a particular file «=
number. Storage allocation always starts at the beginning of the file. Therefore:
100 LIM Fly ACIOO ,ECIO0)
10 LIM Fis ACIOO)
20 LIM #2; EC100)
do not perform the same function. Line 100 allocates 202 elements on file number one. While lines 10 and 20
allocate only 101 elements on file number 1. Each element has two names in this case.
When you specify a virtual array of strings, you should indicate the maximum length of each string. If no maximum
is specified, the default is 16.
To correctly access the data in an existing virtual array file, ensure that the DIM # statement specifies the same data
type and subscript as in the program which created the file. The variable name associated with the file can be
different from the original as long as the data type is the same.
9.3.2 Opening and Closing Virtual Array Files
To open a virtual array file, you use the OPEN statement with a few variations. The virtual array OPEN statement
has the following format:
OPEN filename exp [[FOR {INPUT \| AS [[FILE]] [[#]] expression
OUTPUT
, [[ORGANIZATION]] VIRTUAL pny
‚ACCESS { READ ALLOW | NONE
MODIFY READ
WRITE MODIFY!
WRITE!
[LINVALID line no.T] — [[,LOCKED line no. ]]
where:
filename exp is a file specification.
FOR INPUT specifies an existing file.
FOR OUTPUT specifies the creation of a new file.
expression is the file number. It tan be any numeric or integer expression with a
value between | and the system maximum.
ORGANIZATION VIRTUAL specifics a virtual array file. The keyword ORGANIZATION is optional.
ACCESS READ allows read only.
ACCESS WRITL allows write only.
ACCESS MODIFY allows read and write operations. This is the default.
ALLOW NONI: No simultancous access.
ALLOW READ allows others to read while you have the file. This is the default. рю
This feature is not available on the DI:CSYSTI-M-20 until Version 2.
9-10
hi FEA PF EEE PEE CRA UE E 6 BIE TUE OF Fo Ly
! Ï
Working with Files
ALLOW MODIFY! allows others to read and write while you have the file.
ALLOW WRITE! allows others to write while you have the file.
INVALID line no, specifies a line in the program where your error-handling routine resides.
LOCKED line no. specifies a line in the program where your error-handling routine resides.
The ORGANIZATION clause determines the file to be a virtual array as opposed to a terminal-format file. The
ORGANIZATION clause is not allowed in a terminal-format OPEN statement. The rest of the attribute clauses may
be specified in any order.
Consider these two program lines:
FOLOO» 20)
FOR
LIM #2,
OFEN "VARAY"
1.0
20 QUTFUT AS FILE Ey VIRTUAL
This program opens a virtual array file as FILE 2 and allocates 1,111 elements of storage space, i.c., 100 x 10 plus
the 0 elements.
As an example of a use of virtual array files, consider the problem of an information retrieval system for a small
organization. Assume there are 1000 employees each needing a 255-character record containing the name, home
address, home phone, work station and phone extension. If this information is maintained in a terminal-format
file, it would take a long time to locate the information for any employee and it would be impossible to update.
Alternatively, these records can be maintained in a virtual array file. In this case some index is needed to associate
a particular employce with a record.
In the following example, an index file containing badge numbers is used to find the record in the master file. The
employce”s badge number is in the same position in the index file as the record is in the master file. It is much faster
to scarch through the index file because the data elements are much shorter, and less time is spent reading data from
the file. This example program prints the employee’s name based on the badge number.
gn NO Ao RR Fe, WP BRE EE e A EUA A E TUTO SSeS o e
00010 TIM E1yEZC(1000)
00020 DIM EZ» E$CIONO): 0
00030 OFEN "BADGE" AS FILE 1,VIRTUAL
00040 OPEN "MASTER" AS FILE 27 VIRTUAL
00050 FRINT "UHAT IS THE GANGE NUMBER" y
00060 INFUT N
00070 FOR IZ=1 TO 1000
00080 IF RXZCIZI)I=N THEN 200
00090 NEXT Ix
00100 FRINT "NO SUCH EMFLOYEE"
0110 GOTO 77000
00200 FRINT "NAME IS" SEGECRECIA) 10% 304)
99000 CLOSE #1, #2
77797 ENT
To close a virtual array file, usc the CLOSE statement described in Section 9.2.2.
9.4 FILE RENAMING AND DELETION
The following sections describe the process of renaming a file and deleting a file from storage.
his feature is not available on the DECSYSTEM-20 until Version 2.
9-11
Working with Files
9.4.1 The NAME-AS Statement
The NAME-AS statement has the following format:
NAME string 1 AS string 2
where:
string | is the file specification of the file to be renamed.
string 2 is the new file specification.
For example:
10 NAME "MONEY" AS "ACCNTS"
This statement changes the file named MONEY to ACCNTS.
The NAME-AS statement does not alter the contents of the file. It renames the first file specified to that of the
second file without changing the file number. If you use the NAME-AS statement on an open file, the new name
does not take effect until the file is closed. Sec your User's Guide for system dependent file specifications.
9.4.2 The KILL Statement
The KILL statement has the following format:
KILL string expression
where:
string expression is the file specification of the file you want deleted from storage.
After you delete a file, you cannot open it or access it in any way. For example:
10 KILL “DATA”
deletes the file DATA from storage.
9-12
CHAPTER 10
RECORD 1/0
10.1 RECORD FILES
In addition to the two files discussed in Chapter 9, terminal-format and virtual arrays, BASIC provides another
method for storing information, the record file. A BASIC record file is a collection of related data stored in the
form of records. You determine the size and content of the records and the structure and access properties of the
file.
Programs can write records into a file and subsequently retrieve them. Each record is treated as a separate unit. All
input and output is performed on a record-by-record basis via a buffer between the file and the program.
In order to write BASIC programs that deal with record files, you need to establish the following:
File organization
Access method
Record format
Record mapping
File operations
6. Record operations
od Y ——
na
You also have the option of dynamically mapping 1/0 buffers.
These topics are explained in the following sections. For further information on using record files. sec the BASIC-
PLUS-2 User’s Guide for your system.
10.1.1 File Organization
The manner in which BASIC stores and retrieves records in a file is determined by the structure of the file. In
BASIC, the structure of a tile is known as the organization. When you create the file, you specify its organization.
The organization, in turn, determines the operations and access methods that you can use on the file. The three
organizations you can specify are:
I. Sequential
2. Relative
3. Indexed
A Sequential file contains records that are stored in series. The order in which the records occur in the file is always
the order in which they are written to the file. To read a particular record in the file, for example the 15th record.
a program must open the file and successfuily read the first 14 records before accessing the desired record.
Consequently, records can be added only to the end of a Sequential file because the location of each record is fixed
in relation to the record preceding and succeeding it. Sequential files are allowed on disk or magnetic tape.
A Relative file contains records that are stored in numbered locations. BASIC structures the file into a series of
record positions with each position capable of containing a single record. The number associated with a position
represents its location relative to the beginning of the file. Thus, record number 1 occupies the first record position:
record number 2 occupies the second record position, and so forth,
10-1
Record 1/0
Access to a record can be made sequentially or randomly by record number. Relative files are allowed only on disk.
E“
An Indexed file contains records that are stored according to a table. BASIC sets part of the file aside as an index
in order to locate these records. Lach record is retrieved based on the contents of a field, called a key, in the record.
When vou create an Indexed file, you must specify which field in the record is to be used as the key. Access to a
record can be made sequentially or randomly by reference to the key. Indexed files are allowed only on disk.
10.1.2 Access Methods
The methods that you use to store or retrieve records in a file are called access methods. The access method allowed
on a particular file is determined by the file’s organization. BASIC allows you to specify one of two access methods:
I. Sequential
2. Random
Sequential access indicates that records are accessed in serial order. Random access indicates that records are accessed
by record number.
y A
Table 10-1 shows the relationship between file organization and access methods.
Table 10-1 Access Methods
Access Methods
File Organization Sequential Random
Sequential es 10
que y ' ama
Relative yes yes
Indexed yes yes
10.1.3 Record Format
A BASIC program must specify the format of records within a file. The format of a record determines.how a record
physically appears in a file on a storage medium. BASIC allows you to specify one of three formats:
1. Fixed Length
2. Variable Length
3. Stream a
Fixed-length record format refers to records that are all equal in size. Each record occupies an identical amount of
space in the file.
Variable-length record format refers to records that are not necessarily equal in tength.
A stream format file contains a series of contiguous ASCII characters. In this case, a record is defined as a set of
characters delimited by a form feed, vertical tab. or line feed.
The record format you select is restricted by the file organization. Sequential files support all three formats. How-
ever, Relative and Indexed files permit only fixed and variable length record formats.
Note that specifying variable-length format for Relative files does not save space on the disk. Space is allocated for
the maximum record size for each record position. Records that are smaller than the maximum use only part of
the space available.
Table 10-2 shows the relationship between file organization and record format.
oe ENFRANTE EEN TENER RCA TRGEEE TENES FE Aer SEE RT PRESS
Record 1/0
Table 10-2 Record Formats
Record Format
File Organization Fixed Variable Stream
Sequential yes yes yes
Relative yes yes no
Indexed yes yes no
10.1.4 Record Mapping
To access records in a file, you must establish a buffer for input and output. You can name the buffer and describe
the characteristics of the records in a particular file with the MAP statement. The MAP statement specifies that
certain variables arc contained in the buffer.
The MAP statement has the following format:
MAP (name) ALIGNED element(s)
UNALIGNED
where:
(name) is the name you give to the buffer. The length of the name is system dependent. Parentheses
are optional.
ALIGNED is optional. These keywords refer to the way data is placed in the buffer. ALIGNED is the
UNALIGNED — default. For more information, refer to the User's Guide.
element(s) is a list of elements, separated by commas, defining the characteristics of the record. Each
element represents a field in the record.
A legal element in a MAP statement can be any numeric, integer, or string variable, an entire array, or a FILL. (IFILL,
FILL%, FILLS, FILLS=n, FILL(n), FILLS(n)=m)
FILL acts as a space holder allowing you to mask parts of a record or hold space for future use. FILLS=m is a string
of m characters and FILL$(n)=m is n strings of m characters.
The length of a string variable is specified by the syntax
A$=n
where:
AS is the string variable.
n is the number of characters in the string. n must be a constant.
For example:
10 MAF (BUFF1) NAME$=25y5S%»FILLyACEZ
This statement sets up a buffer arca named BUFF1 and describes four data fields:
1. Astring field containing up to 25 characters
2. An integer field
10-3
3
>.
Record 1/0
À place holder
4. Another integer field
When specifying a string data field, you should define the number of characters in the field. The default is 16 charac-
ters. Strings in a string ficld are a fixed length. BASIC stores them left-justified and padded with blanks. For
example:
00010 MAF (TEST) B$=7
00020 OPEN "FILE" AS FILE 1, SEQUENTIAL» ACCESS AFFENDy MAF TEST
00030 B$="ARC"
00040 CZ=LENCE$)
00045 FRINT CZ
00050 FUT #1
00060 CLOSE #1
00070 ENT
READY
RUNNH
7
Although the value assigned to BS is 3 characters long, the length of the string field contains those 3 characters plus
4 trailing blanks. Its length is 7.
NOTE
Variables that are parameters to subprograms are all
passed by reference. Therefore. if an actual parameter is
a variable that is MAPed. execution of a GET inside the
subprogram will change the value of the dummy
parameter.
The following rules apply to MAP statements in a BASIC program:
|.
All MAP statements must appear before the OPEN statement in a program and before their variables are
referenced.
You can have multiple maps with the same name. The largest buffer (longest element list) must be specified
first. The first map sets up storage allocation.
The same variable can appear on the element lists of different map statements with the same map name. In
this case, the variable must occur in the same position in each map. For example:
100 MAF (RUFF1) A EC
200 MAP (RUFF1) AsQ»C
If you specify an array in a MAP statement, you must dimension it in that statement. If the same array
occurs in two different MAPs, the dimensions must be the same.
The length of a string field should be defined: otherwise, the default is 16 characters.
MAPS are local to the MAIN program or subprogram in which they are defined.
The MAP statement is referenced in the OPEN statement when you create a new file or access an existing file.
{0-4
Cala Ta
Record 1/0
10.2 FILE OPERATIONS
When dealing with record files, you are either working with the file as a whole or working with an individual record in
the file. The following sections describe how to
1. “Create a new file — OPEN statement
2. Access an existing file OPEN statement
3. Close a file — CLOSE statement
4. Return the file pointer to the beginning - RESTORE statement
5. Truncate an entire file - SCRATCH statement
10.2.1 Creating and Accessing a File
The OPEN statement enables vou to create a new file or access an existing file. With this statement you can deline,
explicitly, all the important aspects of each data transfer operation including the structure of the file and its file
sharing capabilitics. You can also include the specification of error returns.
The syntax of the OPEN statement includes keywords that describe attributes of the file. These attributes are fol-
lowed, in general, by a name, numeric expression, or line number, and you separate them with commas.
The following is the general syntax of the OPEN statement for a record file:
OPEN filename exp № Jeo { AS [FILE] =] expression
OUTPUT
‚[ORGANIZATION] (SEQUENTIAL FIXED
RELATIVE VARIABLE
INDEXED STREAM
WRITE READ
[6 Y WRITE
TT
¡ACCESS № AD ALLOW {NONE
(scraten MODIEY
МА mapname [INVALID line no]
,RECORDSIZE num exp
[[LOCKED line no] I DOUBLEBUF |
,BUFFER [4 num exp
[fsa ] [[BLOCKSIZE num exp]
NOSPAN
[BUCKETSIZE num exp] [[CLUSTERSIZE num exp]
[NorEWIND] [[cONTIGUOUS]]
[PRIMARY [KEY] name] ее |
NODUPLICATES
NODUPLICATES INOCITANGES
[ALTERNATE [KEY] remo Y DUPLICATES il (CHANGES N
10-5
Record 1/0
where:
filename exp is a system dependent file specification.
FOR INPUT requires that the specified file exist. If the file does not exist, an error results. This error
causes the OPEN to return to the line specified by the INVALID clause.
FOR OUTPUT creates a new file with the name you specify.
[f you leave the FOR clause out entirely, BASIC searches for an existing file of the specified name. If the search
fails, BASIC creates a new file.
AS [FILE] [+] expression
associates the file with a file number. File number O (user's terminal) is illegal.
[JORGANIZATION]] SEQUENTIAL
arranges the records in the file by order of input. i.e., in serial order.
[[ORGANIZATION]] RELATIVE
arranges records by numbered position in the file.
.[JORGANIZATION]] INDEXED
arranges records so that they can be accessed by reference to a keyed index.
[FIXED]
specities that the records are a fixed length.
[VARIABLE ]]
specifies variable length records in the file. Note that if records are variable length. the buffer is padded with
O's (nulls) after a GET of à record that is smaller than the buffer. This format is the default for all 3
organizations.
[STREAM]
specifies ASCII stream records. (Seguential files only.)
[ACCESS READ]
WRITE
MODIF Y
SCRATCH
APPEND
specifies the operations that the current user can perform on the file.
READ
allows read only.
WRITE
allows write only.
MODIFY
allows read, write, delete. und update operations. This is the default for Seguential, Relative and Indexed files.
SCRATCH
allows full access: read, write, delete, update and truncate. (Note that a file cannot be accessed by multiple
users if it is open with ACCESS SCRATCH.)
APPEND
allows write access at end of file.
10-6
EEE A TT CR
|
CF ОЦА
Record 1/0
[ALLOW NONE]]
READ
WRITE
MODIFY
defines what you allow other users to do to the file while you are using it.
NONE
specifies a protected file. This is the default for Sequential files.
READ
allows read only. This is the default for Relative and Indexed files.
WRITE
allows write only.
MODIFY
allows read and write access.
MAP mapname
references a MAP statement. The map buffer you reference defines the buffer used to store the file’s data
temporarily. The MAP can also be used to define the record size.
,RECORDSIZE num exp
defines the maximum size of records (in characters) in the file. RECORDSIZE must be specified when no MAP
clause is specified.
If you specify both the MAP clause and the RECORDSIZE clause in the same OPEN statement, the RECORDSIZE
overrides the MAP even if the former is smaller. In this case, the RECORDSIZE is the size of the record, and the
MAP is just a place to store it.
[LINVALID tine no.[]
specifies the line number of an error-handling routine. Control transfers to this line if the OPEN fails due to an
illegal file specification. |
[LOCKED line no. []
also specifies the line number of an error-handling routine. Control transfers to this linc if the OPEN fails
because the file is locked (protected). | |
.DOUBLEBUF
[Dou [#1] num exp
signifies the number of buffers used during file operations. The default is 2. DOUBLEBUF has no effect. It
exists for compatibility with another version of BASIC. | |
[[SPAN, NOSPAN|]
signifies that records are allowed to cross block boundaries. The default is SPAN.
BUCKETSIZE num exp ||
.BLOCKSIZE num exp
CLUSTERSIZE num exp
.NOREWIND
CONTIGUOUS |
These attributes are system dependent. Refer to BASIC-PLUS-2 User's Guide for more information.
10-7
Record 1/0
[[-PRIMARY [[KEY [] name ]]
is required for an Indexed file. It defines the name of the Primary index key. The size and location of this key
is specified in the MAP statement. The name is one of the elements in the list. The key must be a string. Dupli-
cates are allowed but CHANGES are not.
[ALTERNATE [[KEY]] name T]
allows you to optionally define the names of one to 254 Alternate index keys. Alternate keys must also be
strings.
{NODUPLICATESUT
DUPLICATES
NODUPLICATES is the default. If DUPLICATES is specified for a given key of reference, the file can contain
more than one record with the same value for that key.
EN
NOCHANCES
NOCHANGES is the default. If CHANGES is specified for a given key of reference, the value of the field for
that key in a given record can be changed. Alternate keys may have changes but the primary key may not.
Note that the combination CHANGES and NODUPLICATES is illegal.
The ORGANIZATION clause must be the first attribute specified. The severity of the error is system dependent.
Refer to the User's Guide. The other attributes may be specified in any order.
The following sections describe the OPEN statement as it applies to each file organization.
10.2.1.1 Opening a Sequential File The following syntax is used when opening an existing file or creating a new
Sequential file:
OPEN filename exp [For eL \| AS [FILE ]] [+] expression
OUTPUTS -
[[ORGANIZATION]] SEQUENTIAL [T(FIXED IT
VARIABLE
STREAM )I|
‚ACCESS (READ ‚ALLOW /NONE
WRITE READ
MODIFY WRITE
SCRATCH MODIFY ||
APPEND
,MAP mapname [INVALID line no. [| [[.LOCKED line no. []
,RECORDSIZE num exp
| | ([CLUSTERSIZE num exp []
,BUFFER [+] num exp
.NOSPAN
[[.BLOCKSIZE num exp]] To | [[-NOREWINDT]
[[.CONTIGUOUS]]
10-8
3
ME.
Record 1/0
The following example opens a Sequential file:
20 OFEN "CASE" AS FILE #5 3
» ORGANIZATION SEQUENTIAL STREAM &
y ACCESS AFFENT:» ALLOW NONE, MAF MAF1 3
» INVALID 120 LOCKED 70
This statement opens an existing file named CASE, positions the file pointer at the end of the file, and associates the
file with file number 5.
The SCRATCH statement allows you to truncate the entire file. This statement is only valid for a file OPENed with
ACCESS SCRATCH. Sec Section 10.2.4.
10.2.1.2 Opening a Relative File — The following syntax opens a Relative file:
OPEN filename exp [[FOR {INPUT AS [FILE] [[#]] expression
OUTPUT
|[ORGANIZATION]] RELATIVE [[JFIXED |
VARIABLES
,ACCESS (READ ALLOW (NONE
WRITE READ
MODIFY WRITE
MODIFY.
LAT mapname [[,BUCKETSIZE num exp |]
,RECORDSIZE num exp
[[,CLUSTERSIZE num exp] fDOUBLERUE |
BUFFER [=] num exp
e | [[ INVALID line no.]| [[ LOCKED line no. ||
,NOSPAN
The following example opens a Relative file:
110 OFEN "FOO" FOR QUTFUT AS FILE #1 &
‚ORGANIZATION RELATIVE FIXED, ACCESS MOLIFY, 2
ALLOW READ: MAF TEST,» LOCKED 230
This statement creates a new file name FOO and associates it with file number 1. Each record in the file has a fixed
length. The user of the file has read and write access capabilities, while other people can only read records.
BUCKETSIZE is system dependent. Refer to the BASIC-PLUS-2 User’s Guide.
10-9
Record 1/0
10.2.1.3 Opening an Indexed File -- The following syntax opens an Indexed file:
OPEN filename exp || FOR out IN AS [Field] expression
OUTPUTS
{[orGANIZATION] INDEXED | |
VARIABLE
¡ACCESS (READ ALLOW ¢ NONE
WRITE READ
MODIFY WRITE
MODIFY/ |
MAP mapname \ [| BUCKETSIZE num exp] Г. LOCKED line no. ]
‚RECORDSIZE num expf
[.CLUSTERSIZE num exp] {DOUBLERUE
BUFFER [[#]] num exp
PRIMARY [KEY] name {[{DUPLICATES |] [[, INVALID line no. |
NODUPLICATES(
| NODUPLICATES/ NOCHANGES
[ALTERNATE [KEY] rome DOI |] | o \|
The PRIMARY key is mandatory for an Indexed file. The following cxample illustrates the opening of an Indexed
file:
50 OFEN "ACCOUNT" FOR INFUT AS FILE #4 3
y ORGANIZATION INDEXEL VARIARLI 38
y ACCESS MODIFY» ALLOW NONE &
y FRIMARY E$» ALTERNATE WAGES$ %
y MAF EUFF1
This statement opens an existing file named ACCOUNT and associates the file with file number 4. The records are
variable length. The primary index key is in the data field BS. and there is one alternate key named WAGESS. Note
specifying CHANGES with NODUPLICATES is illegal.
10.2.2 Closing Files
Record files, as well as terminal-format and virtual array files, should be closed when no longer needed. The CLOSE
statement, described in Section 9.2.2, is also valid for record files.
The CLOSE statement has the following format:
CLOSE [[file number(s) |]
where:
file number(s) represent onc or several tiles separated by commas.
10-10
Record 1/0
For example:
65 CLOSE #3
If you do not specify file numbers, BASIC closes all files.
10.2.3 Restoring a File
The RESTORE # statement allows you to bring the file pointer back to the beginning of the file without disturbing
the data. All file organizations can use this feature.
The RESTORE # statement has the following format:
RESTORE # file number [[ KEY # num exp ]]
where:
file number is the file you want to reset.
KEY #numexp is for indexed files only. This allows you to establish a new key of reference.
For example:
2% RESTORE #6» KEY #0
This example brings the file pointer to the index table designated by 0. This is the Primary key.
10.2.4 Truncating a File
The SCRATCH statement truncates a file at the current file pointer. The SCRATCH statement has the following
format:
SCRATCII [[#]] file number(s)
where:
file number(s) is one or more open files. Separate each file number with a comma.
SCRATCH erases the contents of the file but does not delete the file. To use the SCRATCH statement, the file must
be OPENed, with ACCESS SCRATCH. See Section 10.2.1.
10.3 RECORD OPERATIONS
There are several operations that you can perform on individual records in a file, depending on its organization.
Record file operations allow you to add, remove, examine, and modify the contents of a file. When writing into
a file, a program builds records and passes them for storage in the file. When reading a file, a program requests
records from the file. With BASIC, you can
Read a record — GET statement
Write a record — PUT statement
Locate a record — FIND statement
Replace a record — UPDATE statement
Remove a record — DELETE statement
ло К юн
10-11
Record 1/0
The GET statement reads a record from the file into a buffer.
The PUT statement writes a new record from the bufter to the file.
The FIND statement locates the specific record in the file and points to it.
The UPDATE statement replaces an existing record with a new one. You must do a FIND or a GET before you
can UPDATE.
The DELETE statement erases an existing record from the file. You must do a FIND or a GET before a DELETE
operation.
The following sections describe your options in relation to cach file organization.
10.3.1 Sequential Record Operations
The following are the operations you can perform on a sequentially organized file.
GET file exp [[.LOCKED line no. ]]
[LINVALID line no. ]]
PUT file exp ‚MAP line no. [LINVALID line по. |]
COUNT exp [LOCKED line no.]]
UPDATE file exp MAP line or [INVALID line по. |]
COUNT exp
FIND file exp [[LLOCKED line no JJ[LINVALID line no. J] a
In a Seguential file, a GET operation is performed on succeeding records starting at the beginning of the file. Each
successive GET statement retrieves the next record in the file and places it in the buffer identified by the MAP
statement. If you retrieve a record that is smaller than the buffer, BASIC fills the buffer with nulls.
A PUT statement in a Sequential file writes the record from the buffer to the end of the file without truncating
records. You can write only at the end of a Sequential file without truncating records. When you are writing to a
file, you must specify the record size with a MAP or COUNT. The MAP line number in the PUT statement specifies
the size of the RECORD to PUT. It cannot be used to specify a different buffer from that previously specified in or
the OPEN statement. If the MAP or COUNT clause is not specified, the record size is defined by the MAP or
RECORDSIZE clause in the OPEN statement.
In order to replace an existing record with the UPDATE statement, you must first do a successful GET or FIND.
You also must specify the size of the record by referencing the MAP line number or giving the actual size in charac-
ters with COUNT. The size of the new record must be the same as the one being replaced.
Because you can only access Sequential files sequentially, a FIND operation locates the next record in sequence.
Note that you cannot DELETE records in a sequential file.
10.3.2 Relative Record Operations
The following operations can be performed with a Relative file:
GET file exp [RECORD num exp]]
[[LLOCKED line no.]] [[JNVALID line no.]]
oA -
10-12
Record 1/0
PUT file exp [LRECORD num exp
‚MAP line no.
[far in num of
[LLOCKED line по. |] [LINVALI D line no. |)
UPDATE file exp ‚MAP line no.
‚COUNT num exp
[LLLOCKED line no.] [LINVALID line no.]]
DELETE file exp [[INVALID line no.]]
FIND fileexp = [| RECORD numexp]]
[LLOCKED line no.]] ~~ [INVALID line no.]|
With Relative files, you are allowed random access as well as sequential access. Therefore, you can specify which
record you want to GET and PUT. If you Icave off the record number in the statement, BASIC will read, write.
or locate the next record in seguence. Notice that the DELETE and UPDATE statements do not have [RECORD
num exp J] as an option. The record number is already specified when you do the necessary GET or FIND operation.
Some record operations change the value of the record pointer and some do not. In a Relative file, a sequential GET
and a sequential PUT each modify the value of the record pointer.
For example:
00100 GET #7y RECORD 2 !'RANDOM RETRIEVES RECORD 2
00200 GET #7 SEQUENTIAL RETRIEVES RECORD 3
00300 GET #7 ISEQUENTIAL RETRIEVES RECORD 4
À random GET operation also modifies the value of the record pointer; however, a random PUT docs not. Consider
the following example:
00300 GET #1;KECORD 15 IRANDOM RETRIEVES RECORT 15
00400 FUT #1,RECORD 20 PRANDOM WRITES RECORD 20
00500 FUT #1 SEQUENTIAL WRITES RECORD 16
Note that line 500 PUTs record 16 (not 21) because the random PUT in line 400 did not change the value of the
record pointer.
A FIND operation is only relevant if the next operation is a GET, DELETE, or UPDATE. A PUT after a FIND
invalidates the FIND; therefore, a subsequent GET retrieves the next record rather than the record located by the
FIND.
In the following example line 600 PUTs record 11:
00400 СЕТ #1, КЕСОКО 10 IRETRIEVES RECORD 10
00300 FIND #1,RECORD 20 'LOCATES RECORD 20
00600 FUT #1 "WRITES RECORD 11
However, in the example:
00700 FIND F1»RECORT 20 ILOCATES RECORD 20
00800 UFIDATE #1 IREFLACES RECORD 20
line 800 UPDATES record 20.
10-13
Record 1/0
10.3.3 Indexed Record Operations
The following operations deal with Indexed files only:
EQ
GET file exp [KEY #num exp (GT string ]
GE
[,LOCKED line no. [LINVALID line no. ]]
PUT file exp J MAP line no. |
|COUNT num exp
[[.LLOCKED line no. ILINVALID line no. |]
UPDATE file exp [TJ MAP line no. |
‚COUNT num exp
[INVALID line no.]]
DELETE file exp [INVALID line no.]]
EQ
FIND file exp [KEY “num exp fo! string exp]
GE
[LOCKED line no. [NV ALID line no.
In random access to an Indexed file, you supply a key previously defined in an OPEN statement as a PRIMARY or
ALTERNATE key. To locate a specific record, specify one of the two key matches:
1. Exact key match
2. Approximate key matcn
With the exact key match, BASIC looks for the record that matches the value you assign to the key.
For example:
00010 MAF(CFILE1) SUKNAMES=20,GIVENNAMES=10>SSN$=9 > AUDRESS$=402%
y ZIFCONE $=5
00020 MAFCFILE1) NAMES:=:30sIL$=9, ALDRE=45
00030 OFEN "ACCOUNT" FOR INFUT AS 45» INDEXEN VARTABRLE »MAF FILEL»&
FRIMARY NAM$, ALTERNATE SSN$-, ALTERNATE ZIFCOLE$
00040 СЕТ #5» KEY #1 EQ "013445695"
00050 GET #5-KEY #0 EQ "МОКРНУ"
The map at line 10 defines the record as follows:
SURNAMES GIVENNAMES £SSN$ ADDRESSS 2ZIPCODES
The map at line 20 defines the record as follows:
NAMESS IDS ADDRS
10-14
EE
A +.
HSER TI
Record 1/0
The OPEN statement at line SO defines the keys within the records as follows:
KEY# Starting Position Length
O (PRIMARY) 0 30
| 30 9
2 79 5
When executing line 40, BASIC refers to the keys specified in the OPEN statement. KEY#1 is the first ALTERNATE
key SSNS. This field is defined in the MAP at line 10. BASIC searches for an exact match of a record with
“013446595” starting at position 30.
When executing line 50, BASIC again refers to the keys in the OPEN statement. KEY#0 is the PRIMARY key NAMS.
This key is part of the record described in the MAP on line 20. BASIC searches an exact match of a record with a
ficld “MURPHY” in starting position O.
The second type of search, approximate key match, allows you to request the record closest to the value you specify.
The proximity is determined by the ASCII collating sequence. The approximate key search allows your program to
select either of the following relationships:
1. Equal to or greater than (GE)
2. Greater than (GT)
If the key requested does not exist, BASIC returns the record that contains the next higher key value. This allows
you to retrieve records without knowing the exact key.
For example:
GET #;
GET +
a
y KEY #0
so KEY #0
Mn
O GE
O GE
Md
Line 40 defines the key as PRIMARY and searches for a data ficld that is greater than or equal to (GE) the value
“JONES”, e.g., “KNIGHT”.
Line 50 also uses the PRIMARY key but searches for a data field greater than “ABRAMSON”, e.g., “ADAMS”.
“ABRAMSON?” is not an acceptable match in this case.
You can also affect a match by specifying a key value with fewer characters than were specified for the corresponding
field in the record. The match occurs if the first characters in the field arc identical to the key value.
If you do not specify a KEY, you effect a sequential GET according to the previous KEY specified. BASIC will then
retrieve the next record in the index according to the ASCII collating sequence.
When you PUT to an Indexed file you merely specify
PUT file exp
BASIC places the record in the proper index.
In addition to read, write, and find operations, your program can delete any record in an Indexed file and update
any record. However, during an update operation, be sure that the contents of the modified record do not change
the Primary key value. You can change alternate key values if CHANGES is specified.
10-15
Record 1/0
10.3.4 Record Locking
If you plan to allow file sharing (simultaneous access) by specifying ALLOW READ, ALLOW WRITE, or ALLOW
MODIFY. you should be aware of the correlation between an 1/O operation and the locked status of a record.
Records are locked according to the attributes specified in the OPEN statement and according to the particular
1/0 operation you perform on the record. The ACCESS clause determines the effect the I/O operation has on the
locked status of a record.
If you OPEN with ACCESS READ,
GET locks the record only for the duration of the operation. The record is unlocked when the GET
is completed.
FIND' locks the record untii a GET is completed or until another record is accessed with a FIND or GET
operation.
[If you OPEN with ACCESS WRITE, MODIFY, or APPEND,
GET locks the record until another record is accessed by a GET, FIND, or PUT operation: or until the
current record is UPDATEd or DELETEd.
FIND locks the record until another record is accessed by a GET, FIND, or PUT operation; or until the
current record is UPDATEd or DELETEd.
10.4 DYNAMIC MAPPING OF AN 1/0 BUFFER
The MAP statement (described in Section 10.1.4) defines the format of a record when that format can be specified
at compile time. When this is not the case. the MOVE statement can be used to dynamically access the data ina
record. For example, you can use MOVE to access a record in which the lengths of strings or arrays in the record are
specified by fields at the beginning of the record. The MOVE statement associates the data in a record with the
variables you specify in an I/O list. The format of the MOVE statement is:
MOVE [| ALIGNED | |[JFROM] file exp. 1/0 list
UNALIGNED/ || TO f
where:
ALIGNED is optional. These keywords refer to the way data is placed in the buffer. ALIGNED is the
UNALIGNED default. For more information, refer to the BASIC-PLUS-2 User's Guide.
FROM moves the data from the buffer associated with the file number and places the data in the
clements in the 1/0 list.
TO moves the data from the elements in the I/O list and places it in the buffer associated with
the file number.
file exp is the file number associated with the file OPENed previously.
, the comma is mandatory between the file exp and the I/O list.
1/0 list is a ist of legal elements.
Legal elements in an 1/0 list are:
l. numeric, integer, string variables
2. arrays
"On RSTS/F. the record is unlocked after the FIND operation Is completed.
10-16
MRR ES
«mE
Record I/O
3. array elements
4. fill specifiers
The length of a string may be defined in the 1/0 list, c.g., AS=n. The default length for MOVE TO is LEN(AS); the
default for MOVE FROM is 16.
An array specified in a MOVE statement must have the following format:
A( ) list
A(,) matrix
Note that row zero and column zero are affected by the MOVE.
You specify an array clement by name, i.c.,
A(25)
The following are examples of MOVE statements:
60 MOVE FROM #5» As>B»FILLAICC )
85 MOVE TO #5» AssBysFILLA>CC ?
Successive MOVE statements to or from the same file each start at the beginning of the buffer. The size of the
buffer is not affected by MOVE’s. If a MOVE only partially fills a buffer, the rest of the buffer is unchanged.
To retrieve a record from a file, first read the record with a GET statement. This places the record in the buffer. The
buffer can be a system buffer or a buffer you have set up with a MAP statement.
Then a MOVE FROM places the data from the buffer into the elements in the I/O list. Once the data is associated
with the elements, you can reference them in the program.
A MOVE TO moves the data from the elements in the I/O list to a buffer. To move the data into a file, you do a write
operation with the PUT statement.
Consider the following program:
00010 OFEN "MOVE.DAT" AS FILE #1, ORGANIZATION SEQUENTIAL »Z&
ACCESS MODIFY, ALLOW NONE, RECORDSIZE 50
00020 GET #1
00030 MOVE FROM #1, Is A$=I
00040 At=A$ + ">"
00050 I = I + 1
00060 MOVE TO #1» 1, АФ=1
00070 UPDATE #1
00080 CILOSE #1
00090 ENT
This program opens an existing file named TEST, reads the first record into the buffer, and associates the data with
the variables in the MOVE FROM statement.
The MOVE TO places the record into the buffer, and the PUT statement writes the record back into file #1. The
file is closed and the program ends.
10-17
MEET
CHAPTER 11
PROGRAM SEGMENTATION
11.1 SUBPROGRAMS
In addition to functions, and subroutines, BASIC supplies a third method for writing procedures to be used several
times; subprograms. A subprogram allows you to divide a large task into smaller, more manageable units which, in
turn, can be accessed individually.
You can usc subprograms in two ways:
I. asa segment of a main program which can be called several times from the main program
2. as a mini program, which can be called by several different main programs.
In both cases, the subprogram is executed by a CALL statement (Section 11.1.1) contained in the main program.
The SUB statement marks the beginning of a subprogram and has the following format:
SUB name [[(dummy argument(s))]]
where:
name is the unique name for the subprogram. (The length of the name is system-
specific.)
(dummy argument(s)) represent one or more parameter variables and file references separated by
commas. The variables must agree in type and number with that of the calling
sequence. (See Section 11.1.2.)
If you usc the SUB statement in a multi-statement line, it must be the first statement in that linc.
The body of the subprogram may contain any legal BASIC statement except for those which affect transfer out of
the body of the subprogram. Transfers into and out of the body of a subprogram are illegal.
All variables in a subprogram are local to that subprogram. These local variables are initialized to 0 or a null string
upon cach entry to the subprogram. Also, any data used from DATA statements are local to the subprogram. The
DATA pointer in the main program is not affected.
Exit from a subprogram and return to the main program with the SUBEND statement or SUBEXIT statement. The
SUBEND statement has the following format:
SUBEND
The SUBEXIT statement has the following format:
SUBEXIT
SUBEXIT returns control to the calling program. It has the same effect as GOTO n, where n is the line number of
the appropriate SUBEND statement. | |
Program Segmentation
SUBEXIT is illegal in a main program or multi-line function definition.
AE +.
11.1.1 The CALL Statement
The CALL statement transfers control to the subprogram, provides a parameter transfer, and saves the state of the
calling program.
The CALL statement has the following format:
CALL name [[(actual argument(s))]]
where:
name is the subprogram name defined in the SUB statement.
(actual argument(s)) is onc or more variables, constants, and expressions, separated by commas.
These parameters must agree in position, type, and number with the dummy
list in the SUB statement
You place the CALL statement anywhere in a main program, subprogram, or multi-line DEF. When you reference
a subprogram with the CALL statement, BASIC replaces the dummy arguments with the corresponding actual
arguments (Section 11.1.2) listed with the CALL. The subprogram then works with these parameters.
The following is a SUB statement:
900 SUB TEST (А, В+)
This is a corresponding CALL:
ARE >
90 CALL TEST <CrA$)
Upon returning to the main program, BASIC exccutes the statement following the CALL statement.
11.1.2 Dummy And Actual Arguments
Because you can reference subprograms at more than one point throughout a program, many of the values used by
the subprogram may change cach time it is used. Dummy arguments in subprograms represent the actual values
passed to the subprogram when it is called.
рос
These dummy arguments indicate the data type of the actual arguments they represent. The position, number, and
type of each dummy argument in a subprogram list must agree with the position, number and type of each actual
argument in the reference to the subprogram (CALL statement).
[tems passed to subprograms can be any legal variable, constant, expression, array, or array element. The value of
any parameter can be used as a file number in the subprogram. BASIC passes items from the main program to the
subprogram either by value or by reference. When passing by value, BASIC makes a temporary copy of the value
in the calling program and uses the copy for calculations in the subprogram. The value in the calling program
remains unchanged. The following items are passed by value: .
1. constants
2. expressions
3. array elements
When passing by reference or address, BASIC takes the actual value from the location in the main program, uses
the value in the subprogram, then replaces the value in the main program. In this case, because of calculations in a
ak rhe Tu rer
TA gn Je EA BR CSS PFT ee dena BY Sr EE =} Gi
i
Program Segmentation
the subprogram, the value passed by reference could change in the main program. The following items arc passed
by reference:
|. variables
2. entire arrays
It is not possible to pass complete arrays by value. Individual elements of a list or table, however, arc always passed
by value. When an individual entry in an array is passed to a subprogram, it is received as a numeric or string variable
depending on its type. For example:
90 SUR ELEMENTS (ARRAY)
20 CALL ELEMENTS CRCIIC))
The CALL passes the copy of the valuc in array element BCD(5) to the subprogram. Thc SUB statement accepts
the value in the variable name ARRAY.
If you specify an entire array in either argument list, you do not include the subscript. For example:
C( )is a list
C(, } is a matrix
When you pass an array to a subprogram, its dimensions remain the same as in the main program. It is illegal to use
a DIM statement on an array you specify in the SUB statement. You can, however, redimension such an array with
a MAT statement (Chapter 8). The array will also be redimensioned in the main program as well. Arrays local to
the subprogram must appear in DIM statements within the subprogram.
Functions can be defined inside subprograms. A function definition is local to the subprogram in which it is defined.
However, vou can pass the value of a function as an expression.
You can also pass files to a subprogram. BASIC passes the position of the file pointer to the subprogram unchanged
from its position after the last operation affecting the file in the main program. Any operation on a file in a sub-
program also affects the file in the main program.
You can also open a file within a subprogram. The file remains open after BASIC returns to the main program.
When you include a file reference in a SUB statement, the reference must be a variable name.
The following example illustrates argument lists in the SUB and CALL statements:
LISNH
00010 AZ=5Z NEZ=: 104 NC4S 154
00020 CALL ARGOCRZ)
00030 CALL АКСССЯ)
00040 РЕТМТ "АХ" АЙ; "Все" УВ "СТ СЯ
00050 ENT
00060 SUB ARGCHA)
00070 AZ=30%
000830 DX=IZXAZ
000920 SUBENT
READY
RUNNH
AZ= 5 EZ= 300 C4= 450
Program Segmentation
Note that on RSTS/L, the main program and any subprograms must be compiled separately. See your User's Guide is
for details.
The subprogram ARG is called twice in this program with the CALL statements on lines 20 and 30. The first time
the subprogram is referenced, the value stored in B% is passed to the integer variable D% to be used in calculations.
The second CALL statement passes the value stored in C% to integer variable D%. Notice that variables are local to
the subprogram (A%). Consequently, you can use the same variable name in a main program and a subprogram
without interference.
BASIC passes all constants in the CALL statement to the subprogram by value. That is, the value of the constant
does not change in the main program. However, BASIC passes all variables by reference. The value stored in the
variable location is passcd to the subprogram. Consequently, this value may change in the main program after BASIC
executes the subprogram.
The following table summarizes the proper form for variable names, functions, arrays, and files references in SUB
and CALL statements. ря
Table 11-1 Arguments
Dummy Argument Actual Argument
Data Type SUB Statement Call Statement
numeric A B
integer AZ B%
string AS B%
entire list AC), AZ), AS() B(), B%(), BS() —
entire matrix A(,), A%(,), AS(,) B(,), B%(,), BS(,)
file AC I, N
array clement A D(1)
11.2 TRANSFERRING CONTROL TO ANOTHER PROGRAM — THE CHAIN STATEMENT
The CHAIN statement transfers control from the current program to a program stored in a file. CHAIN first closes
all files and erases all program lines, arrays and variables. Finally, it loads the program from the file, compiles it,
if necessary, and starts the execution of the new program. pa
The CHAIN statement has the same effect as an END statement followed by an OLD command and then a RUN
command.
The format of the CHAIN statement is
CHAIN string [[LINE line number [|
where:
string is a file specification for the file containing the new program. The string can be
any string expression.
[[LINE line number [] specifics the line to start execution in the new program.
If no line number is specified, then execution starts at the lowest numbered line.
A
EE TEE m
Consider the following example:
The file specified by “SEG1” contains:
00005 FRINT
00010 OFEN *ILATA!"
Program Segmentation
"SEG1 IS WORRING"
FOR QUTFUT AS #1
00020
00030
00040
00050
00060
00070
00005
00010
00020
00030
00040
00050
00060
00070
00080
1 TO 100
IX2
FOR I =
FRINT #1»
NEXT 1
CLOSE #1
CHAIN "SEG2.B20"
END
The file specified by “SEG2” contains:
PRINT "SEG? IS WORKING"
OFEN "DATAI" FOR INFUT AS #1
FOR I = 1 TO 100
INPUT #1, I
T = T+I
NEXT 1
PRINT “THE TOTAL I1S"»T
CLOSE #1
END
A run of these programs produces the following output.
RUNNH
SEG1 IS WORKING
SEG? IS WORKING
THE TOTAL IS 2550
IFPRINTS IDENTIFYING MESSAGE
1NOFENS OUTFUT FILE
"WRITES OUT ALL THE
'EVEN NUMBERS 2 TO 200
'TO THE FILE
'CLOSES THE FILE
FCHAINS TO THE NEXT
) SEGMENT
IFRINTS IDENTIFYING MESSAGE
OPENS EXISTING FILE
NINFUTS THE NUMBERS
IFROM THE FILES
AND ADDS THEM TOGETHER
ISTORING THE TOTAL IN T
IPRINTS THE TOTAL
ICLOSES INFUT FILE
If the specified file does not exist, BASIC prints an error message. To allow the error recovery, BASIC does not
erase the current program lines, variables, or arrays. However, all files are closed as they normally would be.
Remember to SAVE a program containing a CHAIN statement before running it, otherwise, the program will erase
itself from memory.
11.2.1 Preserving Variables — The COMMON Statement’
The COMMON statement preserves data passed from one segment of a program to another. Data values associated
with the names of items in the COMMON statement are placed in a common area. The value assigned will be
retained when you transfer control from one segment of a program to another with the CALL statement.
COMMON defines an area that is available to any subprogram that defines it. Thus names need not be the same in
all routines that access a given COMMON block.
The format of the COMMON statement is:
COM [MONT] [[(name)]] list
he COMMON statement is not available on the DECSYSTEM-20 in Version 1.
Program Segmentation
where:
(name) is an optional name for the storage block. The name can be 1 to 6 characters.
list specifies the variables and arrays to be preserved in COMMON. Tt is in the general form:
var [[ (int [[-in«[}[}- var[(int[ Lint J]. ..
The value of each variable in a global common area is position dependent. Therefore, the COMMON statements in
the program CALLED must specify the same variable types and array dimensions. The line numbers, variable
names, and arrays of cach COMMON statement can be different from the original program. But the order of the-
variables and arrays must be maintained.
Consider these examples:
MAIN Subprogram 1 Subprogram 2
10 COMMON ArB:Cs 10 COMMON A»EB 10 COMMON ABZ (100)
20 COMMON DX(100) 20 COMMON C$
30 COMMON G$C2) 30 COMMON C$ IZ (100)7G$(2) 30 COMMON Gs(2)
MAIN and Subprogram 1 have cquivalent COMMON statements. Subprogram 2 has a different order of variables;
D% (100) appears before CS.
It is possible to extend COMMON by placing additional variables and arrays after the existing ones. For example,
MAIN Subprogram
10 COMMON ABZ (100) 10 COMMON AsBZ(100)
20 COMMON G$(5) 20 COMMON C$(5)yF9 100)
30 COMMON A$C30)
The subprogram has the equivalent COMMON statements and has extended the original COMMON with F9(100)
and A$(30).
COMMON lists from all COMMON statements with the same name in a program segment are collected into a global
common area with that name. The order in which the COMMON list appears textually determines the order of the
list in the global arca.
The variables in a COMMON list retain their values until an END statement is executed.
BASIC automatically dimensions arrays that are in COMMON. Therefore, if an array is in COMMON, do not
dimension it with a DIM statement. If an array is in both a COMMON and a DIM statement, BASIC prints an
error message and stops program execution.
If more than one common block is used in a program, all declarations for one block must appear together before
any declarations for another common block. For example:
LEGAL ILLEGAL
10 COM (ELOCKNAME) AsE 10 COM (BLOCKNAME) AsE
20 COM (BLOCKNAME) С 20 COM X
30 COM X 30 COM (BLOCKNAME) C
Variables that you declare in COMMON statements cannot be referenced before the COMMON statements that
declare them.
11-6
APPENDIX A
SUMMARY OF BASIC-PLUS-2
STATEMENTS, FUNCTIONS, AND OPERATORS
This appendix summarizes the BASIC-PLUS-2 statements, functions, and operators. The descriptions contain state-
ment format, examples, and brief notes on statement usage. Section numbers are listed for quick reference.
STATEMENTS
CALL 11.1.1
CALL name [[ (actual arguments) |]
200 CALL SUE! (A,B)
The CALL statement transfers control to a specified subprogram, transfers parameters, and saves the state of the
calling program. Parameters contained in the argument list must agree in type and number with the corresponding
SUB statement.
CHAIN 11.2
CHAIN string [[ LINE line number [|
15 CHAIN “SEE” LINE 70
The CHAIN statement passes control to a specified program. If no line number is specified, execution starts at the
beginning of the program.
CHANGE 7.4.4
CHANGE list TO string variable
or
CHANGE j string variable TO list
{ string expression
25 CHANGE A TO AS
The CHANGE statement converts a list of integers (real numbers are truncated) into a string of characters and vice
versa. The length of the string is determined by the value found in element 0 of the list.
CLOSE 9.2.2
CLOSE [+ || expression(s)
150 CLOSE 76,8
The CLOSE státement terminates I/O to a device and writes all active buffers. The number sign and file expressions
are optional. When no files are specified, all files currently open are closed.
A-1
Summary of Basic-Plus-2 Statements, Functions, and Operators
COMÍ[MON ]] 11.2.1 _
COM (| (name) [] list
50 COM (TEST) A,B,C
The COM, or COMMON statement allows you to establish a named storage area that can be shared by 2 or more sub-
programs. The variables and arrays in the variable list are assigned to the named area and, when accessed by more
than 1 subprogram, must be of the same data type. The common area name must be 1 to 6 characters.
DATA 3.1.3
DATA constant(s)
50 DATA 4,3, “string”, 18, 42%
The DATA statement allows you to provide a pool of information that is accessible to the program by means of a
READ statement. A DATA statement must be the only statement on the line and, when you specify more than one
item, you must separate them with commas. DATA statements cannot be continued. A
DEF (single-line) 7.6.1
DEF FNa [[(61,b2,b3, .. .bn) [|=expression
10 DEF FNX (A,B)=A*B
The DEF statement establishes a user-defined function. The function name can be any legal variable name and must
begin with FN. The variable type determines the function type. The optional arguments represent dummy param-
eters and cannot contain array elements. The function definition can refer to any of the dummy parameters or to
other program variables but the definition cannot be recursive. Single-line user-defined functions are local to the
main program or subroutine in which they are contained.
DEF (multi-line) 7.6.2
DEF FNa [[(b1,b2,63,.. .bn)]], [[e1,c2,03, сп |]
10 DEF FNX (A,B), C
The multi-line DEF establishes user-defined functions and allows you to include other statements in the body of the
function. The function name can be any variable name preceded by FN. Any statement can appear in a function ame
except SUB, SUBEND, RETURN or another DEF. The DATA and DIM statements are not local to the function
definition. A GOTO, GOSUB, ONGOTO, or ONGOSUB transfer outside the function is not allowed. The function
definition must end with an FNEND statement.
DEF* (multi-line) 7.6.3
DEF* FNa[[ (b1,b2,b3, .. .bn)]], [[с1,с2,с3, . . .cn]]
10 DEF* FNZ%
This statement has been added for compatibility with other BASICs. The distinguishing asterisks appear only in the
DEF statement and not in program references to the function. The statement permits global references to function
parameters and places parameter values in global locations. Transfers are allowed into and out of DEF* functions;
however, random transfers can produce unpredictable results. If you transfer out of the function, be sure to transfer
in and exit through the FNEND statement.
A,
А-2
fir BEER TY:
Summary of Basic-Plus-2 Statements, Functions, and Operators
DELETE 10.3
DELETE file exp [INVALID line no. J]
60 DELETE #5, INVALID 500
The DELETE operation is used on relative and indexed files. The operation erases an existing record from the file.
The INVALID clause shifts control to an error-handling routine if the operation fails.
DIM[[ENSION ]] 2.6.1
DIM subscripted variable(s)
30 DIM B(2,3)
The DIM statement reserves storage for arrays. The size of the reserved storage is determined by the subscripts, (con-
stant). A maximum of 2 subscripts is permitted and, when 2 are used, must be separated by a comma.
DIM # 9.3.1
DIM # expression, array(s) [[Finteger J]
50 DIM #2, A(10,15), B(50)
This statement allocates space for the specified arrays on the file associated with the logical number. Storage is al-
located at the beginning of the file such that the right most subscript varies the fastest. The default string storage
length is 16 and the space is pre-allocated.
END 5.4
END
100 END
The END statement trerminates program execution and closes all files. It is optional. When used, END must be the
last statement in the program.
FIND 10.3
FIND file exp [[,RECORD num exp |]
GT
[| KEY # num expr 4 GE > string exp 1
[Loc KED line no. ]] [INVALID line no. ]]
50 FIND #7, RECORD 25, LOCKED 120
The FIND operation causes a RECORD search in the specified file. For sequential files, the FIND starts at the
beginning of the file and locates each successor record for each FIND operation. Relative files allow the specifica-
tion of a record number. Indexed files allow the specification of a key or a sequential search through the key
table. The RECORD and KEY specifications are restricted to relative and indexed files.
FNEND 7.6
FNEND
40 FNEND
The FNEND statement causes an exit from a user-defined function and signals the function’s logical and physical end.
Summary of Basic-Plus-2 Statements, Functions, and Operators
FNEXIT 7.6 ре
FNEXIT
70 FNEXIT
The FNEXIT statement is equivalent to a GOTO n, where niis the line number of the FNEND statement for the cur-
rent multi-line DEF. FNEXIT is legal only inside a multi-line DEF.
FOR 5.2.1
FOR variable=num expt TO num exp2 [| STEP num exp3]]
25 FOR I=1 TO 5 STEP 2
The FOR statement initiates and controls a loop. A simple numeric variable must be used after the FOR, and the
same variable must appear in the required NEXT statement. The first numeric expression is the initial loop value;
the sccond expression is the terminating loop value. The optional STEP expression is the loop increment; +1 is the
default. Transfer into an uninitialized loop is illegal. mi.
FOR (conditional) 5.2.3
FOR variable=num expl [| STEP num exp2]] WHILE conditional exp
UNTIL
80 FOR 1=1 UNTIL I>10
The conditional FOR statement duplicates the previous FOR statement except that loop termination is determined
by a false expression in the WHILE clause or a true expression in the UNTIL clause.
ME.
GET 10.3
GE
GET file exp [[ KEY # num exp GT “ string exp |]
EQ
‚RECORD num exp
‚LOCKED line no. ]] INVALID line no-T
50 GET #5
a“.
The GET operation reads a record from a specified file into a buffer. On sequential files, GET operations are per-
formed on succeeding records starting at the beginning of the file. Relative files allow the specification of a record
number, and indexed files allow the specification of a key name.
GOSUB 5.5.1
GOSUB line number
25 GOSUB 120
The GOSUB statement transfers contro! to a subroutine that begins at a specified line number.
GOTO 5.1.1
GOTO line number
40 GOTO 85
The GOTO statement unconditionally transfers control to a specified line number.
SORIA Aaa =
Summary of Basic-Plus-2 Statements, Functions, and Operators
1 5.1.3
IF conditional exp THEN line number
GOTO
IF conditional exp THEN statement(s)
IF conditional exp THEN line number ELSE ) line number
GOTO statement(s)
IF conditional exp THEN statement(s) ELSE } line number
statements
25 IF A=0 THEN PRINT “A EQUALS 0”
The various forms of the IF statement allow branches in the program. The IF statement can also cause execution of
statements except the following:
DIM, REM, DATA, END, DEF, FNEND, SUB, SUBEND, WHILE, UNTIL, NEXT, and IMAGE.
IFEND# 9.2.6
IFEND # expression, ) THEN statement
GOTO ) line number
25 IFEND # 6 THEN 50
The IFEND # statement checks for the end of file. If the file pointer is at the end of the file, you can transfer con-
trol to another line of the program ot execute a statement.
IFMORE 9.2.7
[FMORE # expression, ) THEN | statement
GOTO line number
10 IFMORE 5 7 GOTO 100
The ¡FMORE + statement tests whether the file pointer is at the end of file. If NOT at the end, BASIC executes the
statement or goes to the line number specified.
IMAGE N 45
IMAGE vnquoted string
‘unquoted string
10 : HHH Tar. Я
The IMAGE stateme nt is used in | conjunction with the PRINT USING statement. The characters following the colon,
or keyword IMAGE, define the format of output. IMAGE must be the only statement on the line and cannot con-
tain comments.
INPUT 3.1.1
INPUT variable(s)
25 INPUT A,B,C%
The INPUT statement allows you to type in data to the program from the terminal. The program requests data by
printing a question mark on the terminal and then waiting for you to respond.
Summary of Basic-Plus-2 Statements, Functions, and Operators
INPUT # 9.2.3
INPUT # expression, variable(s)
25 INPUT #6, A,B,C
The INPUT # statement acts very much as the INPUT statement. However, the INPUT # statement requests data
from a terminal-format file rather than from you.
INPUT LINE and LINPUT 3.1.2
INPUT LINE string variable(s)
LINPUT string variable(s)
15 INPUT LINE AS, BS
The INPUT LINE statement allows a character string (ending with a line terminator) to be input to a specified vari-
able. The line terminator is included in the string with INPUT LINE but discarded with LINPUT.
INPUT LINE # and LINPUT # 9.2.3.1
INPUT LINE # expression, string variable(s)
LINPUT # expression, string variable(s)
10 INPUT LINE +4, AS, B$
The INPUT LINE # and LINPUT # statements read strings from a terminal-format file.
KILL 9.4.2
KILL string expression
10 KILL “SALARY”
The KILL statement deletes a file from storage.
LET 2.5
LET variable(s)=expression
variable(s)=expression
10 A=65
The LET statement assigns constants and expressions to variables. The keyword LET is optional.
LINPUT 3.1.2
See INPUT LINE
LINPUT # 9.2.3.1
See INPUT LINE +
А-6
Summary of Basic-Plus-2 Statements, Functions, and Operators
MAP 10.1.4
MAP (name) ALIGNED element(s)
UNALIGNED
10 MAP (Buffl) A%, BS, C
The MAP statement associates a named buffer with a file. Specified data in the element list is moved from the file to
the buffer on a GET and from the buffer to the file on a PUT.
MARGIN en en ce A В a 9.2.9
MARGIN [espion] ч num exp ER
er
10 MARGIN 5 o
>
The MARG IN statement. allows y you to modify the margin of y your terminal or terminal format file,
MAT INPUT 8.4.1
MAT INPUT array(s)
50 MAT INPUT A
The MAT INPUT statement allows element values to be entered in an array. Input is read from the terminal. Ele-
ments are stored in row order as they are typed.
MATRIX OPERATIONS 8.3
MAT PRINT 8.4.2
MAT PRINT array(s)
120 MAT PRINT A;
The MAT PRINT statement outputs each element of a specified array.
MAT READ 8.4.3
MAT READ array(s)
50 MAT READ B,C
The MAT READ statement reads the values into elements of a 1- or 2-dimensional array from a DATA statement.
MOVE 10.3.4
MOVE ALIGNED FROMU file exp, I/O list
UNALIGNED TO
15 MOVE TO #5, A$, B, C( ), FILL%
The MOVE statement associates the data in a record with the variables you specify in the 1/0 list.
NAMEAS 9.4.1
NAME stringl AS string?
15 NAME “MONEY” AS “ACCNTS”
The NAME-AS statement renames a file without changing the contents of the file or the file number associated with it.
A-7
Summary of Basic-Plus-2 Statements, l'unctions, and Operators
NEXT 5.2.1
NEXT variable(s)
15 NEXTI
The NEXT statement terminates a FOR, WHILE, or UNTIL loop. The variable must correspond with the variable in
the initial FOR statement. Nested loops cannot cross cach other.
NODATA | ВЕ —. 9.2.8
1 — NODATA [[#expression,[] line number
BASIC checks for the end of file (or data in a DATA statement) and goes to line number specified if no data is left. |
ONERROR 5.6.1
ONERROR GOTO line number
25 ONERROR GOTO 50
The ONERROR statement allows control to shift to an error-handling routine.
ON-GOSUB 5.5.2
ON num exp GOSUB line number(s)
50 ON A+B GOSUB 80, 95, 100
The ON GOSUB statement is used to conditionally transfer control to one of several subroutines or to one of several
entry points into one or more subroutines.
ON-GOTO 5.1.2
ON num exp GOTO line number(s)
THEN
20 ON J% GOTO 85
The ON-GOTO statement allows you to transfer control to another line of the program.
ON-THEN 5.1.2
See ON-GOTO
OPEN 9.2.1 Terminal-Format
9.3.2 Virtual Array Files
10.2.1 Record Files
OPEN filename exp [[FOR INPUT
OUTPUT
AS [[FILE]] [[# []expression
OUT nen
, [ORGANIZATION] . VARIABLE
INDEXED STREAM
VIRTUAL
A-8
MRE
Summary of Basic-Plus-2 Statements, Functions, and Operators
(ew on
[ACCESS } monirv (I [LALLOW J READ
. WRITE
SCRATCH MODIFY
APPEND
MAP mapname
,RECORDSIZE num exp
[INVALID line no f] [[ LOCKED line по]
,DOUBLEBUF
BUFFER [#1 num exp
yr
“BLOCKSIZE num exp ]]
Ii { ‚SPAN H
NOSPAN
[| BUCKETSIZE num exp ]]
[| CLUSTERSIZE num exp]]
[PRIMARY [Keyfname]] oa ATES |
DUPLICATES
[ALTERNATE [[KEY]name IK NODUPLICATES + | NOR H
DUPLICATES CHANGES
10 OPEN “FILE” FOR INPUT AS FILE 4
The OPEN statement enables you to create a new file or access an existing file. You can use the OPEN statement to
access terminal-format files as well as record files.
(PAGE a ELA A 9210
PAGE y Even] num NP a o a T4
Red da Y Bel aaa .
Ne cs so фе! $ . - | JE TED N “ Bose. ; > a o o
+
| The PAGE statement allows you to set a a PAGE : size of. any positive number of lines.
PRINT 3.2
PRINT [[ expression(s) J]
30 PRINT A+B
The PRINT statement causes the data you specify to be output on the terminal. The expression list can be expres-
sions, variables, or quoted strings separated by a comma or a semicolon. Commas cause output to terminal print
zones; semicolons ignore the print zones.
PRINT # 9.2.4
PRINT # expression, list
65 PRINT # 6, A, B+C
The PRINT # statement writes data into the specified terminal-format file.
A-9
Summary of Basic-Plus-2 Statements, Functions, and Operators
PRINT USING 4.1
PRINT USING string, list
10 PRINT USING “**## £##”, A,B,C
The PRINT USING statement causes output to be printed in a specified format. The list indicates the elements to be
printed and the image can be a line reference to an IMAGE statement.
PUT 10.3
PUT file exp [| RECORD num exp]]
MAP line no.
‚COUNT num exp
[LLOCKED line по. []
[INVALID line no]
25 PUT #7, RECORD 15
The PUT statement writes a record from a buffer to a specified file. The RECORD clause is used for relative files:
the KEY clause is used for indexed files. Sequential files allow PUT operations only at the end of the file. The MAP
and COUNT clauses define the size of the record.
RANDOMIZE 7.2.3
RANDOM{[ZE ]]
10 RANDOM
The RANDOMIZE statement changes the starting point of the RND function to a new unpredictable location.
READ 3.1.3
READ variable(s)
75 READ A,B%,C$, D(5)
The READ statement directs BASIC to read from a list of values built into a data block by a DATA statement.
REM 1.4
REM comment
30 REM this is a comment
The REM statement contains user written comments and has no effect on program execution.
RESTORE [[#]] (or RESET) 3.1.3
9.2.5
10.2.3
RESTORE # expression
30 RESTORE #3
The RESTORE # statement resets the specified terminal-format file or record file to its beginning from the current
position of the file. Restore without a file exp restores the data in a DATA statement.
A
Summary of Basic-Plus-2 Statements, Functions, and Operators
RESUME 5.6.1
RESUME [ine number |]
50 RESUME 35
The RESUME statement is the last statement in an error-handling subroutine. If no line number is specified, control
is shifted back to the point of error generation. If a line number is specified, control is shifted to that line.
RETURN 5.5.1
RETURN
60 RETURN
The RETURN statement is the last statement in a subroutine. It shifts control to the statement following the last
executed GOSUB statement.
SCRATCH 10.2.2.1
SCRATCH ffile exp
25 SCRATCH #6
The SCRATCH statement allows you to truncate the file. SCRATCH can only be used if the file was OPENed
with ACCESS SCRATCH.
SLEEP 5.3.1
SLEEP num exp
10 SLEEP A*B
The SLEEP statement causes a temporary halt in exccution. The length of delay is determined by the value of
the expression in seconds.
STOP 5.4
STOP
110 STOP
The STOP statement causes a halt in program execution. Files are not closed and a message indicating the loca-
tion of the halt is printed.
SUB 11.1
SUB name [ (dummy argument(s)) ]]
40 SUB TEST (A,B%)
The SUB statement marks the beginning of a subprogram and defines the type and number of subprogram
parameters.
SUBEND 11.1
SUBEND
25 SUBEND
The SUBEND statement marks the end of the subprogram and returns control to the calling program. It must
appcar at the end of all subprograms.
A-11
Summary of Basic-Plus-2 Statements, Functions, and Operators
SUBEXIT | 11.1
SUBEXIT
45 SUBEXIT
The SUBEXIT statement returns control to the calling program. It has the same effect as GOTO n, where n is
the line number of the appropriate SUBEND statement. SUBEXIT is legal only inside a subprogram.
UNTIL 5.2.4
UNTIL conditional exp
50 UNTIL 1=0
The UNTIL statement sets up a loop that must have a corresponding NEXT statement. The loop executes until
the expression is true.
UPDATE 10.3
UPDATE file exp [ MAP line no.
‚COUNT exp
— INVALID line no. Jj
+
The UPDATE statement changes an existing record in the file. The new record size as defined in the MAP or
COUNT clause, must be the same as the record it replaces. On sequential files, an UPDATE must be preceded
by a successful GET or FIND.
WAIT 5.3.2
WAIT num exp
40 WAIT 15
The WAIT statement specifies the maximum number of seconds allowed for input before an error is generated. A
zero or null value disables the WAIT.
WHILE 5.2.4
WHILE conditional exp
75 WHILE A%<10%
The WHILE statement also sets up a loop that must have a NEXT statement. The WHILE expression is evalu-
ated before each loop iteration. If the cxpression is true, BASIC executes the statements in the loop. If the
expression is false, BASIC executes the statements following the NEXT statement.
A-12
Mm
Function
ABS(x)
ASCII(xS)
ATN(x)
CHRS(x%)
CLKS
COS(x)
DATS
DATES(0%)
DATES(x%)
EDITS(string,n%)
EXP(x)
FIX(x)
INSTR(z%,x$vS)
INT(x)
LEFTS(x$ y%)
LEN(x$)
LOG(x)
LOG10(x)
MID(string,n1%,n2%)
‘MOD(x,y)
MOD%(x Y)
PI
POS(x$ y $,77%)
RADS(x%)
RIGHTS(x$,y%)
RND
Summary of Basic-Plus-2 Statements, Functions, and Operators
FUNCTIONS
Usage
returns absolute value of x.
returns the decimal ASCII value of the first character of a specified string.
returns the arctangent of x in radians.
returns the character equivalent of the ASCII value x%.
returns an 8-character string representing the time of day (hh:mm:ss)
returns the cosine of x.
returns an 8-character string representing the current date (dd-mm-myy).
returns the current date in the form mm/dd/yy.
returns the date according to the formula; x = day of the year + (years since
1970* 1000) in the form dd-mmm-yy.
converts a string according to integer specified in table.
returns value of ex where 3=2.71828.
returns truncated value of x.
returns the position of substring y$ in main string x3 starting at position z%.
returns the integral part of x.
returns a substring of x$ beginning at the leftmost position for a total length of y
characters. (Also LEFT(x$,y%)).
returns the number of characters in x$.
returns the natural logarithm of x.
returns the common logarithm of x.
returns a substring of string starting at position n1% with n2% characters.
— returns the real result of x mod y, which is equal to x-y*INT(x/y).
returns the integer result of x mod y, which is the remainder of x/y.
constant value, 3.14159
returns the position of substring y $ in main string x$ beginning of position z.
(See also INSTR)
converts the integer x% to its RADIX-50 equivalent.
returns a substring of x$ that ranges from the yth character to the end of the string.
(Also, RIGIT(x$,y%)).
returns a random number between 0 and 1.
Function
SEGS(x$,v% 7%)
SGN(x)
SIN(x)
SPACES(x)
SQR(x)
STR$(x)
STRINGS(x% y%)
TAB(x%)
TAN(x)
TIMES(x%)
TIMES(0%)
TIME(0)
TIME(1%)
TIME(2%)
VAL(x$)
Summary of Basic-Plus-2 Statements, Functions, and Operators
Usage
returns a substring of x$ that ranges from the yth character to the xth character.
returns 1 if x is positive; O if x is zero;- 1 if x is negative.
returns the sine of x in radians.
produces a string of x spaces.
returns the square root of x; also SQRT(x).
returns the value of an expression without the leading and trailing blanks. (Also
NUM$(x)).
creates a string of x length whose characters represent the ASCII value of y.
moves the print head to the xth position.
returns the tangent of x in radians.
returns time as x minutes before midnight.
returns current time.
returns clock time in seconds since midnight.
returns used CPU time in tenths of seconds.
returns connect time in minutes.
computes the numeric value of the numeric string x$; x$ must be acceptable numeric
input.
Table A-1 Arithmetic Operators
Operator Use Meaning
^ ог ** 572 or 5**2 exponentiation
* А*В multiplication
/ A/B division
+ A+B addition
- А-В subtraction, unary
minus
Sil ddim ¡ba e
Summary of Basic-Plus-2 Statements, Functions, and Operators
Table A-2 Logical Operators
Operator Use Meaning
NOT NOT A logical negative of A
AND À AND B logical product of A and B
OR AORB logical sum of A and B
XOR A XOR B logical exclusive OR of A and B
EQV A EQVB A is logically equivalent to B
IMP A IMP B logical implication of A and B
Table A-3 Relational Operators
Operator Use Meaning
= A= A is equal to B
< A<B А is less than B
> A>B A is greater than B
<= or =< A<=B Á is less than or equal to В
>= or => A>=B A is greater than or equal to B
# or <> Or >< A<>B A is not equal to B
== ==B A is approximately cqual to B
+,& A$+B$ string concatenation
Note that A is approximately equal to B (A==B) if the difference between A and B is less
than 10(-6). If A$ and BS are strings, the relation (==) is true if the contents of AS and
B$ are the same in length and composition.
A-15
#li ENEE REL TE DEN AA SE
AMEN
MR,
ABE,
Table B-1 ASCII T">
/
Download
Apenas um lembrete amigável. Você pode visualizar o documento aqui mesmo. Mas o mais importante, nossa IA já o leu. Ele pode explicar coisas complexas em termos simples, responder às suas perguntas em qualquer idioma e ajudá-lo a navegar rapidamente, mesmo nos documentos mais longos ou complicados.
Anúncio