0% found this document useful (0 votes)
35 views

Applesoft BASIC Programmers Reference Manual

Uploaded by

nfuria
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Applesoft BASIC Programmers Reference Manual

Uploaded by

nfuria
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 371

Applesoft BASIC

Programmer's Reference Manual



Addison-Wesley Publishing Company, Inc.


Reading, Massachusetts Menlo Park, California New York Don Mills,
Ontario Wokingham, England Amsterdam Bonn Sydney Singapore
Tokyo Madrid Bogota Santiago San Juan
Copyright © 1986, 1987 by Apple Computer, Inc.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system,
or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or
otherwise, without prior written permission of Apple Computer, Inc. Printed in the United States
of America.

This manual was written for Apple Computer, Inc. by

Scot Kamins
Technology Translated, Inc.
San francisco, California

Apple, the Apple logo, and ProDOS are registered trademarks of Apple Computer, Inc.

Simultaneously published in the United States and Canada.

ISBN 0-201-17756-0
ABCDEFGHIJ-DO-8987
First printing, July 1987

WARRANTY INFORMATION
ALL IMPLIED WARRANTIES ON THIS MANUAL, INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE, ARE LIMITED IN DURATION 'IO NINETY (90) DAYS FROM THE DATE OF THE ORIGINAL RETAIL
PURCHASE OF THIS PRODUCT.

Even though Apple has reviewed this manual, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER
EXPRESS OR IMPLIED, WITH RESPECT 'IO THIS MANUAL, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR fflNESS FOR A
PARTICULAR PURPOSE. As A RESULT, THIS MANUAL IS SOLD "AS IS;' AND YOU, THE PURCHASER, ARE ASSUMING THE
ENTIRE RISK AS 'IO ITS QUALITY AND ACCURACY.

IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
RESULTING FROM ANY DEFECT OR INACCURACY IN THIS MANUAL, even if advised of the possibility of such
damages.

THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL <JI'HERS, ORAL OR WRIITEN,
EXPRESS OR IMPLIED. No Apple dealer, agent or employee is authorized to make any modification,
extension, or addition to this warranty.

Some states do not allow the exclusion or limitation of implied warranties or liability for in­
cidental or consequential damages, so the above limitation or exclusion may not apply to you.
This warranty gives you specific legal rights, and you may also have other rights which vary
from state to state.
Applesoft BASIC
Programmer's Reference Manual
Contents

Figures and Tables xvii

PREFACE About This Manual xxi


Purposes of This Manual xxi
How This Manual Is Organized xxi
How to Use This Manual xxiv
As a Reference xxiv
To Learn the Applesoft Language xxv
To Learn Program Planning xxv
Conventions Used in This Manual xxv
Where to Learn More xxvi

CHAPTER 1 General Information 1


1.1 Statements, Lines, and Programs 2
1.1.1 Immediate Execution 3
1.1.2 Line Numbers and Deferred Execution 4
1.1.3 Adding Lines to a Program 4
1.1.4 Multiple Statements on the Same Line 4
1.1.5 Deleting Lines From a Program: The DEL Command 5
1.1.6 Changing Lines in a Program 6
1.1.7 Annotating a Program: The REM Statement 6

iv Contents
1.2 Operations on Whole Programs 7
1.2.1 The NEW Command 7
1.2.2 The CLEAR Command 8
1.2.3 The LIST Command 9
1.2.4 The RUN Command 10
1.2.5 The SAVE Command 11
1.2.6 The WAD Command 12
1.3 Interrupting and Resuming a Program 13
1.3.1 Suspending Screen Output 13
1.3.2 Interrupting Program Execution 14
1.3.2.1 CONTROL-C 14
1.3.2.2 CONTROL-RESET 14
1.3.3 Resuming Program Execution: The CONT Command 15
1.4 Editing What You Type 16
1.4.1 Canceling an Input Line 16
1.4.2 The Arrow Keys 17
1.4.3 Escape Mode 18

CHAPTER2 Variables and Arithmetic 21


2.1 Variables 22
2.1.1 Variable Names 23
2.1.2 Real Variables 24
2.1.3 Integer Variables 25
2.1.4 String Variables 25
2.1.5 Arrays: Collections of Variables 26
2.2 Assigning Values to Variables: The Assignment Statement 27

Contents V
2.3 Expressions 28
2.3.1 Arithmetic Operators 29
2.3.2 Relational Operators 30
2.3.3 Logical Operators 32
2.3.4 Precedence of Operators 33
2.4 Functions 35
2.4.1 Built-in Arithmetic Functions 35
2.4.1.1 The ABS Function 36
2.4.1.2 The SGN Function 36
2.4.1.3 The INT Function 36
2.4.1.4 The SQR Function 37
2.4.1.5 The SIN Function 37
2.4.1.6 The COS Function 37
2.4.1.7 The TAN Function 38
2.4.1.8 The ATN Function 38
2.4.1.9 The EXP Function 38
2.4.1.10 The LOG Function 39
2.4.2 Generating Random Numbers: The RND Function 39
2.4.3 Defining Your Own Functions: The DEF FN Statement 40

CHAPTERS Control Statements 43


3.1 Unconditional Branching: The GOTO Statement 44
3.2 Conditional Branching 46
3.2. 1 The ON... GOTO Statement 46
3.2. 2 The IF...THEN Statement 47

vi Contents
3.3 Loops 50
3.3.1 The FOR Statement 52
3.3.2 The NEXT Statement 53
3.3.3 Nesting of Loops 54
3.4 Subroutines 55
3.4.1 The GOSUB Statement 59
3.4.2 The RETURN Statement 59
3.4.3 The ON...GOSUB Statement 59
3.4.4 The POP Statement 60
3.5 Error Handling 61
3.5.1 The ONERR...GOTO Statement 61
3.5.2 The RESUME Statement 65
3.5.3 Restoring Normal Error Handling 65
3.6 Program Termination 57
3.6.1 The STOP Statement 67
3.6.2 The END Statement 67

CHAPTER4 Arrays and Strings 69


4.1 Arrays 70
4.1.1 The DIM Statement 72
4.1.2 Multidimensional Arrays 72

Contents vii
4.2 Strings 74
4.2.1 Comparison of Strings: The ASCII Code 75
4.2.2 The LEN Function 76
4.2.3 Concatenation of Strings 77
4.2.4 Substring Functions 79
4.2.4.1 The LEFT$ Function 79
4.2.4.2 The MID$ Function 80
4.2.4.3 The RIGHT$ Function 81
4.2.5 String Conversion Functions 81
4.2.5.1 The STR$ Function 82
4.2.5.2 The VAL Function 82
4.2.5.3 The CHR$ Function 83
4.2.5.4 The A$C Function 84

CHAPTER5 Input/Output 85
5.1 Input 86
5.1.1 The IN# Statement 86
5.1.2 The INPUT Statement 88
5.1.2.1 Multiple Inputs on the Same Line 89
5.1.2.2 General Rules for Input 90
5.1.2.3 Rules for String Input 90
5.1.2.4 Rules for Numeric Input 91
5.1.2.5 An "Input Anything" Routine 93
5.1.3 The GET Statement 94
5.1.4 The READ and DATA Statements 96
5.1.5 The RESTORE Statement 98

viii Contents
5.1.6 Miscellaneous Input Facilities 99
5.1.6.1 The Hand Controls 99
5.1.6.2 Cassette Input 100
5.2 Output 101
5.2.1 The PR# Statement 101
5.2.2 The PRINT Statement 102
5.2.3 Number Formats 106
5.2.4 Formatting Text on the Screen 108
5.2.4.1 The Text Window 109
5.2.4.2 The TEXT Statement 109
5.2.4.3 The HOME Statement 109
5.2.4.4 The SPC Function 109
5.2.4.5 The TAB Function 111
5.2.4.6 The HTAB Statement 112
5.2.4.7 The VTAB Statement 113
5.2.4.8 The POS Function 114
5.2.4.9 The INVERSE Statement 115
5.2.4.10 The FLASH Statement 115
5.2.4.11 The NORMAL Statement 116
5.2.4.12 The SPEED= Statement 117
5.2.5 Miscellaneous Output Facilities 118
5.2.5.1 Controlling the Speaker 118
5.2.5.2 Annunciator Output 119
5.2.5.3 The Utility Strobe 119
5.2.5.4 Cassette Output 119

Contents ix
CHAPTER6 Graphics 121
6.1 Low-Resolution Graphics 122
6.1.1 The GR Statement 122
6.1.2 The COLOR= Statement 123
6.1.3 The PLOT Statement 125
6.1.4 The HLIN Statement 127
6.1.5 The VLIN Statement 128
6.1.6 The SCRN Function 129
6.2 High-Resolution Graphics 130
6.2.1 The HGR Statement 130
6.2.2 The HGR2 Statement 131
6.2.3 The HCOLOR= Statement 133
6.2.4 The HPLOT Statement 134
6.2.5 Protecting High-Resolution Graphics 137
6.3 Shape Tables 138
6.3.1 Creating a Shape Table 138
6.3.1.1 Plotting Vectors 139
6.3.1.2 How Plotting Vectors Are Interpreted 140
6.3.1.3 Coding a Shape Table 140
6.3.1.4 The Shape Table Index 144
6.3.1.5 Loading a Shape Table Into Memory 146
6.3.1.6 Saving and Loading a Shape Table 149

X Contents
6.3.2 Using Shape Tables 151
6.3.2.1 The DRAW Statement 152
6.3.2.2 The XDRAW Statement 153
6.3.2.3 The SCALE= Statement 154
6.3.2.4 The ROT= Statement 155
6.3.2.5 The SHLOAD Statement 156
6.4 Graphics in Text Mode (MouseText) 158

CHAPTER 7 Utility Statements 161


7.1 System Utilities 162
7.1.1 The PEEK Function 162
7.1.2 The POKE Statement 163
7.1.3 The CALL Statement 164
7.1.4 The USR Function 165
7.1.5 The WAIT Statement 166
7.2 Memory Management 168
7.2.1 The HIMEM: Statement 168
7.2.2 The LOMEM: Statement 170
7.2.3 The FRE Function 171
7.3 Debugging Facilities 172
7.3.1 The TRACE Command 173
7.3.2 The NOTRACE Command 174

Contents xi
CHAPTERS Programming: Bringing It All Together 175
8.1 Planning the Program 176
8.1.1 Program Specification 176
8.1.1.1 What the Program Needs 176
8.1.1.2 What the Program Will and Won't Do 177
8.1.1.3 Validating the Data 178
8.1.1.4 Displaying the Results 179
8.1.1.5 Final Specifications 179
8.1.2 Program Layout 180
8.1.2.1 The Initial Layout 180
8.1.2.2 Refining the Layout 181
8.2 Writing the Code 183
8.2.1 Preliminaries 184
8.2.2 Display the Menu 184
8.2.3 What's the Postage Class? 185
8.2.4 What Does It Weigh? 186
8.2.5 Compute the Charge 187
8.2.6 Display the Results 188
8.2.7 Calculating Routines 188
8.2.8 Consistency-Checking Routines 190
8.2.9 The Keystall Routine 192
8.2.10 The Formatting Routine 193
8.3 Final Advice to the New Programmer 193

xii Contents
APPENDIXA Summary of Applesoft Statements and Functions 195

APPENDIXB Syntax Definitions 221

APPENDIXC ASCII Character Codes 227

APPENDIXD Reserved Words 231

APPENDIXE Error Messages 235


E.1 Error Messages by Number 237
E.2 Alphabetical List of Error Messages 237

APPENDIXF Peeks, Pokes, and Calls 243


F.1 Screen Text 244
F.1.1 Setting the Text Window 245
F.1.2 Text in Windows 246
F.1.3 The Cursor in Windows 248
F.2 Keyboard 249
F.3 Graphics 250
F.3.1 Switching Graphics Screens 251
F.3.2 Clearing Graphics Screens 253

Contents xiii
F.4 Miscellaneous Input and Output 254
F.4.1 Hand Controls and Strobe 254
F.4.2 Annunciators 255
F.4.3 Loudspeaker 256
F.5 Error Handling 257

APPENDIXG Hints for Program Efficiency 259


G.1 Saving Space 260
G.2 Saving Time 263

APPENDIXH Implementation Details 265


H.l Ap ple II Memory Map 267
H.2 Applesoft Memory Allocation 268
H.3 Zero Page Use 271
H.4 Keyword Tokens 274

APPENDIX I Display Formats for Numbers 277

APPENDIXJ On-Screen Editing and Cursor Control 281

APPENDIXK 40/80-Column Display Differences 285

xiv Contents
APPENDIXL Comparison With Integer BASIC 287
L.1 Differences Between Statements 289
L.2 Other Differences 290
L.3 Converting BASIC Programs to Applesoft 291

APPENDIXM If You Have a Cassette Recorder 295

APPENDIXN Complete Listing of the Postage Rates Program 299

APPENDIXO BASIC and the Mouse 307


0.1 Using the Mouse in BASIC 308
0.1.1 Turning the Mouse On 310
0.1.2 Turning the Mouse Off 311
0.2 MOUSE.MOVE 311
0.2.1 MOUSE.MOVE Program Listing 311
0.2.2 How MOUSE.MOVE Works 312
0.3 MOUSE.ORAW 312
0.3.1 MOUSE.ORAW Program Listing 313
0.3.2 How MOUSE.ORAW Works 314

Contents xv
Glossary 317
Index 331
Applesoft BASIC Quick Reference Card
Tell Apple Card

xvi Contents
Figures and Tables

CHAPTER 1 General Information 1


Table 1-1 ASCII Equivalents of Arrow Keys 17
Figure 1-1 Single Cursor Moves 18
Figure 1-2 Long-Range Cursor Moves 19
Table 1-2 Escape-Mode Functions 20

CHAPTER2 Variables and Arithmetic 21


Table 2-1 Variable Types 23
Figure 2-1 A Typical Array 26
Table 2-3 Precedence of Operators 33

CHAPTERS Control Statements 43


Table 3-1 Error Codes 63

CHAPTER4 Arrays and Strings 69


Figure 4-1 A Real Array 71
Figure 4-2 A String Array 71
Figure 4-3 A Two-Dimensional Array 73

Figures and Tables xvii


CHAPTER 5 Input/Output 85
Table 5-1 Number Formats 107
Figure 5-1 Format for Scientific Notation 108

CHAPTER 6 Graphics 121


Table 6-1 Color Codes for Low-Resolution Graphics 124
Figure 6-1 Screen Coordinates for Low-Resolution Graphics 126
Table 6-2 Color Codes for High-Resolution Graphics 133
Figure 6-2 Screen Coordinates for High-Resolution Graphics 135
Figure 6-3 Drawing a Rectangle With HPLOT 135
Figure 6-4 Plotting Vectors in a Byte 139
Figure 6-5 Plotting a Shape 141
Figure 6-6 Codes for Plotting Vectors 142
Figure 6-7 Shape Definition Table 142
Figure 6-8 Converting the Shape Definition to Hexadecimal 143
Table 6-3 Hexadecimal Byte Codes 143
Figure 6-9 Form of a Complete Shape Table 145
Figure 6-10 A Complete Shape Table 146
Figure 6-11 MouseText Characters 159

APPENDIX D Reserved Words 231


Table D-1 Applesoft Reserved Words 233

xviii Figures and Tables


APPENDIX H Implementation Details 265
Table H-1 Apple II Memory Use 267
Figure H-1 Applesoft Memory Map 268
Table H-2 Variable and Array Maps 270
Table H-3 Applesoft Zero Page Use 271
Table H-4 Applesoft Keyword Tokens 274

APPENDIX I Display Formats for Numbers 277


Table 1-1 Number Formats 279
Figure 1-1 Format for Scientific Notation 279

APPENDIX J On-Screen Editing and Cursor Control 281


Figure J-1 Single Cursor Moves 282
Figure J-2 Long-Range Cursor Moves 282
Table J-1 ASCII Equivalents of Arrow Keys 283
Table J-2 Escape-Mode Functions 283

APPENDIX K 40/80-Column Display Differences 285


Table K-1 40/80-Column Display Differences 286

Figures and Tables xix


APPENDIX L Comparison With Integer BASIC 287
Table L-1 Applesoft Features Not Available in Integer BASIC 289
Table L-2 Integer BASIC Features Not Available in Applesoft 289
Table L-3 Applesoft Features Expressed Differently in Integer
BASIC 290

xx Figures and Tables


Preface About This Manual

This is a reference manual for the Applesoft BASIC programming language


as implemented on the Apple® II series of computers. It is intended for
readers who have had some previous experience with programming, either
in BASIC or in some other programming language. It assumes that you are
familiar with the material in the owner's manual for your computer and, if
you are a novice programmer, that you have read theApplesoft Tutorial.

Purposes of This Manual


This manual has four purposes:
□ To serve as a complete reference manual on the Applesoft BASIC
language for the experienced programmer;
□ To provide clear enough explanations and examples so that a new
programmer can learn the details of any statement quickly and easily;
□ To allow any reader, even one who is not trying to learn Applesoft in
detail, to get a general feel for the language;
□ To provide an introduction to program planning, design, and
development for the programmer-in-training.
This manual is decidedly not a tutorial. Experienced programmers can learn
a great deal about Applesoft by reading it from the first page straight
through to the end, but it wasn't designed to be used that way.

How This Manual Is Organized


This manual has eight chapters, fifteen appendixes, a glossary of terms, and
a quick reference card. All of it is designed to help you get the most out of
Applesoft. Here's a description of what each chapter and appendix is about:

How This Manual Is Organized xxi


□ Chapter 1, "General Information," contains information every Applesoft
programmer needs. It discusses the programming environment in which
Applesoft operates and tells how to create, modify, execute, and store
Applesoft programs.
□ Chapter 2, "Variables and Arithmetic," deals with some of the most
fundamental concepts of Applesoft programming: variables, arithmetic
expressions and operators, arithmetic precedence, Applesoft's built-in
functions, and how to define and use your own functions.
□ Chapter 3, "Control Statements," covers the various statements available
to direct the flow of program execution. It includes information on
unconditional and conditional branching, loops, subroutines, error
handling, and program termination.
□ Chapter 4, "Arrays and Strings," completes the material on variables
begun in Chapter 2. It includes information on the definition and use of
arrays in Applesoft and on the various string manipulation facilities.
□ Chapter 5, "Input/Output," describes Applesoft's facilities for getting
information into and out of programs and for formatting the way
information is presented on the display screen.
□ Chapter 6, "Graphics," tells how to create, change, display, and store low­
and high-resolution graphic designs. There is an extensive discussion on
creating and using shape tables, with examples of animation sequences.
MouseText, a set of graphics you can use in text mode, is also covered.
□ Chapter 7, "Utility Statements," contains information on a variety of
miscellaneous Applesoft facilities for low-level control of the
programming environment: directly accessing specific memory locations,
controlling the limits of program space, and tracing the execution of a
program for debugging purposes.
□ Chapter 8, "Bringing It All Together," is more tutorial than any other
chapter in the manual. It describes and demonstrates a method for
planning, designing, and developing efficient, bug-free (well, relatively
bug-free) programs.
□ Appendix A, "Summary of Applesoft Statements and Functions," gives
an abbreviated description of each Applesoft statement and function,
together with a reference to the chapter, section, or appendix where you
can find more detailed information and examples.
□ Appendix B, "Syntax Definitions," defines terms used in the formal
syntactic definitions of Applesoft statements given in Appendix A. In the
body of the manual, statement syntax is shown by example rather than
by formal definition; most readers can safely avoid the formal definitions
altogether.

xxii Preface: About This Manual


o Appendix C, "ASCII Character Codes," contains a complete listing of the
ASCII characters; it is an adjunct to the comments on ASCII in Chapter 4.
o Appendix D, "Reserved Words in Applesoft," is a list of words (some of
them rather odd-looking) that cannot be used in variable names.
o Appendix E, "Error Messages," describes the meanings of the error
messages that Applesoft displays on the screen. Each description
includes an explanation of why the error occurred; in some cases, there
are suggestions for debugging.
o Appendix F, "Peeks, Pokes, and Calls," deals with low-level access to
features of the Apple II computer via Applesoft's PEEK function and
POKE and CALL statements. There are sections on screen text, the
keyboard, graphics, miscellaneous input and output, and error handling.
o Appendix G, "Hints for Program Efficiency," offers techniques for cutting
down the size of programs and for speeding up program execution.
o Appendix H, "Implementation Details," contains information of interest
mainly to the advanced programmer. Included here is a memory map
with a list of pointers and their descriptions, information on Applesoft's
methods of internal storage allocation, an outline of its usage of special
locations in page O of memory, and a list of the tokens it uses for internal
representation of keywords.
o Appendix I, "Display Formats for Numbers," describes how Applesoft
displays numbers on the screen, and gives the ranges of numbers the
system is capable of handling.
o Appendix J, "On-Screen Editing and Cursor Control," contains tables
summarizing Applesoft's on-screen editing features.
o Appendix K, "40/80-Column Display Differences," is a table showing the
differences in Applesoft's behavior when it is displaying 80 as opposed to
40 columns of text.
o Appendix L, "Comparison With Integer BASIC," gives charts showing the
differences between Applesoft and Apple Integer BASIC and discusses
how to convert Integer BASIC and non-Apple II BASIC programs into
Applesoft.
o Appendix M, "If You Have a Cassette Recorder," describes Applesoft's
statements for using tape cassettes as a storage medium for programs
and information. This applies only to the Apple II, Apple II Plus, and
Apple Ile.
o Appendix N, "Complete Listing of the Postage Rates Program," gives the
complete text of the programming example developed in Chapter 8.
o Appendix 0, "BASIC and the Mouse", shows how to take advantage of
the optional mouse accessory in BASIC programs.

How This Manual ls Organized xxiii


At the back of the manual is a glossary of technical terms. In general, buzz
words are no-no's in this manual; but any technical field has its own jargon,
developed out of necessity to describe concepts genuinely having no parallel
in common language. The glossary lists all such words and terms that have
found their way into the manual, and a few others besides. When you run
across a term you're not familiar with, look it up in the glossary.
A tear-out quick reference card, designed to act as a memory aid, gives an
extremely brief description of each statement, function, operator, and
variable type in Applesoft BASIC.

How to Use This Manual


Here are some suggestions on how to use this manual, depending on what
you want to accomplish.

As a Reference Book
There are several ways you can use this book as a reference:
□ Look up the feature of interest on the quick reference card; each
statement, function, operator, and variable type is listed there in an
extremely abbreviated form as a memory aid.
□ Look up the feature in Appendix A, "Summary of Applesoft Statements
and Functions." Each statement and function is described briefly, and a
reference is given to the chapter, section, or appendix where it is
discussed in detail:
□ Look up the feature in the index. There you'll find page numbers of the
places in the manual where it is mentioned.
□ Look in the appendixes at the back of the manual for quick reference on
specific facts.

xxiv Preface: About This Manual


To Learn the Applesoft Language
If you are not familar with Applesoft, you can follow this procedure to learn
it:
1. Read Appendix A, "Summary of Applesoft Statements and Functions,"
to get a quick feel for each of the features in the language.
2. Read through each chapter and enter and run the sample programs.
Then try modifying them to check your understanding and gain
hands-on experience.
3. Enter, run, and modify the sample program in Chapter 8.

To Learn Program Planning

If you already know something about Applesoft and want to increase your
programming skill and efficiency:
□ Read through Chapter 8 and experiment with the program developed
there.
□ Develop your own programs based on the methods presented in
Chapter 8.
□ Restructure someone else's program using the methods in Chapter 8.
□ Read Appendix G, "Hints for Program Efficiency," at the back of the
manual.

Conventions Used in This Manual

Throughout this manual you'll encounter the following conventions:


The term Apple II is used generically to refer to all models in the Apple II
series of personal computers (original Apple II, Apple II Plus, Apple Ile,
Apple Ile). Comments referring specifically to the original Apple II are clear
from the context.
When numbers (such as memory addresses) are preceded by a dollar sign,
such as $9600, that means they are in hexadecimal notation. Numbers
without a dollar sign are generally in decimal, unless otherwise stated.
Computer terms you may not know are in boldface type. All boldface
words are defined in the Glossary.

Conventions Used in This Manual XXV


Every section that explains an Applesoft statement or command begins
with an example or examples of correct syntax. For instance, Section 3.&2,
"The Next Statement," begins with these examples:
NEXT
N E X T I NDE X
NEXT J , I
A.Warning Warnings like this indicate potential serious problems.
Important! Text set off in this manner-and with a tag in the margin-presents
important information.
II, II Plus, lie Text set off in this manner presents information specific to one or more
models in the Apple II series of computers. For instance, the tag opposite
this paragraph indicates that the text concerns the Apple II, Apple II Plus,
and Apple Ile.
Marginal notes define computer terms By the Way: Text set off in this manner presents sidelights or
and point you to additional information interesting pieces of information.
about a topic.

Where to Learn More


The following sources contain further information about the Apple II series
of computers in general and the Applesoft programming language in
particular:
□ The owner's manual for your particular Apple computer covers the
basics of the system and includes a special section on your computer's
keyboard. It also contains a list of books and magazines of special
interest to Applesoft programmers, as well as a short guide to the rest of
the documentation that comes with your computer.
□ A keyboard introduction disk comes with all disk-based Apple II systems.
It contains an interactive tutorial program giving you hands-on practice
with many of the concepts discussed in your owner's manual. It's a must
if you're new to computers.
□ BASIC Programming With ProDOS tells how to create and read text
files on disk, and how to save your Applesoft programs on disk, using the
ProDOS operating system. This manual includes a disk of programming
examples, as well as the Applesoft Programmer's Assistant-a collection
of time-saving tools.
□ The Applesoft Tutorial is an excellent guide for beginning
programmers. It provides introductory, step-by-step guidance for the new
programmer and has a special chapter on editing Applesoft programs.

xxvi Preface: About This Manual


□ Apple Backpack: Humanized Programming in BASIC, by Scot
Kamins and Mitchell Waite (BYTE/McGraw-Hill Books) teaches
programming in a friendly and easy-paced way for people who are not
computer experts.
□ The reference manual for your Apple computer contains a wealth of
information about the more technical aspects of the system's operation,
with lists of various programmer-accessible system flags, pointers, and
soft switches.

Where to Learn More xxvii


Chapter 1 General Information



..,, .,·
... •' . •



BASIC: Beginner's All-purpose Symbolic Applesoft BASIC is a very extended version (in computer parlance, a
Instruction Code superset) of the BASIC programming language. It includes many more
features than either the original BASIC, developed at Dartmouth College in
the 1960s, or the standard version of the language, as defined by the
American National Standards Institute (ANSI). The extra features allow
your programs to use the special capabilities of the Apple II, such as color
graphics, animation, and hand controls.
This first chapter introduces the Applesoft language and the environment
in which it operates. Here you will find information on how to create,
modify, execute, and store Applesoft programs.
o Section 1.1, "Statements, Lines, and Programs," deals with the
fundamental units of Applesoft programs. It tells how to type Applesoft
statements for immediate execution and how to create and modify
programs in the computer's memory.
o Section 1.2, "Operations on Whole Programs," introduces Applesoft's
commands for displaying a program on the screen, writing it to an output
device such as a printer, executing it, saving it on a disk, and retrieving it
from a disk.
o Section 1.3, "Interrupting and Resuming a Program," tells how to suspend
or cancel the execution of a running program and how to resume
execution after an interruption.
o Section 1.4, "Editing What You Type," briefly describes Applesoft's
facilities for correcting typing errors and editing text on the screen.

1 . 1 Statements, Lines, and Programs


The basic unit of an Applesoft program is the program line, which can
contain one or more statements specifying actions you want the computer
to perform. Most Applesoft statements are identified by one or more
keywords, special words that Applesoft recognizes as denoting a particular
type of statement.
You can type a program line whenever you see Applesoft's prompt
character, a right bracket ( ] ), displayed on the screen followed by the
cursor. Each line you type must end in a press of the I RETUR N I key (but see
Section 1.1.4 about multiple statements per line). Depending on what you
type, the statements in the line are either executed immediately or deferred
for later execution as part of a complete program.

2 Chapter 1 : General Information


Uppercase Versus Lowercase: If you have an Apple Ile or an
enhanced Apple Ile, it doesn't matter whether you type the names of
variables or Applesoft commands in uppercase or lowercase letters;
they're automatically converted to uppercase when you list the program.
However, the Apple II, Apple II Plus, and earlier Apple Ile computers
require that you use uppercase letters. For the sake of consistency,
uppercase letters are used in this manual.
By the way, earlier Apple Ile computers can be upgraded to enhanced
Apple Ile's. See your dealer for details.
Notice that a program line is not the same thing as a line of text on the
screen. If the cursor reaches the end of a screen line while you're typing a
program line, it wraps around to the beginning of the next screen line and
continues displaying what you type. A program line can be up to
239 characters long (including line numbers) and ends only when you press
I RETURN 1.
Extra-Long Program Lines: Actually, you can type as many as
255 characters in a program line (including the line number and any
spaces), but all characters after 239 are ignored. If you type more than
255 characters, Applesoft displays a backslash character (\) and cancels
the entire line. It then redisplays the prompt character ( ] ) followed by
the cursor, and you have to retype the entire line from the beginning. As a
warning, Applesoft beeps with every character you type beginning with
the 245th in a line.
It's usually a bad idea to type program lines this long. In practice, you
should keep your lines well below 239 characters in length.

1 . 1 . 1 Immediate Execution

If you want Applesoft to execute a statement or program line as soon as you


type it, just type the line and press I RETURN 1. For example, if you type
P R I NT " H E L L O "
Applesoft immediately displays the word H E L L O on the screen, on the line
following what you just typed.

1 . 1 Statements, Lines, and Programs 3


1 . 1 .2 Line Numbers and Deferred Execution
If you want Applesoft to save a program line to be executed later-that is, if
you want it to defer execution-then precede the line with a line number:
10 P R I NT " H E L L O "
Line numbers must be in the range 0 through 63999. Applesoft uses the
presence or absence of line numbers to determine whether the line you type
is to be carried out immediately or deferred (stored for execution at some
future time).
A sequence of deferred-execution lines, each preceded by a different line
number, is an Applesoft program. Program lines are stored in the
computer's memory in sequential order, from the lowest-numbered line to
the highest.

1 . 1 .3 Adding Lines to a Program

To add a new line to a program, just type the new line preceded by a line
number indicating where in the program you wish to insert it. It makes no
difference in what order you enter program lines; Applesoft puts them in
the proper order for you.
Helpful Hint: Instead of using consecutive line numbers (0, 1, 2...), it's
usually more convenient to leave intervals of 5 or 10 or 20 between the
line numbers in your program. This makes it easy to insert new lines, if
necessary, in between the old ones.

1 . 1 .4 Multiple Statements on the Same Line


Applesoft allows you to put more than one statement on the same program
line. Use a colon (:) to separate the statements:
4 0 P R I N T " C O M E O U T S I DE '' : P R I NT " A N D P L A Y "
You can type as many statements as will fit within the limit of
239 characters per line.

4 Chapter 1 : General Information


A Drawback: Although using multiple statements on the same line can
speed up the execution of your program, it can also make program editing
difficult and time consuming. This example, for instance, has two
statements on the same line. In order to change the word □ U T S r DE in the
first statement to I N S I D E , you would have to retype both statements.
But if each statement were on its own line, you would have to retype only
the one statement you wanted to change. This may not seem like much of
a time savings; but when you multiply three or four seconds by the
dozens of edits you might need to make in developing a typical program,
the savings can become considerable.

1 . 1 .5 Deleting Lines: The DEL Command


DEL Hlfrl , 2 0 0

The DEL command deletes (removes) a range of consecutive lines from the
program currently in memory. The line numbers of the first and last lines to
be deleted follow the keyword DEL and are separated from each other by a
comma. All program lines between and including the two specified line
numbers are deleted from the program. This example, for instance, deletes
lines 100 to 200, inclusive.
If either line number is out of the range of lines in the actual program (for
instance, if the command is DEL 100, 200 and the highest existing line
number is 150), then all existing lines within the specified range are
deleted. If DEL specifies a range of lines that doesn't exist, or if the second
line number is smaller than the first, the command has no effect:
DEL 2 0 0 , 1 0 0 Nothing happens.
A single number with a comma also has no effect:
DEL 35 ,

A single number without a comma causes a syntax error:


DEL 35 Syntax error.
To delete a single line from the program, simply type the number of that
line and press I RETURN 1:
1 50 J RETURN j

1 . 1 Statements, Lines, and Programs 5


Dash Not Allowed in DEL Command: Unlike the LIST command (see
Section 1.2.3), you cannot use a dash (-) to separate the line numbers in
the DEL command:
D E L 6 fll - 1 fll fll Causes a syntax error.
The DEL command is normally used in immediate execution. You can also
use it from within a program, but as soon as it is executed the program stops
with no error message:
2 fll D E L 1 3 5 , 2 5 fll Removes lines 135 through 250 from
program; halts program execution.

1 . 1 .6 Changing Lines in a Program

To replace an existing line of your program, simply type the new line using
the same line number as the existing one. What you type replaces the old
line under the same line number; the old line is forgotten.
To alter an existing line, either retype the line or use your computer's
editing facilities, discussed in Section 1.4 and in Appendix J.

1 . 1 .7 Annotating a Program: The REM Statement

REM TEST FOR E R R O R


One rule of good programming practice is to include comments in your
program, explaining or clarifying to a human reader how the program
works. Applesoft's REM (for remark) statement allows you to include such
remarks within the body of your program. It consists of the keyword REM
followed by any explanatory notes you care to ip.clude. An example of a
REM statement is
Ill REM M O N T H L Y B U DGET P R OG R A M
This statement is included in the program strictly for the benefit of the
human reader. When you list the program, the REM statement appears just
like any other statement. But when you run the program, Applesoft ignores
everything following the keyword REM on the same line and just goes on to
the next line. See Chapter 8, "Programming: Bringing It All Together," for
some tips on using the REM statement.

6 Chapter 1 : General Information


1 .2 Operations on Whole Programs

This section describes Applesoft's commands for manipulating whole


programs:
□ NEW (see Section 1.2.1) clears the current program from the computer's
memory so you can start typing another.
□ CLEAR (see Section 1.2.2) resets all variables and internal control
information to their initial settings, without affecting the Applesoft
program in memory.
□ LIST (see Section 1.2.3) displays the current program on the screen or
writes it to an output device such as a printer.
□ RUN (see Section 1.2.4) executes the program currently in memory. It
can also be used to load and execute a program stored on a disk.
□ SAVE (see Section 1.2.5) writes the program currently in memory onto a
disk or a tape cassette for future use.
□ LOAD (see Section 1.2.6) reads a program into memory from a disk or a
tape cassette for execution.
You can use all of these commands for immediate execution. You can use
some of them from within your Applesoft programs as well.

1 .2 . 1 Clearing Memory: The NEW Command

MEW
The NEW command clears the current program from memory, resets the
values of all numeric variables to O and those of all string variables to the
null string, and prepares Applesoft to accept a new program. If there are no
programs and no variables in memory, NEW has no effect.
When you sit down to start typing a new program, always begin by typing
NEW. Otherwise, you might find that you're not typing a new program at
all, but just editing the first lines of a program already in memory.
Although NEW is usually used in immediate execution, you can also use it
in deferred execution (from within a program):
1 00 I F A $ • "RATS" THEM MEW
NEW in conditional statement.
999 MEW NEW on its own line.

1 .2 Operations on Whole Programs 7


.A.Warning Using NEW in deferred execution can do strange and unpredictable
things to Applesoft's innards, causing subsequently entered programs to
hang: for a program to spin its wheels hang. If you use NEW from within a program, it's a good idea to warn
indefinitely, performing no useful work your user to restart the system before typing another program:
100 I F A $ = "RATS" THEN PR I NT "PLEASE
RE START Y O U R SY STEM BEFORE TYP I NG
A N E W P R O G R A M . II : N E W

1 .2.2 Resetting Variables: The CLEAR Command

CLEAR
The CLEAR command resets the values of all numeric variables to O and
null string: a string containing no those of all string variables to the null string; it also resets Applesoft's
characters internal control information to its initial state. It has no effect on the
contents of the program lines in memory.
Although CLEAR is usually used in immediate execution, you can also use it
in deferred execution (from within a program):
1 00 I F 2 $ • " N UT S " T H E N C L E A R
CLEAR in conditional statement.
999 CLEAR CLEAR on its own line.
.A.Warning Be careful where you execute CLEAR. Since CLEAR resets Applesoft's
internal control stack, using it in the midst of a subroutine or in a
subroutines, control stack: see FOR/NEXT loop can interfere with the orderly flow of program
Section 3.4 execution. The following program, for example, crashes in line 40 with a
N E X T W I T H O U T F O R error:
10 FOR X 1 TO 1 0 Tries to loop 10 times.
20 PR I NT X
30 CLEAR CLEAR resets control stack
( among other things).
40 NEXT X Program fails here-doesn't know
it's in a loop.
50 PR I NT "H I ! " Program won't get this far.

8 Chapter I : General Information


1 .2.3 Listing a Program: The LIST Command
L I ST
L I ST 1 1Hl
L I ST 1 00 ,
L I ST 1 00 -
L I ST - 200
L I ST , 200

L I ST 1 0 0 , 2 0 0
L I ST 1 0 0 - 2 0 0

The LIST command displays on the screen all or part of the program
currently in memory, or writes it to the current output device as specified in
the last PR# statement. (See Section 5.2.1.) For example, if there is a
printer connected to slot 1 or port 1, and if the statement P R # 1 has been
executed, then the program listing is sent to the printer.
To list the entire program, just type
L I ST

and press I RETUR N 1.


You can list a portion of the program by specifying the first and last lines
you want to list, separated by either a comma or a dash:
L I ST 1 0 0 , 2s 0 Displays lines 100 through 250.
L I sT 1 0 0 - 2s 0 Also displays lines 100 through 250.
If none of the lines in the specified range are in memory, nothing is listed. If
the specified range is greater than the actual range of lines in the program,
Applesoft lists the entire program.
If you specify only one line number preceded by a comma or dash, all lines
from the beginning of the program through the specified line are listed:
L I ST , 1 0 0 Displays from beginning of program
through line 100.
If you specify only one line number followed by a comma or dash, all lines
from the specified line through the end of the program are listed:
L I ST 1 0 0 - Displays from line 100 through end
of program.
If you just specify a single line number, only that line is listed:
L I sT 1 0 0 Displays line 100 only.

1.2 Operations on Whole Programs 9


An Exception: You cannot list line number O by itself. You must use a
form like
L I ST 0 , 1
•Warning Always be sure to type the keyword LIST before the number of the
program line you want to list; typing a line number not preceded by a
keyword deletes the specified line from the program. (See Section 1.1.5.)
Although the LIST command is usually used in immediate execution, you
can also use it from within a program:
1 50 L I ST Lists entire program.
235 I F Z • X T H E N L I ST 1 0 , 7 5
Lists lines 10 through 75 if
variable Z holds same value as
variable X.

1 .2.4 The RUN Command

RUN
RUN 275
R U N M O N TH L Y . BUDGET
The RUN command instructs Applesoft to execute the program currently in
memory. If no line number is given, execution begins at the beginning of the
program; if the RUN command includes a line number, execution begins at
the specified line:
RUN Executes program from beginning.
RUN 5 0 0 Executes program from line 500.
If you attempt to run a program from a specified line number (as in
R U N 5 0 0) and that line doesn't exist, the message ? U N D E F ' D
S T A T E M E N T E R R O R is displayed and program execution halts.
Although RUN is normally used in immediate execution, you can also use it
from within a program:
1 5 0 I F A • 0 THEN RUN If value of A is 0, then executes
program from beginning.
235 RUN 6 0 0 Executes program from line 600.
You can use this technique, for example, to restart a game or to avoid
executing some code with low line numbers.

10 Chapter 1 : General Information


�Warning Whenever the RUN statement is executed, it resets the values of all
numeric variables to O and those of all string variables to the null string
before executing the first program line. I f you have assigned values to any
variables in immediate execution, those values are forgotten. This
happens even if there is no program currently in memory.
If your computer is equipped with a disk drive and the disk operating
system is active, you can use the RUN command to load a program into
memory from a disk file and then execute it. To do this, follow the keyword
RUN with the filename under which the program is stored on the disk. For
example, if the program you want to run is stored in a file named AWAY,
first make sure the disk containing that file is in the disk drive, then type
RUH AWAY
and press I RETURN J. Applesoft (and the disk operating system) does the
rest.
If you try to use this form of the RUN command with no disk drive
connected to your computer, or without the disk operating system loaded
and active, you'll get a syntax error.
Where Else to Look: For more information on disk drives, disks, files,
and filenames, see BASIC Programming With ProDOS and the manual
that came with your disk drive. If you received DOS with your disk drive,
this is the DOS User's Manual. If you received ProOOS, it is the ProDOS
User's Manual. If your computer is an Apple Ile, it is the System
Utilities Manual. For related Applesoft commands, see Sections 1.2.5
and 1.2.6. For information on using a cassette tape recorder in place of a
disk drive, see Appendix M.

1 .2.5 The SAVE Command


SAVE
S A V E M O H T H L Y . BUDGET
On systems equipped with a disk drive, the SAVE command writes the
Applesoft program currently in memory to a file on a disk. The keyword
SAVE is followed by the filename under which the program is to be saved.
The copy of the program in memory is not affected in any way. For
example,
S A V E M Y . C H I LD
stores the current program on disk under the filename MY.CHILD.

1.2 Operations on Whole Programs 11


Attempting to use this form of the SAVE command with no disk drive
connected to your computer, or without the disk operating system loaded
and active, results in a syntax error.
II, II Plus, lie If you issue the SAVE command without specifying a filename, Applesoft
attempts to write the program in memory onto a tape cassette. If no
cassette recorder is connected, the computer seems to hang for a while;
the actual time that passes before you regain control depends on the
length of the program in memory. You can regain control immediately by
pressing I CONTROL H RESET I (see Section 1.3.2).
Where Else to Look: For more information on disk drives, disks, files,
and filenames, see BASIC Programming With ProDOS and the manual
that came with your disk drive-the DOS User's Manual, ProDOS
User's Manual, or System Utilities Manual. For related Applesoft
commands, see Sections 1.2.4 and 1.2.6. For information on using a
cassette tape recorder in place of a disk drive, see Appendix M.

1 .2.6 The LOAD Command


L O A D M O N T H L Y . BUDGET
On systems equipped with a disk drive, the LOAD command reads an
Applesoft program from a file on a disk into the computer's memory for
execution or editing. The keyword LOAD is followed by the filename under
which the program is to be found on the disk. For example,
LOAD THE . D I CE
loads the program into memory from the file named THE.DICE.
LOAD does not execute the program it retrieves; it merely reads a copy of
the program into memory. You can then execute the program, if you wish,
with the RUN command. The copy of the program on the disk is not
affected in any way.
If the disk in the disk drive doesn't contain a file of the specified name, the
error message F I L E N O T F O U N D is displayed. If there is no disk drive
connected to your computer, or if the disk operating system isn't loaded and
active, you get a syntax error.

12 Chapter 1 : General Information


On systems capable of cassette tape storage, if you issue the LOAD
command without specifying a filename, Applesoft attempts to read a
program into memory from a tape cassette. If no cassette recorder is
connected, or if the tape in the recorder doesn't contain a program to load,
or if the recorder is turned off, the computer hangs forever looking for a
program that isn't there. When you get bored waiting, press
I CONTROL H RESET I to regain control.
Where Else to Look: For more information on disk drives, disks, files,
and filenames, see BASIC Programming With ProDOS and the manual
that came with your disk drive. For related Applesoft commands, see
Sections 1.2.4 and 1.2.5. For information on using a cassette tape recorder
in place of a disk drive, see Appendix M.

1 .3 Interrupting and Resuming a Program


If a program starts to run away from you, (for example, if it gets into an
endless loop), there are various ways of interrupting it and regaining
control.

1 .3 . 1 Suspending Screen Output


Sometimes a program's output, or its listing, exceeds the number of lines
available on the display screen, causing the output to fly by on the screen
too fast for you to read. To suspend screen output temporarily, you can
press I CONTROL H]J (press � while holding down I CONTROL I).
I CONTROL H]J doesn't permanently discontinue the display of text; pressing
any key, including another I CONTROL H]J, causes screen output to resume.
You can then suspend it again with another I CONTROL rf]]. To permanently
discontinue a program or a listing, use �.
Helpful Hint: Experienced programmers looking at listings of long
programs keep I CONTROL I continually pressed; they press � whenever
they want to either suspend or continue the listing.

1 . 3 Interrupting and Resuming a Program 13


1 .3.2 Interrupting Program Execution
Applesoft gives you two ways of interrupting the execution of a running
program or canceling a listing. Pressing � interrupts the
program in such a way that it is usually possible to resume execution from
the point of the interruption. Pressing I CONTROL H RESET I is somewhat
more drastic, and often leaves the system in a state from which the program
can't be resumed with a CONT statement (see Section 1.3.3).

1 .3.2. 1 CONTROL-C
Pressing � (pressing @] while holding down I CONTROL D
cancels the execution or listing of a program and returns Applesoft to its
command level, displaying the prompt character ( ] ). You can then resume
execution of the program, if you wish, with the CONT command.
Canceling a Program Waiting for a Response: To cancel a program
that is waiting for a response to an INPUT statement (see Section 5.1.2),
press � and follow it immediately with I RETURN 1.
� does not interrupt a program waiting for a response to a
GET statement (see Section 5.1.3). Unlike the INPUT statement, GET
assumes that � is a valid response and assigns the ASCII
code for the character � to the specified variable. To allow a
program halted at a GET statement to be interrupted with �.
use this form in the program:
2s0 GET A $ Waits for user to press a key
260 I F A $ • C H R $ C 3 ) T H E N STOP
If user presses �
(ASCII code 3), then stops
_..warning In certain situations, using � can disconnect the disk
operating system. See the disk operating system manual for information
on this point.

1 .3.2.2 CONTROL-RESET
In most cases you can immediately and unconditionally stop the execution
of any Applesoft program or command by pressing I CONTROL H RESET I
(pressing I RESET !While holding down I CONTROL I). The program in memory
remains intact, but some of Applesoft's internal "housekeeping" information
is changed; as a result, it may not be possible to resume execution of the
program with the CONT command.

14 Chapter I : General Information


Controlling I CONTROL H R ES ET I : Your Apple II has an advanced
software feature called a reset vector, which allows you to control what
happens when I CONTROL H RES ET I is pressed. You can use the reset
vector to make the program continue as if nothing had happened, branch
to some other portion of the program, or do whatever you choose. To use
this technique you need to be familiar with the Apple II's built-in Monitor
program: see your computer's reference manual for details.

1 .3.3 Resuming Execution: CONT Command

CONT
The CONT (for continue) command is used to resume execution of a
program after it has been interrupted by a STOP (see Section 3.6.1) or END
statement (see Section 3.6.2) or by pressing �- Execution
resumes at the first statement after the STOP or END, or at the point in the
program where execution was interrupted by � (see
Section 1.3.2).
CONT won't work if
□ the program has been stopped because of an error
□ an error has occurred in immediate execution
□ an INPUT statement has been interrupted with �
□ the CLEAR or NEW command has been executed
□ any program line has been edited since the program stopped running
□ there are no more program lines after STOP or END.
However, you can continue the program with CONT after examining or
changing the values of variables, provided you haven't edited any program
lines.
Important! Resuming after I CONTROL H RESET J: When a program is interrupted with
I CONTROL H RES ET I, CONT may or may not continue execution. Let the
programmer beware!
.A.Warning I The CONT command should be used in immediate execution only. If it is
executed from within a program, it causes the program to hang.

1.3 Interrupting and Resuming a Program 15


1 .4 Editing What You Type

This section gives a very brief description of Applesoft's facilities for


correcting typing mistakes and editing text on the screen. More detailed
discussions of these features can be found in your Apple computer owner's
manual and theApplesoft Tutorial. For hands-on experience with the
various keys and editing features, use the keyboard introduction disk that
came with your computer.

1 .4. 1 Canceling an Input Line


I CONTROL H:Kl is your escape hatch. By pressing 00 while holding down
I CONTROL I, you can change your mind (as long as you haven't yet pressed
I RETURN D and cancel a program line that you're entering or editing, or a
line of input that you're in the midst of typing into a program. Applesoft
displays a backslash (,) at the end of the line you were typing, to show that
it's ignoring that input, and redisplays the cursor at the beginning of the
next line of the screen.
□ If you were typing a new program line, the whole line is eliminated and
you can start over again.
□ If you were retyping a previously entered program line, any changes you
typed are canceled.
□ If you were typing input to a running program, the line you were typing
is ignored and the program waits for your new response.
I CONTROL @ does not affect any previous input you've typed or program
lines already entered.

16 Chapter 1 : General Information


1 .4.2 The Arrow Keys

There are four arrow keys on most models of the Apple II keyboard:
□ The G key works as a backspace. It moves the cursor one position to the
left and causes Applesoft to forget the last character typed from the
keyboard (or recopied with the G key;), though no characters are
removed from the screen. If any pure cursor moves (see Section 1.4.3)
have been used, the character "erased" may not be the one the cursor
backs up over.
□ The G key recopies the character under the cursor as if it had been
typed from the keyboard, then moves the cursor one position to the right.
Moving the cursor over a character with G is exactly the same as typing
that character from the keyboard.
□ The [I) key moves the cursor down one line without erasing or recopying
any characters. Neither the Apple II nor the Apple II Plus has this key.
□ The [I) key has no effect in Applesoft.
In escape mode (see Section 1.4.3), all four arrow keys lose their backspace
and recopy functions and simply move the cursor one position in the
indicated direction.
Fast Moves: The Apple II keyboard's auto-repeat feature is particularly
handy for long cursor moves. If you press and hold down any of the arrow
keys, the cursor moves repeatedly in the indicated direction for as long as
you hold down the key. (Exception: the [I) key doesn't move the cursor
unless you're in escape mode.)
Every time you press an arrow key, you send an ASCII code (see
Section 4.2.1 and Appendix C) to the computer. Table 1.1 shows which
codes correspond to which keys.

Table 1-1. ASCII Equivalents of Arrow Keys


ASCII Keyboard
Key Code Equivalent

G 8 �
G 21 I CONTROL !{ill
m 11
10

I CONTROL ID]
[I)

1.4 Editing What You Type 17


For Experts Only: IT] and [I) (not present on Apple II and Apple II Plus)
can be typed by the user in response to an INPUT statement in a running
Applesoft program. CB and E) can't be, because they're interpreted as
backspace and recopy, even in program input; but any of the four arrow
keys can be typed as a response to a GET statement.) In your own
programs, you can make the arrow keys mean just what you choose them
to mean by having the program test the input for each arrow's ASCII
value, as shown in Table 1-1. The program can take any action you want
on receiving one of these codes from the user.
("The question is," said Alice, "whether you can make keys mean so
many different things."
"The question is," said Humpty Dumpty, "which is to be master-that's
all.")

1 .4.3 Escape Mode

If you press I ESC I while the 1 prompt is on the screen, you put Applesoft
into escape mode, in which certain keys take on special meanings. Some
of the keys become pure cursor moves, meaning that they move the cursor
around on the screen without erasing or recopying characters or affecting
Applesoft's input in any way. Others can be used to clear away text from all
or part of the screen, again without having any effect on the input received
by Applesoft.
Letters Can Be Uppercase or Lowercase: All of the letter keys listed
have the same effect whether they are typed in uppercase or lowercase
on all Apple II series computers.
In escape mode, the following characters move the cursor one position in
the stated direction and then leave escape mode. To continue moving the
cursor, you have to press I Esc I again. The functions of these keys are
Figure 1-1. Single Cursor Moves illustrated in Figure 1-1.
□ IA] moves the cursor one position to the right.
□ []] moves the cursor one position to the left.
□ @] moves the cursor down one line.
□ [[) moves the cursor up one line.

18 Chapter 1: General Information


11, II Plus, lie The following characters move the cursor one position in the stated
direction and remain in escape mode. You can continue moving the
cursor without pressing I ESC I again. These keys are especially useful for
Figure 1-2. Long-Range Cursor Moves long-range cursor moves. The functions of these keys are illustrated in
Figure 1-2.
□ [I) moves the cursor up one line.
□ Q] moves the cursor one position to the left.
□ IB] moves the cursor one position to the right.
□ [M] moves the cursor down one line.
Cursor Control Diamond: Notice that the [I), Q], IB], and [M] keys
form a diamond shape on the keyboard, representing the directions in
which these keys move the cursor: (I) up, Q] left, [K) right, [M] down.
Fast Moves: The Apple Ile and Apple Ile keyboards have an auto-repeat
feature, particularly handy for long cursor moves. If you press and hold
down [I), Q], IB], [M], or any of the arrow keys while in escape mode, the
cursor moves repeatedly in the indicated direction for as long as you hold
down the key.
In escape mode, the following keys clear away text from all or part of the
display screen and then leave escape mode:
□ [I) clears from the current cursor position to the end of the line.
□ [I:) clears from the current cursor position to the end of the text window.
(See Section 5.2.4.)
□ [ru clears the entire text window and moves the cursor to the top-left
corner.
□ I Esc 1 1 CONTROL I{[) enables displaying on the screen ot most control
characters. I Esc 1 1 CONTROL f{[) disables it. (This applies to the Apple Ile
and enhanced Apple Ile's only.)
The s�ial functions of all keys in escape mode are summarized in
Table 1-2.
To leave escape mode, you can press any key except one of those listed in
the table. But to avoid inadvertently pressing a key that has a special
meaning, it's safest always to press the I SPACE I bar to leave escape mode.

1.4 Editing What You Type 19


Table 1-2. Escape- Mode Functions
Note: Table appli,es to Apple Ile andApple JJe only.

Key Function

0 Moves cursor right one position; leaves escape mode.


[[] Moves cursor left one position; leaves escape mode.
@] Moves cursor down one line; leaves escape mode.
[QJ Moves cursor up one line; leaves escape mode.

[D Moves cursor up one line; remains in escape mode.


II] Moves cursor left one position; remains in escape mode.
[K] Moves cursor right one position; remains in escape mode.
[0 Moves cursor down one line; remains in escape mode.
G Moves cursor left one position; remains in escape inode.
G Moves cursor right one position; remains in escape mode.
II) Moves cursor up one line; remains in escape mode
(Apple Ile and Apple Ile only).
[I) Moves cursor down one line; remains in escape mode
(Apple Ile and Apple Ile only).
Clears from cursor to end of line; leaves escape i:node.
Clears from cursor to end of screen; leaves escape mode.
Clears entire screen; moves cursor to top-left corner;
leaves escape mode.
I CONTROL KI] Enables display of control characters.
� Disables display of control characters.

20 Chapter 1: General Information


Chapter 2 Variables and Arithmetic

21
This chapter deals with variables and arithmetic in Applesoft. These
concepts are fundamental to Applesoft programming and appear again and
again throughout this manual.
□ Section 2.1, "Variables," discusses how to define and use variables, the
various types of variables available in Applesoft, and the rules for
naming them.
□ Section 2.2, "Assigning Values: The Assignment Statement," deals briefly
with one of Applesoft's most basic types of statements, the assignment
statement.
□ Section 2.3, "Expressions," discusses arithmetic operators and
expressions and the rules of precedence that govern them.
□ Section 2.4, "Functions," covers Applesoft's built-in arithmetic functions
and tells how you can define your own functions.

2.1 Variables

A variable is a symbol representing a location in the computer's memory


where a value can be stored. The first time your program assigns a value to
a particular variable, Applesoft automatically allocates enough memory for
that variable and stores the specified value at that location. Thereafter,
whenever your program uses that particular variable name, Applesoft takes
the name to refer to the value stored at the corresponding location. For
instance, if the variable PI refers to a memory location where the value
3.14159 is stored, then the statement P R r tf f P r displays the value
3 . 1 4 1 ss on the screen.
Applesoft has three types of variables:
□ Real variables (see Section 2.1.2) can contain either whole numbers or
numbers containing decimal fractions.
□ Integer variables (see Section 2.1.3) can contain whole numbers only.
□ String variables (see Section 2.1.4) can contain strings of text
characters such as words or names.
In addition, Applesoft allows you to define collections of variables, called
arrays, of any of the types listed.

22 Chapter 2: Variables and Arithmetic


Programming Tip: Applesoft converts all integer values to real fonn
before performing arithmetic on them. Because this conversion takes
time, integer arithmetic is considerably slower than arithmetic on real
quantities. However, integers take up less space in the computer's
memory than real numbers. In relatively small programs in which space
is not a concern, you can speed up your program by using real variables
instead of integers wherever possible, especially in subroutines, loops,
and other sections of code that are executed many times. In large
programs where space is critical, you can save space at the expense of
time by using integers instead of reals, particularly in arrays containing
many elements. See Appendix G for further suggestions on how to save
space and time in your programs.

2. 1 . 1 Variable Names
The name of a variable must begin with a letter of the alphabet, which may
be followed by one or more letters and/or digits. In addition, the names of
all integer variables must end with a percent character (%) and those of
string variables must end with a dollar sign ($). The various variable types
and the rules for naming them are summarized in Table 2-1.

Table 2-1. Variable Types

Simple Array
Type Suffix Examples Examples
Real (none) K AGE (CHILD)
PRICE TAX (ITEM)
Nl Nl (J %,3)
Integer % J% YEAR% (N)
G5% BOOK% (COUNT)
N1% Nl% (J%,3)
String $ A$ SHOP$ (5)
SAM$ DAY$ (WEEK)
N1$ Nl$ (J%,3)

A variable name can be up to 238 characters long, but Applesoft uses only
the first two characters to distinguish one variable from another of the same
type. Except for the suffix, all characters beyond the first two in a name are
ignored, as long as they don't include a reserved word.

2.1 Variables 23
.A.Warning Take care not to begin the names of different variables of the same type
with the same two characters. Applesoft considers the names SUM and
SUNSTROKE, for example, to refer to the same variable, since they both
begin with the same two characters.
Notice that this restriction applies only to variables of the same type.
Applesoft considers the names TAX, TAX%, and TAX$ to refer to three
different variables, even though they all begin with the same two
characters, because they are of different types (real, integer, and string).
Reserved Words: Certain words used in Applesoft are reserved for
special uses in specific commands; you can't use these words as variable
names or as parts of variable names (even beyond the first two
characters). For instance, TOTAL or SUBTOTAL are illegal as variable
names, because they both contain the reserved word TO. See Appendix D
for a list of Applesoft's reserved words.

2.1 .2 Real Variables


A real variable can hold any numeric value, with or without a decimal
point, between -9.99999999E+37 and +9.99999999E+37 (where "E+37"
means "times 10 to the +37th power"). Applesoft represents real numbers
to 32 bits (about 9 digits) of precision.
The name of a real variable must consist of letters and digits only. Some
legal real variable names are
SAM
TAX
Q7
SUMOFALLNUMBERS
Until they are given some other value with an assignment statement, all
real variables are preset to the value 0.

24 Chapter 2: Variables and Arithmetic


2. 1 .3 Integer Variables
Integer variables can hold only whole-number values between -32767
and +32767. The name of an integer variable must end with the percent
character (%). Some legal integer variable names are
SHARE%
D5%
TAX%
Until they are given some other value with an assignment statement, all
integer variables are preset to the value 0.
If a number containing a decimal fraction is assigned as the value of an
integer variable, it is truncated to the next lowest whole number-not
rounded to the nearest whole number:
LET A X • 32 . 678 Value 32 is assigned to variable A%.
LET BX • - 3 4 . 2 Value -35 is assigned to variable B%.

2.1 .4 String Variables

A string is a sequence of text characters (letters, digits, and punctuation


marks). Just as you can write numeric constants such as 27 and 2.236 in
your Applesoft programs, you can write string constants by enclosing the
characters in the desired string between double quotation marks:
"NOT WITH A BANG BUT A WHIMPER"
"George Bernard Shaw"
"H234J7"
"$?*! ! %"
Lowercase Okay: Even though your version of Applesoft may not
understand lowercase letters when you use them in keywords, it allows
you to use them in a string constant, as the second example shows.

2.1 Variables 25
A string can contain from O to 255 characters; when it contains no
characters it is called a null string. Two quotation marks with nothing
between them denote the null string:
11 11

A string variable can hold any string as its value. Its name must end with a
dollar sign ($). Some legal string variable names are
NAME$
S9$
J$
Until they are given some other value with an assignment statement, all
string variables are preset to the null string.

2. 1 .5 Arrays: Collections of Variables

An array is a collection of variables referred to by the same name, usually


holding a collection of data items that are related to each other in some
logical or systematic way. The individual variables in the array are called
its elements, and are distinguished from one another by means of
identifying index numbers called subscripts.
An array can be of any type: integer, real, or string. Array names follow the
same rules as simple variable names of the same type. To refer to a
particular element of an array, write the array name followed by one or
more subscripts, separated by commas and enclosed in parentheses. The
subscripts refer to the position of the desired element within the array:
G c6> Element 6 of real array Q.
F I GU R E X C H > Element N of integer array
FIGURE%.
Figure 2-1. A Typical Array NAME s c J - 3 > Element J - 3 of string array
NAME$ .
array R C O U N T c suMx , 2 > Element (SUM%, 2) of real array
COUNT.
R (O) - 53
Figure 2-1 shows a real array named R with five elements, numbered O to 4.
R ( I) - 27.35 Element R(O) (pronounced R-sub-zero) holds the value 53, R(l)
holds 27.35, and so on. If the value of variable S is 2, then the
R (2) --+ 31.4 - R (S) expression R(S) refers to element R(2), whose value is 31.4, and the
expression R(S + 2) refers to element R(4), which holds the value 19.
R (3) - 6 For a more complete discussion of arrays and their use, see Section 4.1.
R (4) - 19 -- R (S + 2)

26 Chapter 2: Variables and Arithmetic


2.2 Assigning Values: The Assignment Statement
L E T P I • 3 . 1 4 1 59 2 6 5
C O U l'I T% • 0
When Applesoft begins running a program, it sets the values of all real and
integer variables to O and the values of all string variables to the null string
(that is, a string containing no characters). The program can then change
the value of any variable at any time by executing an assignment
statement.
Commands That Reset Variables: The NEW (see Section 1.2.1 ),
CLEAR (see Section 1.2.2), and RUN (see Section 1.2.4) commands also
reset all real and integer variables to O and all string variables to the null
string.
An assignment statement consists of the optional keyword LET, followed
by the name of the variable whose value is to be changed, an equal sign ( = ),
and an expression denoting the new value to be assigned to that variable.
The equal sign means receives the value or is assigned the value; it is
often read simply as gets ("X gets Y plus 2"). The assignment statement
means evaluate the expression to the right of the equal sign and
assign the resulting value to the variable named to the left of the
equal sign. The variable holds that value until it is changed by another
assignment statement or is reset by a NEW, CLEAR, or RUN command. For
example:
LET Q • 27 . 4 Assigns value 27.4 to real
variable Q.
L E T D3 • J Assigns current value of real
variable J to real variable D3;
variable J unchanged.
C O U l'ITX • A + B Assigns current value of real
variable A plus current value of real
variable B to integer variable
COUNT%; variables A and B
unchanged.
S9% • 35 Assigns value 35 to integer
variable S9%.
NAME $ • "SAM" Assigns string value "SAM" to string
variable NAME$.

2.2 Assigning Values: The Assignment Statement 27


HAME S • SAM$ Assigns current value of string
variable SAM$ to string variable
NAME$; variable SAM$ unchanged.
BD X C S > • 36 Assigns value 36 to element 5 of real
array BOX.
JX • A X C H > Assigns current value of element N
of integer array A% to integer
variable J%; array A% and
variable N unchanged.
S H D P H H > • " BA K E R Y " Assigns value "BAKERY" to
element N of string array SHOP$.
Keyword Optional: The keyword LET is optional in assignment
statements. The statements
LET Q • 27 . 4
and
Q • 27 . 4
mean exactly the same thing.

2.3 Expressions

An expression is a formula describing a calculation for the computer to


perform. It can involve any number of numeric variables and constants,
together with operators specifying how the values of the variables and
constants are to be combined. There are three kinds of operators that can be
used in an Applesoft expression:
□ Arithmetic operators (see Section 2.3.1) combine two numeric values
and produce a numeric result.
□ Relational operators (see Section 2.3.2) compare two values and
produce a logical (true-or-false) result.
□ Logical operators (see Section 2.3.3) combine two logical values and
produce a logical result.

28 Chapter 2: Variables and Arithmetic


2.3.1 Arithmetic Operators

Arithmetic operators combine two numeric values to produce a numeric


result. There are five of them in Applesoft, corresponding to the familiar
operations of arithmetic: + (addition), - (subtraction), * (multiplication),
/ (division), and (exponentiation), Here are some examples of their use:
A

3 + 4 3 plus 4, yielding 7.
+ 1 44 Plus 144 (a positive number).
x + v The value of X plus the value of Y.
23 . 7 - 1 1 . 4 23.7 minus 1.4, yielding 12.3.
5e - 75 50 minus 75, yielding -25.
- 1 44 Minus 144 (a negative number).
SUMX - 2 The value of SUM% minus 2.
13 * 5 13 times 5, yielding 65.
6 * . 25 6 times .25, yielding 1.5.
25 * Q U A R T E R S X 2 5 times the value of QUARTERS%.
4 . 0 * co u tH c 5 > 4.8 times the value of element 5 of
array COUNT.
10 1 s 18 divided by 6, yielding 3.
s 1 10 6 divided by 18, yielding .333333333.
D I sr I T I M E The value of DIST divided by the
value of TIME.
D□ L L A R S X 1 1 0 0 The value of DOLLARS% divided
by 100.
2 " 3 2 to the 3rd power, yielding 8.
3 ,. . 5 3 to the .5 power,
yielding 1.73205081.
x " JX The value of X raised to the power
of the value of J%.
Note: Like most other computer languages, Applesoft uses an asterisk
( * ) instead of the letter x to represent multiplication.

2.3 Expressions 29
What to Do With Fractions: Applesoft doesn't treat fractional numbers
in the way that you are probably used to dealing with them. Most people
would read the expression 3 3/4 as three and three quarters. To
Applesoft, however, the same expression would mean thirty-three
divided by four. (Applesoft ignores any spaces it finds in a number.)
It's easy to convert fractions to a form Applesoft understands correctly.
Just think of 3 3/4 as three plus three divided by four. In other words,
instead of typing
LET A • 3 3 / 4
type this:
LET A • 3 + 3/4
Applesoft does the rest.

2.3.2 Relational Operators


A relational operator tests for a relation between two values and
produces a logical (true-or-false) result, depending on whether the
particular relation does or doesn't hold between those two values. For
example, the expression
A > 8

means the value of variable A is greater than that of variable B. If the


current value of variable A is 5 and that of B is 3, then the relation is true; if
the value of B is 8, the relation is false.
Note: Relational operators are particularly useful in connection with the
IF...THEN statement, discussed in Section 3.2.2.

30 Chapter 2: Variables and Arithmetic


The TruthAbout Applesoft: Applesoft actually uses numeric values to
represent the logical values true and false: if the stated relation is true,
the value of the relational expression is 1; if the relation is false, the value
of the expression is 0. For example, if you type the statement
P R I NT 6 > 1 2

in immediate execution, Applesoft responds by displaying the number 0,


meaning false; if you type
P R i l'I T 1 2 > 6

Applesoft displays the number 1, meaning true.


Applesoft has six relational operators (some of which can be written in
more than one way) :
= is equal to
< is less than
> is greater than
< = or = < is less than or equal to
> = or = > is greater than or equal to
< > or > < is not equal to.
Here are some examples of their use:
6 • 6 6 equals 6, yielding 1 for true.
6 • 12 6 equals 12, yielding O for false.
X • 2 The value of X is equal to 2.
NAME $ " "Ann" The value of NAME$ is equal to the
string "Ann."
6 < 6 6 is less than 6, yielding O for false.
6 < 12 6 is less than 12, yielding 1 for true.
P R OBAB I L I TY < . 5 The value of PROBABILITY is less
than .5.
6 > 6 6 is greater than 6, yielding O for
false.
6 > 12 6 is greater than 12, yielding O for
false.
AGE > 65 The value of AGE is greater than 65.
6 <• 6 6 is less than or equal to 6,
6 •< 6 yielding 1 for true.
6 (m 12 6 is less than or equal to 12,
6 •< 12 yielding 1 for true.
A % < • 3 " BX The value of A% is less than or
A % • < 3 * BX equal to 3 times the value of B %.

2 . 3 Expressions 31
6 >· 6 6 is greater than or equal to 6,
6 ·> 6 yielding 1 for true.
6 >• 12 6 is greater than or equal to 12,
6 •> 12 yielding O for false.
S A L A R Y > · 2 fil fil fil fil The value of SALARY is greater
S A L A R Y • > 2 fil fil fil fil than or equal to 20000.
6 <> 6 6 is not equal to 6, yielding O for
6 >< 6 false.
6 <> 12 6 is not equal to 12, yielding 1 for
6 >< 12 true.
X <> y The value of X is not equal to the
X >< y value of Y.
B A N G $ > < "WH I MP E R " The value of BANG$ is not equal to
B A N G $ < > "WH I MP E R " the string "WHIMPER."

2.3.3 Logical Operators

A logical operator combines two logical (true-or-false) values and


produces a logical result. There are three logical operators in Applesoft:
AND, OR, and NOT. Here are some examples of their use:
6 < • 1 2 AND 6 > • 1 2 6 is less than or equal to 12 and 6 is
greater than or equal to 12; value
is O for false.
• 25 < • R AHD R < • 75 .25 is less than or equal to the value
of R and the value of R is less
than .75.
6 < • 1 2 □R 6 > • 1 2 6 is less than or equal to 12 or 6 is
greater than or equal to 12; value
is 1 for true.
A N I MA L $ • "DOG" D R A N I MA L • " C A T "
The value of ANIMAL$ is equal to
the string "DOG" or the string
"CAT."
NOT C 6 < • 1 2 ) 6 is not less than or equal to 12;
value is O for false.
NOT C Y E A R X > 1 95 0 ) The value of YEAR% is not greater
than 1950.

32 Chapter 2 : Variables and Arithmetic


How OR Works: Notice that the OR operator doesn't behave exactly the
way we often use the word or in everyday speech. When we say "A or B
is true," we usually mean that one of the two statements is true, but not
both. The Applesoft OR operator produces a true value if either or both of
its original expressions are true.
Applesoft's logical operators consider a numerical value of O to mean false;
any numerical value other than 0 is taken to mean true. The logical
operators always yield a value of 1 for true or 0 for false.
Logical operators are particularly useful in connection with the IF ... THEN
statement, discussed in Section 3.2.2.

2.3.4 Precedence of Operators


Operators in Applesoft have an order of precedence that determines which
operations are carried out first when they are combined in an expression.
Table 2-3 lists the operators in descending order of precedence. Operators
shown higher in the list are carried out before those lower down. Operators
on the same line of the list have the same precedence, and are carried out
from left to right within an expression.

Table 2-3. Precedence of Operators


Parentheses (innermost first) ( )
Signed arithmetic and logical NOT + - NOT
Exponentiation (powers of numbers)
Multiplication and division * I
Addition and subtraction + .
Relational operators = < > <=
=<
>= => < >
><
Logical AND AND
Logical OR OR

2.3 Expressions 33
Notice that the operators + and - have higher precedence when used to
represent the sign of a number ( as in + 144 or -X) than when they stand for
the operations of addition and subtraction.
To understand how Applesoft's precedence rules work, consider the
expression
-2 * 2 A 3 + Q / 5 - A * B
When Applesoft evaluates this expression, it begins by applying the first
minus sign to the constant 2, obtaining a result of -2. Next it raises the value
of Z to the 3rd power and multiplies the result by -2. Then it divides the
value of Q by 5 and adds the result to that of the previous calculation.
Finally, it multiplies the values of A and B and subtracts that result from
the previous one.
For example, suppose the current values of the variables in this expression
are as follows: Z = 2, Q = 10, A = 7, B = 4. Then
-2 = -2
z 3
A =8
-2 * 8 = -16
Q/5 = 10 / 5 =2
-16 + 2 = -14
A*B = 7*4 = 28
-14 - 28 = -42
The value of the expression is -42.
Parentheses can be used to change the normal order of precedence. For
example:
-2 * 2 A C3 + Q) / 5 - A * B
Value is -3304.8; (3 + Q) evaluated
as a unit.
-2 * 2 A 3 + CQ / 5 - A) * B
Value is -36; ( Q / 5 - A) evaluated as
a unit.
-2 * 2 A 3 + Q / c s - A * B>
Value is -16.4347826;
(Q / (5 - A * B)) evaluated as a unit.
The original expression above is equivalent to the fully parenthesized
expression
C C C -2) * CZ A 3)) + CQ / 5 ) ) - C A * B>

34 Chapter 2 : Variables and AriLhmetic


Helpful Hint: When you're unsure of the order of precedence, use
parentheses to make sure the expression is evaluated in the order you
intend.

2.4 Functions
A function is a preprogrammed calculation that can be carried out on
request. You can use functions whenever you need to perform the same
calculation repeatedly throughout a program. Whenever you call a function
(request its execution), you must give it a particular value to operate on;
this value is called the argument of the function.
Applesoft offers a variety of built-in functions, discussed in Section 2.4.1,
for calculating common mathematical values such as logarithms, cosines,
and square roots. Section 2.4.2 covers the built-in function RND, used for
generating random numbers. In addition, you can define your own functions
for the special needs of a particular program-see Section 2.4.3 for details.

2.4. 1 Built-in Arithmetic Functions

This section discusses the various built-in functions that Applesoft provides
for calculating commonly used mathematical quantities. To call a built-in
function, just type the name of the function followed by an expression in
parentheses representing the argument value on which you want the
function to operate. For example, suppose you need to calculate the square
root of a number. Applesoft has a built-in function named SQR for this
purpose; to find the square root of 3, type
SQR C 3 )
To find the square root of the value of variable X plus 2 , type
SQR C X + 2 )

2.4 Functions 35
2.4. 1 . 1 The ABS Function
The built-in function ABS computes the absolute value of a number-that
is, the positive numerical value of the number, without regard to its original
sign. For example,
ABS ( 2 7 ) Absolute value of 27; yields 27.
ABS C - 2 7 ) Absolute value of -27; yields 27.
A B S c 36 . a 23 . 3 ) Absolute value of 36.8 minus 23.3i
yields 13.5.
A B S ( 2 3 . 3 - 36 . 8 ) Absolute value of 23.3 minus 36.8;
yields 13.5.
ABS C C X C 9 » Absolute value of element 9 of
array C%.

2.4. 1 .2 The SGN Function


The SGN function determines whether the value of its argument is positive,
negative, or 0. It yields a result of 1 if the argument value is positive (greater
than 0), -1 if the argument value is negative (less than 0), and 0 if the
argument value is 0. For example,
SGH ( 2 7 ) Sign of 27; yields 1 (positive).
SGH ( - 2 7 ) Sign of -27; ·yields -1 (negative).
SGH ( 36 . 8 - 23 . 3 ) Sign of 36.8 minus 23.3; yields 1
(positive).
SGH ( 2 3 . 3 - 36 . 8 ) Sign of 23.3 minus 36.8; yields -1
(negative).
SGH (9 * 5 - 4 5 ) Sign of 9 times 5 minus 45; yields 0.
S G H C S UM - 2 0 ) Sign of SUM minus 20.

2.4. 1 .3 The INT Function


INT returns the integer (whole-number) part of its argument value, with the
fractional part, if any, discarded. Note that this function makes no attempt
at rounding: that is, if the argument value is not an integer, INT yi�lds the
next lower integer, not necessarily the nearer integer. For example,
I HT ( 2 7 ) Integer part of 27; yields 27.
I H T ( 36 . 8 ) Integer part of 36.8; yields 36.
I HT C - 7 . 9 ) Integer part of -7.9; yields -8.
I H T ( - 62 . 1 > Integer part of -62.l; yields -63.
I HT C 5 * PR I C E > Integer part of 5 times PRICE.

36 Chapter 2: Variables and Arithmetic


Rounding a Number: To make your program round a numeric value to
the nearest integer, first add .5 and then apply the INT function to the
result. For example, to find the nearest integer to the current value of
variable AGE, use the expression
I H T C A GE + • 5 >

2.4. 1 .4 The SQR Function


The SQR function computes the positive square root of its argument. For
example,
S Q R C 1 69 ) Square root of 169; yields 13.
S Q R C 1 63 . B 4 > Square root of 163.84; yields 12.8.
SQR C 3 > Square root of 3; yields 1.73205081.
SQR C X "2 + 9 > Square root of X squared plus 9.
If you try to take the square root of a negative number, an I L L E G A L
G U A tH I TV error occurs.

2.4. 1 .5 The SIN Function


SIN computes the trigonometric sine of its argument. The argument must be
to convert degrees to radians: see Section expressed in radians (not degrees). For example, assuming the value of the
2.4.3 variable PI is 3.14159265,
S I H CPI / 3) Sine of PI / 3 radians;
yields .866025403.
SIH C1> Sine of 1 radian; yields .841470985.
S I H C X"2 - V"2> Sine of X squared minus Y squared.

2.4. 1 .6 The COS Function


COS computes the trigonometric cosine of its argument. The argument must
be expressed in radians (not degrees). For example, assuming the value of
the variable PI is 3.14159265,
cos C P I I 3 ) Cosine of PI / 3 radians; yields .5.
cos C 1 ) Cosine of 1 radian;
yields .540302306.
cos C X " 2 - V " 2 > Cosine of X squared minus Y
squared.

2.4 Functions 37
2.4. 1 . 7 The TAN Function
TAN computes the trigonometric tangent of its argument. The argument
must be expressed in radians (not degrees). For example, assuming the
value of the variable PI is 3. 14159265,
TAN C P I / 3 ) Tangent of PI / 3 radians;
yields 1. 7320508.
TAN ( 1 ) Tangent of 1 radian;
yields 1.55740772.
TAN C X "2 - Y " 2 > Tangent of X squared minus Y
squared.

2.4. 1 .8 The ATN Function


ATN computes the trigonometric arc tangent (inverse tangent) of its
argument: tl;uit is, the angle whose tangent is equal to the given value. The
result is expressed in radians (not degrees). For example,
ATN C SQ R C 3 ) ) Arc tangent of the square root of 3;
yields 1.04719755 ( = PI / 3)
radians.
AT N C 1 > Arc tangent of 1; yields
. 785398163 radians.
Arc tangent of X squared minus Y
squared.

2.4. 1 .9 The EXf> Function


The EXP function calculates the mathematical exponential of its argument.
The exponential is defined as the constant e raised to the power of the
argument, where e = 2. 718281828. For example,
ExP c3> e to the 3rd power;
yields 20.0855369.
E X P C L□Gc u » e to the power of the natural
logarithm of 10; yields 10.
E X p C A .. T > e to the power A * T.
Limited Accuracy: Although Applesoft displays the result of the EXP
function to nine places, only the first six are actually reliable. For
instance, in the first example above, the computed result of 20.0855369
should be interpreted simply as 20.0855.

38 Chapter 2: Variables and Arithmetic


2.4. 1 . 1 0 The LOG Function
LOG calculates the natural logarithm of its argument (the logarithm to the
base e, where e = 2.718281828.) For example,
LOG C 1 0 ) Natural logarithm of 10;
yields 2.30258509.
LOG C E X P C 3 » Natural logarithm of e to the 3rd
power; yields 3.
L O G C S I IH T H E T A » Natural logarithm of the sine of
THETA.
If you try to take the logarithm of 0 or a negative number, an I L L E G A L
G U A N T,. I T Y error occurs.

2.4.2 Generating Random Numbers: The RND Function


The built-in function RND produces random decimal numbers between 0
and 1. The behavior of this function depends on whether the argument you
give it is positive, 0, or negative.
The simplest way to use RND is to give it a positive argument. RND
produces a different random number each time you call it with a positive
argument. The actual numeric value of the argument is ignored; only its
sign is significant:
RND C D Yields .431448496.
RND C D Yields .735966024.
R N D C 99 ) Yields .345445325.
If you give RND a 0 argument, it reproduces the same result as at the
previous call:
R N D C 99 ) Yields .270011996.
RND CID Yields .270011996.
RND C I D Yields .270011996.
R N D C 99 ) Yields .139756248.
RND C I D Yields .139756248.

2.4 Functions 39
Calling RND with a negative argument causes it to begin a new, repeatable
sequence of random numbers. This is called seeding the random number
generator; the particular negative value you use for the argument acts as a
seed for the new sequence. Different seeds produce different sequences;
but each time you use the same seed you get the same result. Subsequent
calls to RND with positive arguments then produce the same sequence of
results:
RND (-1) Yields 2.99196472E-08.
RND (1) Yields .738207502.
RND (1) Yields .272707136.
RND (1) Yields .299733446.
RND ( -5) Yields 3.73720468E-08; starts new
sequence.
RND ( 1 ) Yields .407457285.
RND ( 1 ) Yields .463740324.
RND ( 1 ) Yields .387195686.
RND ( - 1 ) Yields 2.99196472E-08; repeats same
sequence as before.
RND ( 1 ) Yields .738207502.
RND ( 1 ) Yields .272707136.
RND ( 1 ) Yields .299733446.
Scientific Notation: The suffix E-08 in some of the random values
listed above means times 10 to the minus-8th power, and is an
example of the scientific notation that Applesoft uses to display certain
numbers. See Section 5.2.3 for further details.

2.4.3 Defining Functions: The DEF FN Statement

D E F FN C U B E C X > = X * X * X
In addition to the built-in functions discussed in Sections 2.4.1 and 2.4.2,
Applesoft gives you the ability to define your own functions for the special
needs of a particular program. Defining your own functions can be a real
time-saver: instead of writing out the same complex formula over and over
again, you can simply define it once as a function, give it a name, and then
refer to it by that name whenever you need it.
To define a function of your own, use the DEF FN statement. This
statement consists of the keywords DEF FN (for define function) followed
argument: the value on which a function by the name of the function you're defining, the argument name enclosed in
operates parentheses, an equal sign ( = ), and the formula defining the function.

40 Chapter 2: Variables and Arithmetic


The following examples define functions to convert temperatures from
Fahrenheit to Celsius and vice versa, and to convert angles from degrees to
radians and vice versa, assuming that the value of the variable PI
is 3.14159265:
10 DEF FN FTC C T > • C T - 3 2 ) * S / 9
Fahrenheit to Celsius.
20 D E F F H CTF C T > • T • C 9 / 5 ) + 32
Celsius to Fahrenheit.
30 DEF FN DTR C A > • A • C P I / 1 8 0 )
Degrees to radians.
40 D E F F N RTD C A ) • A • C 1 8 0 / P I >
Radians to degrees.
For example, the definition for function FTC says to convert from
Fahrenheit to Celsius, take the value of the argument (T),
subtract 32, multiply by 5, and divide by 9.
I Formula Length Limit: The formula defining a function must not
exceed one program line (239 characters) in length.
The names you give to your functions must follow the same rules given in
Section 2. 1.1 for variable names: the name can be as long as you like (up to
239 characters), but Applesoft uses only the first two characters to
distinguish one function from another. The argument variable in the
function definition must be a real variable-integer and string variables
(ending in % or $) are not allowed.
Be Careful With Function Names: Take care not to begin the names
of different functions with the same two characters. Applesoft considers
the names CODFISH and COUNT, for example, to refer to the same
function, because they both begin with the same two characters. If you
try to define functions with these two names, the second definition
redefines the function, causing the first definition to be forgotten.
However, a program can have a function and an array beginning with the
same two characters (or even having exactly the same name). This is
because references to the function are written with the keyword FN, but
references to the array aren't. Thus Applesoft can tell that, for example,
FH COUHT C H )
is a call to the function named COUNT, whereas
COUHT C H >
is a reference to the array of the same name.

2.4 Functions 41
The DEF FN statement can be executed only from within a program; you
can't use this statement in immediate execution.
To call a function that you've defined with DEF FN, type the keyword FN
(for function) followed by the name of the function and an expression in
parentheses representing the argument value on which you want the
function to operate. For example, using the functions you defined,
F H F T C c s0 . G > Converts 98.6 degrees Fahrenheit to
Celsius; yields 37.
F ti C T F c 1 0 e > Converts 100 degrees Celsius to
Fahrenheit; yields 212.
F ti D T R c 1 0 e > Converts 180 degrees to radians;
yields 3.14159265.
F ti RTD c P 1 1 2 > Converts PI / 2 radians to degrees;
yields 90.
Note that the keyword FN is used in calling your own defined functions, but
not for built-in functions. (See Section 2.4.1.)

42 Chapter 2: Variables and Arithmetic


Chapter 3 Control Statements

..

43
Ordinarily, Applesoft program lines are executed sequentially, from the
lowest-numbered line to the highest. Control statements allow you to
branch to another part of the program: that is, to alter the order of execution
and send control to a line of the program other than the next line in
sequence. This ability to change the course of program flow is what gives
computer programs their real power and flexibility.
□ Section 3.1, "Unconditional Branching: The GOTO Statement," deals
with the GOTO statement, which sends control unconditionally to a
specified line of the program.
□ Section 3.2, "Conditional Branching," discusses conditional branching
statements, which allow the program to decide what to do next by
evaluating an expression or testing for a condition.
□ Section 3.3, "Loops," covers statements that are used in loops (portions of
a program that are executed many times repeatedly).
□ Section 3.4, "Subroutines," deals with the very important subject of
subroutines: sections of a program that can be executed on request from
elsewhere in the program to perform some particular task.
□ Section 3.5, "Error Handling," describes Applesoft's facilities for
detecting and dealing with error conditions that arise during the
execution of a program.
□ Section 3.6, "Program Termination," covers the various ways of ending
program execution.

3.1 Unconditional Branching: The GOTO Statement


GOTO 1 0 0

An unconditional branch sends control to a specified line of the program


without reference to whether any particular condition holds. Applesoft has
two statements that cause an unconditional branch: GOTO and GOSUB.
The GOTO statement is described in this section; see Section 3.4.1 for a
description of the GOSUB statement.
The GOTO statement interrupts the normal sequential execution of
program lines and forces execution to branch to (go to) a specified line
number. The branch is unconditional: that is, it doesn't depend on the truth
or falsity of any particular condition.

44 Chapter 3: Control Statements


For example, consider the following program:
1 0 PR I NT "HELLO" Displays the word H E L L O .
2 0 P R I NT "TH E R E " Displays the word TH E R E .
3 0 GOTO 1 0 Branches to line 10.
4 0 PR I N T " F R I E N D " This line never executed.
This program displays the word H E L L O on the screen (line 10), displays the
word TH E R E (line 20), and then (line 30) goes back to line 10 to repeat the
process. The word F R I E N D never gets displayed, because program
execution never reaches line 40. Instead, the program simply repeats
lines 10 to 30 indefinitely, displaying the words H E L L O and TH E R E over and
over again on the screen.
loops: see Section 3.3 Stopping an Infinite Loop: This program contains an example of an
infinite loop. To stop the program and regain control of the computer,
press �.
If your program attempts to branch to a nonexistent line, or if a GOTO
statement does not include a line number, an error message such as
? U N D E F ' D S T A T E M E N T E R R O R I N 2 0 appears, identifying the program
line in which the error occurred. The program stops and Applesoft returns
to command level.
10 PR I NT "HELLO"
20 P R I NT "TH E R E "
30 GOTO 1 5 Branches to nonexistent line.
40 P R I NT " F R I END"
You Can't Branch to a Variable: If you attempt to use a variable
instead of an actual line number to specify the line to which the program
should branch (as in GOTO J), Applesoft branches to line number 0, no
matter what value the variable holds. If line O doesn't exist, an U N D E F ' D · .
S T A T E M E N T error occurs:

5 LET J • 1 0 Assigns value to variable.


10 P R I NT "HELLO"
20 P R I NT "THE R E "
30 GOTO J Applesoft tries to go to line
number 0.
40 PR I NT " F R I E ND"

3.1 Unconditional Branching: The GOTO Statement 45


3.2 Conditional Branching

A conditional branch decides what action to take next, depending on the


truth of a stated condition or on the value of an arithmetic expression.
Applesoft has three statements that cause a conditional branch:
□ ON ... GOTO (see Section 3.2.1) branches to one of a number of possible
program lines, depending on the value of an arithmetic expression.
□ ON ... GOSUB (see Section 3.4.3) branches to one of a number of possible
subroutines, depending on the value of an arithmetic expression.
□ IF ... THEN (see Section 3.2.2) either executes or skips one or more
statements, depending on the truth of a stated condition.

3.2. 1 The ON ... GOTO Statement


OH X GOTO 1 5 B , 2 B B , 3 1 " , 3 1 " , 1 5 B , 999
OH 5% - 7 GOTO 3 B B , 285 , 9 B B , 1 5 B
The ON ... GOTO statement sends control to one of a list of line numbers,
depending on the integer value of an arithmetic expression. The expression
between the keywords ON and GOTO is evaluated; if the result is real it is
truncated to an integer. If this value is between 1 and the number of line
numbers in the list, program execution branches to the line number at the
corresponding position in the list. (For example, if the integer value of the
expression is 3, execution branches to the third line number in the list.) If
the integer value of the expression is O or is greater than the length of the
list, execution continues with the next statement following the ON ... GOTO.

46 Chapter 3: Control Statements


The following program illustrates the use of ON ... GOTO:
1 0 H I PUT X Gets number from keyboard.
20 ON X GOTO 1 5 0 , 2 0 0 , 3 1 0 , 3 1 0 , 1 5 0 , 999
Decides where to go, depending on
value of X.
30 P R I NT "VA L U E O U T OF R A N G E , P L E A S E R E T Y P E ; "
Control comes here if X = 0 or
X > 6.
40 GOTO 1 0 Starts again.
150 P R I N T " V A L U E I S 1 OR 5 "
Control comes here if X = 1 or
X = 5.
160 GOTO 1 0
20 0 P R I N T "VA L U E I S 2 " Control comes here if X = 2.
210 GOTO 1 0
310 P R I N T "VA L U E I S 3 OR 4 "
Control comes here if X = 3 or
X = 4.
320 GOTO 1 0
999 END Control comes here if X = 6.
If the integer value of the expression between ON and GOTO is less than 0
or greater than 255, an I L L E G A L Q U A N T I T Y error occurs and program
execution halts.

3.2.2 The IF . . . THEN Statement


IF Z > 255 THEN END
IF HX - 23 < SM - TTL THEN KX • HX - 23 H% • 0
IF X C I ) • 1 2 T H E N GOTO 3 2 5
IF A $ > < B$ THEN 3 0 0
IF C DE L T A > , 0 5 ) A N D N O T C E > . 1 > G O T O 2 1 5 0
The IF ... THEN statement tests for the condition given between the
keywords IF and THEN. If the condition is true, the statement or
statements following THEN in the same program line are executed. If the
condition is false, the remainder of the line following THEN is skipped and
execution continues with the next program line in sequence.

3.2 Conditional Branching 47


When You Can Omit a Keyword: When the statement following
THEN is a GOTO, either (but not both) of the keywords THEN and GOTO
can be omitted. The following statements are all equivalent:
I F X C I > • 1 2 T H E N GOTO 3 2 5
IF X C I > • 12 THEN 325
IF X C I > • 12 GOTO 325
Notice that when the IF condition is false, program execution continues
with the next program line in sequence. No other statements in the IF line
are carried out:
1 1! LET J • 1 : K • 2
2 1! L E T A • 1 ll A is set to 10 here.
3 1! P R I NT " J H O L D S '' ; J ; " A N D K H O L D S " ; K
4 1! I F A > 1 1! T H E N J • 5 K • 1 1! : GOTO 1 1l ll
A is not greater than 1 O; test fails.
S il P R I NT " T H E V A L U E S O F J A N D K A R E U N C H A NG E D . "
This message gets printed.
6 1! G O T O 999
1 1l ll P R I N T "J N O W H O LD S " ; J ; " A N D K H O L D S " ; K
This message is not printed.
999 END

When this program is run, the IF test in line 40 fails, the values of J and K
are not changed, and execution continues with line 50. If line 20 were
changed to
2 1! LET A • 25
then the IF test in line 40 would succeed, the values of J and K would be
changed, and control would branch to line 100.

48 Chapter 3: Control Statements


Using Numeric Values With /F... THEN: The IF... THEN statement
considers a numeric value of O to mean false; any nonzero value is taken
to mean true. Thus you can write statements such as
I F J TH E N G O S U B 4 0 0
which is equivalent to
I F J < > 0 THEN GOSUB 4 0 0
Recall also that Applesoft's relational and logical operators always yield a
value of 1 for true and O for false. Thus you can combine numeric values
with the logical operators: the statement
I F N O T J T H E N GOTO 5 0 0
is equivalent to
I F J • 0 T H E N GOTO 5 0 0
and
I F A AND B THEN END
is equivalent to
I F C A < > 0 ) AND C B < > 0 ) THEN END
Numeric values used in this way offer two advantages over the
corresponding relational expressions:
□ They take up less space in memory.
□ They execute somewhat faster.
See Appendix G for further hints on making your programs more
efficient.
Curious Parsing: Applesoft gets confused if the keyword THEN is
immediately preceded by a variable name ending in the letter A. For
example, the statement
I F J = BETA T H E N 2 3 0
is interpreted as
I F J • B E T AT H E N 2 3 0
causing a syntax error. This is because AT and THEN are both reserved
words. In the example, the word AT is encountered first, so it is
interpreted first. Such is life with Applesoft. You can get around the
problem by using parentheses:
I F C J = BETA > T H E N 2 3 0

3.2 Conditional Branching 49


3.3 Loops
A loop is a sequence of statements in a program that is executed
repeatedly, often with the value of some variable being changed on each
pass through the loop. Loops are fundamental to all computer programming:
it's practically impossible to write any kind of useful or interesting program
that doesn't include at least one loop.
The usual way of writing loops in Applesoft is with the FOR (see
Section 3.3.1) and NEXT (see Section 3.3.2) statements. The FOR statement
marks the beginning of the loop. It identifies the loop's index variable (the
variable whose value changes on each pass through the loop) and gives the
starting and ending values the index variable is to take on. Sometimes it
also specifies the amount by which the value of the index variable is to
change on each pass.
The NEXT statement marks the end of the loop and causes the loop to be
executed again for the next value of the index variable. When the loop has
been executed once for each value of the index variable, as specified in the
FOR statement, control passes (falls through) to the statement immediately
following the NEXT statement.
Here's an example to show how loops work:
5 PASS • 0 Initializes pass count.
1 0 F O R X • 3 TO 1 0 Executes loop eight times, once for
each value of X from 3 to 10.
20 PASS • PASS + 1 Counts passes through the loop.
4 0 P R I NT " I N D E X .
3 0 P R I NT " P A S S ' " ; P A S S
II
;
Displays pass count.
Displays current value of index
X

variable X.
5 0 P R I NT Displays blank line (for neatness).
60 NEXT X Repeats loop for next value of X.
7 0 P R I NT " L O O P F I N I S H E D " Control comes here after last pass
through loop.
80 END
The loop begins with the FOR statement in line 10, which specifies that the
loop is to be executed once for each value of index variable X from 3 to 10.
Lines 20 to 50 form the body of the loop. The NEXT statement in line 60
marks the end of the loop and sends control back to line 20 for the next
value of X. After the loop is executed for the last time, with X set to the
specified ending value of 10, X is increased to 11. Since this exceeds the
ending value, control falls through the NEXT statement to line 70.

50 Chapter 3: Control Statements


When this program is executed, it displays the following results on the
screen:
PASS # 1
I N DE X • 3
PASS #2
I ND E X • 4
PASS #3
I ND E X • 5
PASS #4
I ND E X • 6
PASS #5
I ND E X • 7
P A S S #6
I N DE X • 8
PASS #7
I ND E X • 9
PASS #8
I ND E X • 1 0
LOOP F I N I SHED
Loop Before You Leap: Exiting from the middle of a FOR/NEXT loop
before the index variable reaches the ending value leaves Applesoft
expecting a resolution that never comes. This is a dangerous practice that
can cause unpredictable results in your program's execution. Don't write
loops of the form
10 F O R I N D E X • L O W TO H I GH
20 LET COUNT • COUNT + 1
30 I F C O U N T • L I M I T T H E N GOTO 1 0 0
40 NEXT I NDEX
To be on the safe side, it's better to finish the loop this way:
30 I F C O U N T • L I M I T TH E N I NDE X • H I GH :
N E X T I NDE X : GOTO 1 0 0

3.3 Loops 51
3.3. 1 The FOR Statement
FOR V • 1 TO 1 0
FOR MASS • 3 . 5 TO 7 STEP 1 . 5
FDR V E A R • 1 98 0 TD 1 96 0 S T E P - 4
FDR V • A + 2 T D 2 * B - 3 STEP C / 2
The FOR statement marks the beginning of a loop, identifies the loop's
index variable, and gives the starting and ending values of the index
variable. It may also optionally specify the step value, the amount by
which the value of the index variable is to change on each pass through the
loop. If no step value is given, a value of 1 is understood.
In the example in Section 3.3, no step value was given, so the index
variable X was incremented by 1 on each pass through the loop. If line 10 in
the example were changed to
10 F O R X = 3 TD 1 0 S T E P 2
the program would execute a loop for each value of X from 3 to 10 by 2s and
would produce the following output on the display screen:
PASS # 1
I HD E X • 3

PASS '2
I HDEX • 5

PASS #3
I HDEX • 7

PASS #4
I HDE X • 9

LOOP F I H I SHED
The loop would be executed four times, with the index variable taking on
values of 3, 5, 7, and 9. At the end of the fourth pass, the index variable
would exceed the specified ending value (9 plus 2 is 11, which is greater
than the ending value of 10), so the loop would end and execution would
continue with the statement following the NEXT in line 60.

52 Chapter 3: Control Statements


Applesoft Will TryAnything Once: Notice that the test to see whether
the index variable exceeds the ending value is carried out at the end of
the loop. This means the body of the loop is always executed at least
once. Even if the specified starting value is greater than the ending value,
as in
10 F D R X • 1 0 TD 3
it won't be discovered until after the loop has been executed once
(10 plus 1 is 11, which is greater than 3).
It's also possible to specify a negative step value:
10 F D R X • 1 0 T D 3 STEP - 2
In this case the index variable takes values of 10, 8, 6, and 4. When the step
value is negative, the loop ends when the index value becomes less than the
ending vaiue (4 plus -2 is 2, which is less than the ending value of 3). Notice
that the starting and ending values have been reversed; if the statement
read
10 F D R X • 3 TD 1 0 STEP - 2
the loop would be executed only once (3 plus -2 is 1, which is less than 10).
Stopping an Infinite Loop: A step value of O results in an infinite loop.
To stop the program and regain control of the computer, press
�-
The index variable specified in a FOR statement must be a real variable.
Attempting to use an integer variable, such as
10 F D R X X • 3 TD 1 0
causes a syntax error at run time. (However, the expressions for the
starting, ending, and step values are unrestricted; any or all of these values
can be specified by an integer variable.)

3.3.2 The NEXT Statement


HEXT
H E X T I N DE X
HEXT J , I
The NEXT statement marks the end of a loop and causes the loop to be
repeated for the next value of the index variable, as specified in the
corresponding FOR statement. When the value of the index variable

3.3 Loops 53
becomes greater than the specified ending value (less than the ending value
if the step value is negative), execution proceeds with the statement
immediately following the NEXT statement.
Naming the index variable in a NEXT statement is optional; if you omit it,
Applesoft automatically repeats the most recently entered loop. If you're
using nested loops (see Section 5.3.3), this means the innermost loop
containing the NEXT statement is repeated.
Helpful Hint: Leaving out the index variable in NEXT statements
makes your programs run slightly faster:
10 FOR G • 1 TO 6
20 P R ili T " W O W , M O M ! "
30 H E XT No index variable necessary.

3.3.3 Nesting of Loops


FOR/NEXT loops can be nested one inside another to a maximum depth of
ten levels. For example,
10 F O R A • 1 TO 3 Starts outer loop.
20 F O R B • 1 TO 2 Starts inner loop.
30 P R I HT "A • " ; A ; " B = "; B
Displays values of index variables.
40 HE xT B Repeats inner loop.
s0 HEXt A Outer loop is not repeated until
inner loop is finished.
The inner loop (lines 20 to 40) is executed twice for each pass through the
outer loop; the PRINT statement in line 30 is executed six times in all. This
program displays the following on the screen:
- -
A 1' B
. 1

-
A = 1' B
. 2
A
-
2, B
- 1
A
-
2, B
- 2
A
A -
3, B
3, B - 1
2

54 Chapter 3: Control Statements


Although this example shows only two levels of nesting, Applesoft allows as
many as ten levels (a loop inside a loop inside a loop ... ten times). If you nest
your loops to a depth greater than ten, your program halts with an □ U T O F
M E M O R Y error message.

Nested loops must not cross each other-that is, each loop must be
completely contained within the body of the next outer loop. Once a loop is
started using a particular index variable, the corresponding NEXT must
name the same index variable (if it names any at all). In the example above,
if lines 40 and 50 were reversed
40 NEXT A Attempts to repeat outer loop
50 NEXT 8 before inner loop is finished.
the program would halt with an error because of the crossed loops.
Combining NEXT Statements: When two or more NEXT statements
occur in a row, you can combine them into a single NEXT statement of
the form
40 NEXT 8 , A
Notice, however, that the index variables must be listed in the reverse
order of their corresponding FOR statements, to avoid crossing loops. The
statement
40 NEXT A , 8

causes the program to end abruptly with the messsage N E X T w r T H O U T


FOR ERROR.

3.4 Subroutines
A subroutine is a section of a program that can be executed on request
from another part of the program. Applesoft has four statements relating to
subroutines:
□ GOSUB (see Section 3.4. 1) directs control to a particular subroutine.
□ RETURN (see Section 3.4.2) sends control back to the statement
following the GOSUB that branched to the subroutine.
□ ON ... GOSUB (see Section 3.4.3) selects one of a number of possible
subroutines, depending on the value of an arithmetic expression.
□ POP (see Section 3.4.4) removes a return address from the top of the
control stack (see the box entitled "How Subroutines Stack Up" later in
this section).

3.4 Subroutines 55
To call a subroutine (request its execution), branch to its first line with a
GOSUB statement. GOSUB differs from an ordinary GOTO (see Section 3.1)
in that it remembers where in the program the subroutine was called from,
so that control can return to that point when the subroutine is finished. The
same subroutine can be called from many different places in the program;
when the subroutine is finished, it sends control back to the statement
following the proper point of call by executing a RETURN statement.
Here's an example to illustrate the idea:
10 F O R Z • 1 TO 1 0 Executes loop ten times.
20 LET X = I HT C RHD < 1 > * 1 0 0 )
Generates a random integer
between O and 99.
30 PR I HT x " I s " ; Displays first part of message.
40 I F X < 5 0 THEH GOSUB 1 0 0 0 : GOTO 6 0
Branches to subroutine at line 1000
if random number is less than 50; on
return, goes to line 60.
50 Gos uB 2 0 0 0 Branches to subroutine at line 2000
if random number is 50 or greater.
60 PR I NT "PASS "" ; Z P R I NT
Counts number of passes through
loop.
70 HEXT Z Repeats loop.
999 E H D Ends program.
1000 P R I H T " L E S S T H A H 5 0 " Prints second part of message for
numbers less than 50.
1 0 1 0 RETURH Returns to statement following
point of call.
2 0 0 0 P R I N T " M O R E T H A H 4 9 " Prints second part of message for
numbers greater than 49.
2 0 1 0 RETURN Returns to statement following
point of call.
The loop in lines 10 to 70 generates a random integer between O and 99,
then calls one of the two subroutines at lines 1000 and 2000, depending on
the value of the random number. Each of the subroutines displays an
appropriate message, then returns control to the statement following the
point of call with a RETURN statement (lines 1010 and 2010). The program
then displays a count of the number of passes through the loop and repeats
the loop from the beginning. When the loop has been executed ten times,
the program ends.

56 Chapter 3: Control Statements


Notice that the RETURN statement returns control to the statement
following the GOSUB statement, not just to the line following it. In line 40
of the example, if the random number generated is less than 50, control is
directed to the routine at line 1000. When execution returns from the
subroutine, it continues with the statement GOTO 60, branching around
line 50.
Don't Use the Back Door: Every subroutine should be regarded as a
separate, indivisible unit of your program, which should be entered only
with a GOSUB and exited only with a RETURN. Careful programmers
avoid jumping into or out of the middle of a subroutine with an ordinary
GOTO which subverts Applesoft's orderly control stack mechanism. (See
"How Subroutines Stack Up," later in this section.)
Subroutine calls can be nested: that is, you can call one subroutine from
inside another. Consider the following program:
10 GosuB 1 0 0 0 Branches to first subroutine.
20 P R I N T " BA C K H O M E AGA I N " This message is displayed last.
30 END Prevents control from accidentally
"falling into" a subroutine.
1000 P R I NT "F I R S T S U B R O U T I N E C A L L E D "
This message is displayed first.
1010 GOSUB 2 0 0 0 Branches to second subroutine.
1 020 P R I N T " BA C K A T F I R S T S U B R O UT I N E "
This message is displayed third.
1 0 30 RETURN Returns to statement following
point of call (line 20).
20 0 0 P R I N T " S E C O N D S U B R O U T I N E C A L L ED"
This message is displayed second.
20 1 0 RETURN Returns to statement following
point of call (line 1020).

3.4 Subroutines 57
Line 10 calls the first subroutine, at line 1000. This subroutine displays the
first message on the screen, then (line 1010) calls the second subroutine at
line 2000. The second subroutine displays its message, then returns control
(line 2010) to the statement following the point of call in the first
subroutine. The first subroutine then displays another message and returns
control (line 1030) to the statement following its point of call. The final
message is then displayed (line 20) and the program ends. The lines of the
program are executed in the following order:
Line 10
Line 1000
Line 1010
Line 2000
Line 2010
Line 1020
Line 1030
Line 20
Line 30
The program produces the following output on the screen:
F I RST SUBROUT I NE CALLED
SECOND SUBROUT I NE CALLED
BACK AT F I RST SUBROUT I N E
B A C K H OME AGA I N
How Subroutines Stack Up: Applesoft maintains a control stack to
keep track of the return addresses-the points to which control is to
return on completion-for all subroutines in progress. Each time a
GOSUB is executed, the location of the statement following the GOSUB is
pushed onto the top of the stack. When a RETURN statement is
executed, the top entry is popped from the stack and control is directed
to that point in the program. This arrangement ensures that control
enters and leaves subroutines in LIFO (last-in-first-out) order.
Subroutine calls can be nested up to 25 levels deep: that is, you can GOSUB
from a GOSUB from a GOSUB ... 24 times. Attempting to go more than
25 levels deep results in an o u T OF M E M O R Y error. If this error occurs,
you're actually out of stack space, as opposed to program space. Since no
rational BASIC program ever uses such complex nesting, this error usually
means you've got a subroutine accidentally calling itself.

58 Chapter 3: Control Statements


3.4. 1 The GOSUB Statement
G O S U B 1 lil lil lil

The GOSUB (for go to subroutine) statement is used to branch to a


subroutine, saving a return address to which control can return when the
subroutine is completed. The location of the statement immediately
following GOSUB is pushed onto the control stack (see Section 3.4), and
control is sent to the line number specified in the GOSUB statement.
GOSUB differs from an ordinary GOTO (see Section 3. 1) in that it
remembers where in the program the subroutine was called from, so that
control can return to that point when the subroutine ends with a RETURN
statement.
A GOSUB to a target line that doesn't exist causes a message such as
? U N D E F ' D S T A T E M E N T E R R O R r n 1 3 5 lil to be displayed, identifying
the line number in which the error occurred, and your program comes to an
untimely halt.

3.4.2 The RETURN Statement


RETURN

The RETURN statement returns control from a subroutine to the statement


following its point of call. The top entry is popped off the control stack and
control is sent to that return address.
If the control stack is empty when RETURN is executed, your program halts
with the message ? R E T U R N w I T H O U T G O S UB.

3.4.3 The ON ... GOSUB Statement


ON X G O S U B 1 5 lil , 2 lil lil , 3 1 lil , 3 1 lil , 1 5 lil , 999
ON SX - 7 G O S U B 3 lil lil , 2 8 5 , 9 lil lil , 1 50

The ON ... GOSUB statement sends control to one of a list of subroutines,


depending on the integer value of an arithmetic expression. The expression
between the keywprds ON and GOSUB is evaluated; if the result is real, it is
truncated to an in�eger. If this value is between 1 and the number of line
numbers in the list, program execution branches to the subroutine at the
corresponding position in the list. (For example, if the integer value of the
expression is 3, execution branches to the subroutine beginning at the third

3.4 Subroutines 59
line number in the list.) If the integer value of the expression is O or is
greater than the length of the list, execution continues with the next
statement following the ON ... GOSUB.
The following program illustrates the use of ON ... GOSUB:
10 I HPUT X Gets number from keyboard.
20 O H X G O S U B 1 5 0 , 2 0 0 , 3 1 0 , 3 1 0 , 1 5 0 , 999
Decides where to go, depending on
value of X.
30 I F X • 0 D R X • 6 T H E H P R I H T "VA L U E O UT O F R A HGE ,
P L E A S E R E T Y P E : II Displays message if X out of range.
4 0 GOTO 1 0 Starts again.
1 5 0 P R I H T "V A L U E I S 1 O R 5 "
Control comes here if X = 1 or
X = 5.
1 60 RETURH
200 PR I HT "VALUE I S 2" Control comes here if X = 2.
210 RETURH
310 P R I HT "VA L U E I S 3 D R 4 "
Control comes here if X = 3 or
X = 4.
320 RETURH
999 EHD Control comes here if X = 6.
Compare this program with the example given for the ON ... GOTO statement
in Section 3.2.1. The operation of ON ... GOSUB is very similar to that of
ON ... GOTO, except that ON ... GOSUB remembers where in the program the
subroutine was called from by pushing onto the control stack the location of
the next statement following ON ... GOSUB. Control can then return to that
point with a RETURN statement when the subroutine is finished.
If the integer value of the expression between ON and GOSUB is less than 0
or greater than 255, an I L L E G A L G U A H T I TY error occurs and program
execution halts.

3.4.4 The POP Statement

POP
The POP statement removes (pops) the top return address from the control
stack without sending control to that point. This causes the next RETURN
statement to send control back to the point of the second most recent
subroutine call, instead of the most recent.

60 Chapter 3: Control Statements


Here's an example illustrating the use of POP:
1 0 GO s u B 1 0 0 0 Branches to first subroutine.
2 0 P R I N T "BACK H O M E AGA I N " This message is displayed last.
30 EHD Prevents control from accidentally
"falling into" a subroutine.
1000 PR I NT "F I RST SUBROUT I NE CA LLED"
This message is displayed first.
1010 GOSUB 2 0 0 0 Branches to second subroutine.
1 020 PR I NT "BACK AT F I RST SUBROUT I NE"
This message is never displayed.
1 030 RETURN This return is never taken.
2000 P R I NT " S E C O N D S U BR O U T I N E C A L L E D"
This message is displayed second.
2005 POP Removes return address from stack.
20 1 0 RETURN Returns to first subroutine's point of
call (line 20).
This program is identical to the one in Section 3.4 illustrating nested
subroutine calls, except that a POP statement (line 2005) has been added to
the second subroutine. The effect of the POP is to remove the second
subroutine's return address (line 1020) from the control stack, causing the
RETURN in line 2010 to go back to the statement following the point of call
of the first subroutine (line 20) instead. As a result, lines 1020 and 1030 are
never executed, and the message B A C K A T F I R S T S U B R O U T I H E is
never displayed. The lines of the program are executed in the following
order:
Line 10
Line 1000
Line 1010
Line 2000
Line 2005
Line 2010
Line 20
Line 30
The program produces the following output on the screen:
F I RST SUBROUT I NE CALLED
SECOND SUBROUT I N E CALLED
B A C K H O M E AGA I N
If the control stack is empty when POP is executed, your program halts
with a R E T U R N w I T H O UT GO S U B error.

3.4 Subroutines 61
Resist Temptation: Although it's sometimes tempting to try to get out
of a tight programming situation by using POP, most good programmers
avoid it, because it makes program flow really difficult to follow. If you
find yourself becoming ensnared in convoluted code, 'tis a far better thing
to redesign your program than to resort to the use of POP. Refer to
Chapter 8 for a tutorial on program planning.

3.5 Error Handling


Sometimes even the most carefully written program comes to an
embarrassing halt at an inopportune moment because of an error. If you've
never suffered an "error crash," you're not a programmer. Applesoft's
ONERR GOTO (see Section 3.5.1) and RESUME (see Section 3.5.2)
statements provide a mechanism for detecting program errors as they occur
and dealing with them from within your program. Using these statements,
you can make your program display its own error messages or take any
other action you consider appropriate, instead of coming to a sudden,
screeching stop.

3.5. 1 The ONERR GOTO Statement


O N E R R GOTO 2 0 0 0 0
The ONERR GOTO statement turns off Applesoft's normal error handling
and replaces it with an error-handling subroutine in your program. After
this statement is executed, program errors no longer stop the program, but
instead transfer control to the error routine beginning at the specified line
number.
Before sending control to the error routine, Applesoft stores an error code
identifying the type of error at a special location in the computer's memory,
location 222. The error routine can then look at the contents of this location
with the PEEK function (see Section 7.1.1) and decide what action to take,
depending on the error. Table 3-1 lists the possible error codes and their
meanings. See Appendix E, for further information on the conditions that
cause each type of error.

62 Chapter 3: Control Statements


Table 3-1. Error Codes

Code Meaning
0 NEXT without FOR
16 Syntax error
22 RETURN without GOSUB
42 Out of data
53 Illegal quantity
69 Overflow
77 Out of memory
90 Undefined statement
107 Bad subscript
120 Redimensioned array
133 Division by 0
163 Type mismatch
176 String too long
191 Formula too complex
224 Undefined function
254 Bad response to INPUT statement
255 CONTROL-C interrupt attempted

To prevent an error from interrupting the program, the ONERR GOTO


statement must be executed before the error occurs. If you're using ONERR
GOTO, it's a good idea to make it one of the first lines in your program, as in
the following example:
1 0 O N E R R GOTO 2 1 5 0 0 Establishes error routine at
line 21500.

2 1 500 L E T E C = P E E K ( 2 2 2 ) Gets error code.


21510 I F EC < > 255 THEN 2 1 55 0
Branches if not �-
2 1 520 P R I N T " S O R R Y - - P ROGRAM C A N ' T BE STO P P E D W I TH
CONTR O L - C " If user pressed �,
displays special message ...
2 1 530 R E S UME . . . and resumes program
2 1 550 PR I NT "UNANT I C I PATED E R R O R , CODE " ; EC
On any other error, displays general
message ...
2 1 560 STOP . . . and halts

3.5 Error Handling 63


This program uses its own error-handling routine to prevent the user from
interrupting execution by pressing �- Line 10 turns off
Applesoft's normal error handling and substitutes instead the program's
own error routine, beginning at line 21500.
If an error later occurs, the first thing the error routine does (line 21500) is
get the error code from memory location 222 to find out what type of error
occurred. The error code is assigned to variable EC to make it easier to
handle. Line 21510 tests for an error code of 255, meaning "�
interrupt attempted" (see Table 3-1). If the error is a �. the
message S O R R V - - P R O G R A M C A H ' T B E ST O P P E D W I T H C O M T R O L - C
is displayed on the screen (line 21520) and control is sent back to the point
of the error with the RESUME statement in line 21530.
If the error isn't a �. the IF ... THEN test in line 21510 sends
control to line 21550. Since the error routine has no special action to take for
any of these other errors, and since Applesoft's normal error messages are
not being displayed, the error routine just displays a general error message
such as U M A M T I C I P A T E D E R R O R , C O D E 1 6 (for a syntax error) and
stops the program.
... warning Once an ONERR GOTO statement has been executed, ordinary error
messages are not displayed and the program does not stop if an error is
detected. If your program's own error routine doesn't take some
appropriate action ( such as stop) for every possible error code, the
program may hang indefinitely or exhibit other forms of deviant behavior.
Make sure your error routine tells the computer what to do in all possible
cases of error; see "More PEEKing" for suggestions.
More PEEKing: In the preceding program, the general error message
displayed in line 21550 would be more useful if it included the line
number where the error occurred as well as the error code itself. Through
the magic of the PEEK function (see Section 7 .1.1 ), the following two
lines (replacing line 21550 of the original example) do this:
2 1 55 0 EL • PEEK C 2 1 9 > * 256 + PEEK ( 2 1 8 >
Gets error line.
2 1 555 P R I MT "UMAMT I C I PATED ERROR , C ODE " ; EC ; ",
I M L I 1-1 E " ; E L Displays general error message.
For an even nicer way of handling unanticipated errors, see Section 3.5.3
and Appendix F.
The ONERR GOTO statement can be executed only from within a program;
you can't use this statement in immediate execution.

64 Chapter 3: Control Statements


3.5.2 The RESUME Statement
R E SUME
The RESUME statement returns control from an error-handling routine to
the statement in which the error occurred. It should be used only in error
routines, and should never be encountered in the normal flow of control.
.._Warning If Applesoft encounters a RESUME statement without an error having
occurred, the program may stop or hang indefinitely, or other
unpredictable, but probably unpleasant, events may happen.
Notice that when an error has occurred, RESUME sends control back to
the same statement that caused the error in the first place. I f the same
error occurs again, the program may hang in an infinite loop. Similarly, if
an error occurs within the error-handling routine itself, RESUME causes
the program to hang.
Cleaning the Stack: When an error occurs while an ONERR GOTO
statement is in effect, Applesoft pushes certain information onto its
internal control stack before transferring control to the error routine.
When you leave the error routine with a RESUME statement, these
control codes are automatically popped off the stack. But if the error
routine ends with a GOTO instead of a RESUME, the control codes remain
behind on the stack and will probably cause your program to crash
unexpectedly. Always clean up the stack by using
CALL statement: see Section 7.1.3 C A L L - 3 2 88
before leaving an error routine with a GOTO statement.
The RESUME statement should be executed only from within a program.
Attempting to use this statement in immediate execution may cause a
syntax error, cause the system to hang, or begin executing an existing or
even a deleted program.

3.5.3 Restoring Normal Error Handling

You can restore Applesoft's normal error-handling mechanism by using the


POKE statement (see Section 7. 1.2)
POKE 2 1 6 , 0
After executing this statement, Applesoft goes back to stopping the program
when an error occurs and displaying its usual error messages.

3.5 Error Handling 65


One use of this technique is to prevent your program from hanging or falling
Monitor program: see your Apple's into the Monitor in case an error occurs in the error-handling routine itself.
reference manual You can do this by restoring normal error handling with POKE 216,0 at the
beginning of your error routine, then reactivating the error routine with
ONERR GOTO before returning to the main program. Here's another version
of the sample program in Section 3.5.1 that illustrates this technique:
1 0 O N E R R GOTO 2 1 5 0 0 Establishes error routine at
line 21500,

21 500 PoKE 2 1 6 , 0 Restores normal error handling.


21 505 LET E C • PEEK c 22 2 > Gets error code.
21510 I F EC < > 255 THEN 2 1 54 0
If not �. resumes
program under normal error
handling.
2 1 520 P R I H T " S O R R Y - - P R O G R A M C A N ' T BE S T O P P E D W I T H
coNTROL - C " If user pressed �,
displays special message ...
2 1 53 0 O N E R R GOTO 2 1 5 0 0 . . . reactivates this error routine ...
2 1 54 0 RE SUME . . . and resumes program.

This program also illustrates another application of POKE 216,0. Notice that
if the error is anything other than a � interrupt (code 255), the
IF ... THEN test in line 21510 sends control directly to the RESUME
statement in line 21540, without executing the ONERR GOTO in line 21530.
The effect of this is to re-execute the statement containing the original
error, but with Applesoft's normal error handling still in effect. This causes
the same error to occur again, but this time Applesoft displays its normal
error message and halts the program. Thus � is the only error
that gets special handling; all other errors produce the same results as if
there were no special error routine.

66 Chapter 3: Control Statements


3.6 Program Termination
The STOP and END statements are used to halt the execution of a program.
The only difference between them is that STOP displays a message giving
the number of the line at which execution was halted; this information is
debugging: finding and correcting errors useful primarily for debugging purposes. END simply stops the program
in a program without any message, and is usually used at a program's natural finishing
point.

3.6. 1 The STOP Statement


STOP
The STOP statement halts execution of the program and displays a message
giving the number of the program line in which the STOP occurs. For
example, the line
1 1 5 STOP

displays the message


BREAK 1 H 1 1 5
Applesoft returns to its command level, allowing you to enter new lines,
examine or change the values of variables, and so on. You can then resume
the execution of the program using the CONT command. (See Section 1.3.3.)

3.6.2 The END Statement


EHD

The END statement halts execution of the program and returns control to
Applesoft's command level. No message is displayed on the screen; program
execution just stops quietly.
999 E H D
An END statement is purely optional at the end of a program. The program
ends by itself, even without an END statement, when it runs out of
statements to execute.

3.6 Program Termination 67


Chapter 4 Arrays and Strings





fl,

69
This chapter discusses two important forms of data on which Applesoft
programs can operate: arrays and strings. Both topics were treated briefly in
Chapter 2, "Variables and Arit}unetic," but are covered in more detail here.
□ Section 4.1, "Arrays," deals with collections of related information of any
type (real, integer, or string), referred to by the same name and
distinguished by means of numerical subscripts.
□ Section 4.2, "Strings," describes Applesoft's facilities for manipulating
strings of characters such as words or names: comparing them,
concatenating (chaining) them together, taking them apart, and
converting them to and from numeric values.

4. 1 Arrays
An array is a collection of variables referred to by the same name, usually
holding data items that are related to each other in some logical or
systematic way. The individual variables in the array are called its
elements, and are distinguished from one another by means of identifying
index numbers called subscripts.
An array can be of any type: integer, real, or string. Array names follow the
same rules as simple variable names of the same type. To refer to a
particular element of an array, write the array name followed by one or
more subscripts, separated by commas and enclosed in parentheses. The
subscripts refer to the position of the desired element within the array:
G c6> Element 6 of real array Q.
F r GU R E x c to Element N of integer array
FIGURE%.
NAME s c J - 3 > Element J - 3 of string array
NAME$ .
C O U N T ( S UM % , 2 ) Element (SUM%, 2) of real array
COUNT.
Figure 4-1 shows a real array named R with five elements, numbered 0 to 4.
Element R(0) (pronounced R-sub-zero) holds the value 53, R(l)
holds 27.35, and so on. If the value of variable S is 2, then the
expression R(S) refers to element R(2), whose value is 31.4, and the
expression R(S + 2) refers to element R(4), which holds the value 19.

70 Chapter 4: Arrays and Strings


Figure 4-1 A Real Array

array R

R (O) - 53

R ( l) - 27.35

R (2) - 31 . 4 -- R (S)

R (3) - 6

R (4) - 19 +-- R (S + 2)

Another example is shown in Figure 4-2, this time a string array named
NAME$ with seven elements, numbered O to 6. Element NAME$(1) holds
the string value "SCOT", NAME$(3) holds the value "BRUCE", NAME$(6)
holds "MEG", and so on. If the value of variable C% is 5, then the expression
NAME$(C%) refers to element NAME$(5), whose value is "J.D.", and the
expression NAME$(C%- 3) refers to element NAME$(2), which holds the
value "BITZEL".

Figure 4-2. A String Array


array NAME$

NAME$ (0) ­ "BANA"

NAME$ (1 ) ­ "SCOT"

NAME$ (2) ­ "BITZEL" - NAME$ (C% - 3)

NAME$ (3) ­ "BRUCE"

NAME$ (4) ­ "SUSAN"

NAME$ (5) ­ "J.D. " - NAME$ (C%)

NAME$ (6) - "MEG"

4. 1 Arrays 71
4. 1 . 1 The DIM Statement
DIM R C4>
DIM T I TL E $ C 1 0 0 >
DIM HS CJX>
DIM MARKX C 3 , C I S , P + 2>

The DIM (for dimension) statement defines the size of an array and
allocates memory space for its elements. The expressions in parentheses
following the array name give the dimensions of the array. There can be
from 1 to 88 dimensions.
Once an array has been defined in a DIM statement, any reference to that
array with a different number of subscripts, or with a subscript that
exceeds the maximum specified for that dimension in the DIM statement,
causes the program to halt with a BA D S U B S C R I P T E R R O R message.
Arrays are limited in size by the amount of available memory. See
Section H.2 for detailed information on the amount of space required by
each type of array.
Subscripts Start From 0: Since array subscripts in Applesoft begin
with O (not 1 ), there is actually one more than the specified number of
subscripts in each dimension. For example, the array TITLE$ defined in
the second example has 101 (not 100) elements. In the definition
D I M TEST C 1 2 , 3 , S >

array TEST has 312 elements (13 times 4 times 6), not 180 (12 times 3
times 5) as you might expect.
When Applesoft encounters a reference to an array that has not yet been
defined in a DIM statement, it automatically allocates space for
11 subscripts (0 to 10) in each dimension of the array. Later attempting to
redefine the same array with a DIM statement causes an error stop with the
message ? R E D I M ' D A R R A v E R R a R. Defining the same array in more than
one DIM statement, or executing the same DIM statement twice, produces
the same message.

4.1 .2 Multidimensional Arrays


The examples shown in Figures 4-1 and 4-2 are both one-dimensional
arrays. Actually, arrays in Applesoft can have as many as 88 dimensions,
subject to the amount of memory available. Arrays of 88 dimensions aren't
terribly useful, but those of 2 and 3 dimensions often are.

72 Chapter 4: Arrays and Strings


Figure 4-3a shows an example of a two-dimensional array named EGGS that
has been defined by the DIM statement
D I M EGGS ( 1 , 5 )

Figure 4-3a. A Two-Dimensional Array


array EGGS
column column column column column column
0 I 2 3 4 5
row o ­ (O.o) (0, 1 )
---
(0, 2) (0, 3)
---
(0,4) (0,5)

row J - (l.o) (1,1 ) (1,2 ) (1 ,3) (1 ,4) (1 ,5)

For the newly perplexed, an analogy may be helpful. Think of the array as
an empty egg carton. On the outside is written the word EGGS. When you
open the egg carton, there are a dozen cup-like indentations where the eggs
go-two rows of six cups each-corresponding to the elements of the array.
Each of the cups is identified by a row number, 0 or 1, and a column number
from O to 5 (we're dealing with strange chickens here).
Now suppose you place three eggs in the egg carton, in elements (0,2), (0,5),
and (1,3):
L E T EGGS ( 0 , 2 ) • " E GG "
L E T E GG S < 0 , 5 ) • " EGG"
LET EGGS < 1 , 3 ) s " E GG "
Figure 4-3b shows the result.

Figure 4-3b. A Two-Dimensional Array


array EGGS
column column column column column column
0 I 2 3 4 5

4 .1 Arrays 73
You might also elect to use your egg carton to hold small change. If you put
a nickel in position (0,1), a dime in position (1,1), and a quarter in
position (1,4)
L E T EGGS ( 0 , 1 ) • 5
L E T EGGS C 1 , 1 > • 1 0
L E T EGGS ( 1 , 4 ) • 2 5
your carton would look like Figure 4-3c.

Figure 4-3c. A Two-Dimensional Array


array EGGS

�, -
column column column column column column
0 1 2 3 4 5

row ! --+
1 J-+o-1�1 l-� 1�1 EGG

Scrambled Analogy: Actually, of course, you can't store eggs in your


Applesoft arrays, only numbers and strings-but, after all, analogies
aren't always eggsact.

4.2 Strings
A string is a sequence of text characters (letters, digits, and punctuation
marks). Just as you can write numeric constants such as 27 and 2.236 in
your Applesoft programs, you can write string constants by enclosing the
characters in the desired string between double quotation marks:
"ON SALE FOR $49.95"
"Truth is impervious to hissing"
"H2SO4"
"???"
Lowercase Okay: Even though your version of Applesoft may not
understand lowercase letters when you use them in keywords, it allows
you to use them in a string constant, as shown in the second example .

74 Chapter 4: Arrays and Strings


A string can contain from O to 255 characters; when it contains no
characters it is called a null string. Two quotation marks with nothing
between them denote the null string:
1111

A string variable can hold any string as its value. Its name must end with a
dollar sign ($). Some legal string variable names are
TITLE$
G2$
D$
Until they are given some other value with an assignment statement, all
string variables are preset to the null string.

4.2. 1 Comparison of Strings: The ASCII Code


The characters in a string are represented inside the computer in the form
of numbers from O to 127. The correspondence between these internal
character codes and the characters they represent is based on a nationwide
computer-industry standard called the American Standard Code for
Information Interchange, or ASCII (pronounced asky). For instance, ASCII
code 65 represents the uppercase letter A, 112 represents a lowercase p,
52 represents the digit 4, 43 represents a plus sign (+), and so on. For a
complete table of ASCII character codes and the characters they represent,
see Appendix C.
Like numbers, strings can be compared with each other using the relational
operators. The result of the comparison is based on the ASCII codes of the
characters in the strings. Applesoft looks for the first nonidentical
characters in the two strings and compares them by ASCII code to decide
which is greater. For example, the character F (ASCII 70) is considered
greater than the character D (ASCII 68) but less than the character H
(ASCII 72). If one string is longer but begins with all the same characters as
the other string, the longer string is considered greater. For example,
"A" is less than "B"
"AA" is less than "AB"
"AB" is less than "BA"
"AB" is less than "ABC"

4.2 Strings 75
Strings and Alphabetical Order: Since letters of the alphabet are
represented by consecutive codes in the ASCII table, comparisons
between strings of alphabetic letters can be used to place the strings in
conventional alphabetical order. For example,
"E" is less than " F"
"ED" is less than "EDGAR"
"EDGAR" is less than "EDWARD"
"EDWARD" is less than "EDWARDS"
"EDWARD" is less than "FRANK"
There are a few surprises, however: since uppercase letters precede
lowercase letters in the ASCII chart,
"Zebra" is less than "aardvark"
And since strings are compared strictly character by character,
"48" is less than "5"
If you want to compare two strings consisting of digits according to the
numbers they represent, use the VAL function. (See Section 4.2.5.)

4.2.2 The LEN Function


The LEN (for length) function counts the number of characters in a string.
The argument can be a string constant, a string variable, or a concatenation
(see Section 4.2.3) of two or more strings. For example,
LEN ( "APPLE") Length of the string "APPLE";
yields 5.
LEN c SAMPLE$ > Length of the string contained in
variable SAMPLE$.
LEN c A $ + "* * *" + B$ > Length of the concatenation of
variable A$, string " * * * ", and
variable B$.

76 Chapter 4: Arrays and Strings


Using LEN, you can assign the length of a string to a numeric variable and
then use it in further operations:
1 ll L E T H X • L E H C "MY H E A R T S O A R S L I K E A
HAWK . " )
2 1l P R I HT "TH E R E A R E '' ; H X ; " C H A R A CT E R S
r n THE STR r HG . 11

When executed, this program displays the following output on the screen:
T H E R E A R E 2 7 C H A R A CT E R S I H T H E STR I H G .
If you use as LEN's argument a concatenation of two or more strings with a
combined length of more than 255 (the maximum allowable string length),
your program halts with the message ? STR I HG TOO L O H G E R R O R .
Instead of writing
LEH C A $ + BS + C S >
it's safer to use
LEH C A $ ) + LEH CB$ ) + LEH C C $ )

4.2.3 Concatenation of Strings


Concatenation means chaining together. To concatenate two or more
strings is to join them together into a new string containing all the
characters of the original strings. This operation is represented in Applesoft
by a plus sign ( + ):
"BOR I S " + II AHD II + " H A TA S H A "
Concatenation of the strings
"BORIS", " AND ", and "NATASHA";
yields the string
"BORIS AND NATASHA."
Fs + cs Concatenation of the contents of
string variables F$ and C$.
HS + "RATS ! " Concatenation of the contents of
string variable H$ with the string
constant "RATS!"
Hs + LE F n c c s , 4> Concatenation of the contents of
string variable H$ with the leftmost
four characters of the contents of
string variable C$.

4.2 Strings 77
The program
1 fJ L E T N A ME S • " C H A R L I E "
2 1! L E T T I TL E S • "DEAR " + NAME S + II
' II

3 1! P R I NT T I TL E $
4 1! P R I NT " H A V E W E GOT A S A L E ! "
displays the output
DEAR CHARL I E ,
H A V E WE GOT A S A L E !
on the screen. The program
1 1! L E T A $ • "GOOD "
2 1! L E T A S • A $ + "G R I E F ! "
3 1! P R I NT A $
displays
G O O D GR I E F !
If the result of a concatenation operation is a string more than
255 characters in length, the program halts with the error message
? S TR I NG T O O L O N G E R R O R .
You can test how long the result of a concatenation will be beforehand by
using the LEN function. For example:
1 1! LET A $ • "HAPPY DAYS"
20 LET L 1 • L EI'! < A S > How many characters in A$?.
31! L E T B S • " A R E H E R E AGA I N "
4 1! L E T L 2 • L EI'! < B S > How many characters in B$?
S il I F C L 1 + L 2 > < 2 5 6 T H E N LET A $ • A $ + B S
If the combined lengths of A$
and B$ are less than 256, combines
the two strings into A$.

78 Chapter 4 : Arrays and Strings


Concatenation Isn't Addition: Don't confuse the concatenation of
strings with the addition of numbers, even though both are represented in
Applesoft by the same symbol ( + ). The value of the expression
1 2 + 34

is the number 46; the value of the expression


" 1 2" + "34"

i s the string "1234". I f you want to add two strings consisting o f digits
according to the numbers they represent, use the VAL function. (See
Section 4.2.5.)

4.2.4 Substring Functions


A substring is a string that is part of another string. Applesoft has three
built-in functions for extracting substrings from a string:
□ LEFT$ extracts a substring from the beginning of a string.
□ MID$ extracts a substring from anywhere in a string.
o RIGHT$ extracts a substring from the end of a string.

4.2.4. 1 The LEFT$ Function


LEFT$ extracts a specified number of characters from the beginning (left
end) of a string. The LEFT$ function takes two arguments, separated by a
comma: the string from which the characters are to be taken and the
number of characters desired. For example,
L E F H ( "TH I S I S I T ! " , 4 ) First 4 characters of the string
"THIS IS IT!"; yields "THIS."
LEFH C HAME S , c + 2 > First C + 2 characters of the
contents of string variable NAME$.
If the value you give for the number of characters in the substring is a real
number, LEFT$ converts it to the next lower integer. If the value specified
is greater than the length of the string, Applesoft returns the entire string;
no extra characters are added.
The number of characters requested must be between 1 and 255 or the
program halts with the message ? I L L E G A L Q U A N T I T Y E R R O R . If you
omit the dollar sign ($) from the function name LEFT$, Applesoft treats
LEFT as an arithmetic variable name, causing an error stop with the
message ? T Y P E M I S M A T C H E R R O R .

4.2 Strings 79
4.2.4.2 The MID$ Function
MID$ (for middle) extracts a specified number of characters fr.om a
specified position within a string. The MID$ function takes three
arguments, separated by commas: the string from which the characters are
to be taken, the position within the string of the first character, and the
number of characters desired. For example,
M I D S C " H O W DO I L OV E T H E E ? " , 1 0 , 4)
4 characters beginning at
position 10 in string "HOW DO I
LOVE THEE?"; yields "LOVE."
M I S C H9s , R + 7 , 2 * v
D > 2 * V characters beginning at
position R + 7 in the contents of
string variable H9$,
You can optionally leave out the third argument to MID$. If you don't
specify the number of characters you want, or if the number of characters
you request is greater than the length of the string, MID$ yields all
characters from the designated starting position to the end of the string:
M I D S ( " T H E R E T H E Y G O ! " , 7 ) All characters from position 7 to end
of string "THERE THEY GO!"; yields
"THEY GO!"
M I os < A s , 1 0 > All characters from position 10 to
end of the contents of string
variable A$.
M I D s < " H I TH E R E " , 4 , 2 0 > All characters from position 4 to end
of string "HI THERE"; yields
"THERE."
If the value you give for the starting position or the number of characters in
the substring is a real number, MID$ truncates it to the next lower integer.
If the designated starting point is greater than the length of the string, or if
the number of characters requested is 0, MID$ yields the null string.
The starting position must be between 1 and 255, and the number of
characters between O and 255, or the program halts with the message
? I L L E G A L . Q U A N T I T Y E R R O R . If you omit the dollar sign ($) from the
function name MID$, Applesoft treats MID as an arithmetic variable name,
causing an error stop with the message ? TY P E M r S M A T C H E R R O R .

80 Chapter 4 : Arrays and Strings


4.2.4.3 The RIGHT$ Function
RIGHT $ extracts a specified number of characters from the end (right end)
of a string. The RIGHT $ function takes two arguments, separated by a
comma: the string from which the characters are to be taken and the
number of characters desired. For example,
Last 7 characters of the string
R I GH T $ ( " G I MM E A B R E A K " , 7 )
"GIMME A BREAK"; yields "A
BREAK."
R I GHH c NAME s , c + 2 > Last C + 2 characters of the
contents of string variable NAME$.
If the value you give for the number of characters in the substring is a real
number, RIGHT $ truncates it to the next lower integer. If the value
specified is greater than the length of the string, Applesoft returns the
entire string; no extra characters are added.
The number of characters requested must be between 1 and 255 or the
program halts with the message ? I L LEGAL QUANT I TY E R R O R . If you
omit the dollar sign ($ ) from the function name RIGHT$, Applesoft treats
RIGHT as an arithmetic variable name, causing an error stop with the
message ? T Y P E M I SMATCH E R R O R.

4.2.5 String Conversion Functions


Strings and numbers are not the same, even when the string looks like a
number:
2 " 1 23 Yields 246.
2 " " 1 23" T Y P E M I SMATCH E R R O R .
LEFT$ ( " 1 23" , 2) Yields "12."
LEFT$ C 1 23 , 2 > T Y P E M I SMATCH E R R O R .
This section describes Applesoft's built-in functions fo r converting between
numeric and string values:
, □ STR$ converts a number to a corresponding string.
□ VAL converts a string to a corresponding number.
□ CHR$ converts an ASCII code to the corresponding character.
□ ASC converts a character to the corresponding ASCII code (see
Section 4.2.1).

4.2 Strings 81
4.2.5.1 The STR$ Function
The STR$ (for string) function converts a numeric value into a string
representing that value. For example,
STR $ C - 1 1HJ ) A string representing the
number -100; yields "-100."
STR $ ( 3 . 1 4 1 59 ) A string representing the
number 3.14159; yields "3.14159."
STR$ (MARK> A string representing the numeric
value of real variable MARK.
STR $ C C O U H T X > A string representing the numeric
value of integer variable COUNT%.
A string representing the numeric
value of the expression
B A 2 - 4•A•C.
The string produced by STR$ is in the same format that Applesoft uses to
display or print numbers; see Appendix I for details. For example,
STR S C 1 BB BBB BBB> Yields "100000000."
STR$ (1 BBB BBB BBB> Yields "1E+09."
STRS C - . 83) Yields "-.03."
STR S C - . IHJ 3 ) Yields "-3E-03."
If the numeric value of the argument falls outside the allowable range for
real numbers (-9.99999999E+37 to +9.99999999E+37), the program halts
with the message ? OV E R F L O W E R R O R.

4.2.5.2 The VAL Function


The VAL (for value) function converts a string to the numeric value it
represents. For example,
VAL ( " 4 896 " ) Number represented by the string
"4096"; yields 4096.
VAL C "- 1 . S BS E •2"> Number represented by the string
"-1.505 E +2"; yields -150.5.
VAL <WHOLE $ + II
+ FRAC S >
II
Number represented by the
concatenation of strings WHOLE$ ,
".", and FRAC$.
VAL C R I GH T S C Q S , 4 ) > Number represented by the last four
characters of string Q$.

82 Chapter 4: Arrays and Strings


VAL recognizes the same number formats as can be used in keyboard input.
(See Section 5.1.2.) If VAL encounters a non-numeric character in its
argument string, it yields the numeric value of everything up to the first
non-numeric character, ignoring the rest of the string. (The digits 0
through 9, the signs + and -, the decimal point (.), and the letter E for
scientific notation are considered numeric characters. Spaces are also
allowed, and are simply ignored.) If the first character in the string is
non-numeric, VAL yields a value of 0. For example,
V A L ( " 1 2 . 5 4 OR S O " ) Yields 12.54.
V A L < "ABOUT 4 . 5 7 " > Yields 0.
If the absolute value of VAL's result is greater than 1E38 or contains more
than 38 digits (including trailing zeros), the program halts with the message
? OV E R F L OW E R R O R .

4.2.5.3 The CHR$ Function


The CI-1R$ (for character) function regards its single numeric argument as
an ASCII character code and yields a one-character string consisting of the
corresponding character.
For example,
CHR $ <68> Character with ASCII code 68;
yields the string "D."
CHR$ c 47> Character with ASCII code 47;
yields the string "/."
c HR $ < 7 > Character with ASCII code 7; yields
a string containing the ASCII bell
character �).
cHR $ c c 1 > Character whose ASCII code is the
value of variable Cl.
c HR $ c L x + 64 > Character whose ASCII code is the
value of expression L% + 64.
If the value of the argument is a real number, CHR$ converts it to the next
lower integer. For example,
CHR $ C 8 1 . 9) Argument is truncated to 81;
yields "Q."
An argument less than 0 or greater than 255 causes the program to halt with
the message ? I L L E G A L Q U A N T I T Y E R R O R .

4.2 Strings 83
4.2.5.4 The ASC Function
The ASC (for ASCII) function takes a single string argument and yields the
ASCII code corresponding to the first character in the string. For example,
A s c c D 11 >
II
ASCII code for character D;
yields 68.
A s c c 11 1 11 > ASCII code for character /;
yields 47.
A S C ( e . e . c u mm i n 9 5 " )
11
ASCII code for character e;
yields 101.
Asc c B0 o ASCII code for the first character in
string BO$.
A S C C M I D S O i AME $ , 5 ) > ASCII code for the fifth character in
string NAME$.
If the argument given to ASC is the null string, the program halts with the
message ? I L L E G A L Q U A H T I TV E R R O R .

84 Chapter 4 : Arrays and Strings


Chapter 5 Input/Output


85
This chapter is concerned with the ways in which Applesoft programs
communicate with the outside world. Here are described Applesoft's
facilities for getting information into and out of the computer and for
controlling the way information is presented.
□ Section 5.1, "Input," deals with the various statements through which
Applesoft programs receive information for processing.
□ Section 5.2, "Output," describes how programs transfer information to
the "outside world": to the display screen, printers, and so forth.

5.1 Input
The input statements discussed in this section enable Applesoft programs to
receive information for processing, either from the keyboard or from a
peripheral device connected to the computer:
□ The IN# statement (see Section 5.1.1) controls the source from which
the computer receives its input.
□ The INPUT statement (see Section 5.1.2) accepts a line of input from the
current input device.
□ The GET statement (see Section 5.1.3) reads a single character from the
current input device.
□ The READ (see Section 5.1.4), DATA (see Section 5.1.4), and RESTORE
(see Section 5.1.5) statements are used to read information from within
the running program itself.
□ A few miscellaneous input facilities (see Section 5.1.6) are available for
reading the hand controls and, in the case of the Apple II, Apple II Plus,
and Appie Ile, for reading information from a cassette tape recorder.

5. 1 . 1 The IN# Statement


I N# 2
I N# X
I N # SLOT - J
The IN# statement specifies the source from which the computer receives
subsequent input. The expression following the keyword IN# should
port or expansion slot: see your Apple's evaluate to a number between O and 7, designating the appropriate port or
owner's manual and reference manual expansion slot from which input is to be taken.

86 Chapter 5: Input/Output
When Applesoft is started up, it is set to receive input from the keyboard.
Executing an IN# statement with a number from 1 to 7 instructs Applesoft
to receive input instead from the peripheral input device (such as a modem)
connected to the designated port or slot. Using number O reestablishes the
keyboard as the current input device. For example, the following program
fragment reads a single character from the device connected to port 2, then
reestablishes keyboard input:
5 1 il l i'i # 2 Accepts input from port 2.
GET statement: see Section 5.1.3 5 2 il GET A$ Reads one character from port 2.
5 3 il I i'i # il Accepts future input from keyboard.
Notice that the character # is part of the keyword IN# and cannot be
omitted.
If You Use DOS or ProDOS: If you have DOS or ProOOS active, any
IN# or PR# (see Section 5.2.1) statement must be set up as a disk
operating system command to prevent the disk operating system from
being disconnected. In that case, the example would look like this:
5 1 il P R l l'i T C H R $ C 4 ) ; " 11'i # 2 "
5 2 il GET AS
5 3 il P R ll'i T C H R $ C 4 ) ; " ll'i # il "

See the manual that came with your disk operating system for more
details .
..&.Warning If the port designated in an IN# or PR# statement contains a disk
controller card, Applesoft attempts to restart the system from the disk
contained in drive 1 connected to that port. When you do this on purpose,
it's the usual way of restarting the system from within Applesoft; when
you do it by mistake, it can be a catastrophe. So be careful!
If no input device is connected to the port designated in an IN#
statement, the system hangs. To recover, use I CONTROL H R ESET 1. Using a
port number between 8 and 255 causes unpredictable and possibly
aberrant behavior.
Using a port number less than O or greater than 255 in an IN# statement
stops the program with an error message.

5 . 1 Input 87
5.1 .2 The INPUT Statement
I N P UT PR I CE
I HPUT M H T H X , DA Y X , Y E A R X
I HPUT "WHAT I S Y O U R P A S SW O R D ? '' ; P A S SW D $
I H P UT "" ; X
The INPUT statement accepts a line of input (which must be terminated by
I RETURN I) from the current input device, specifying values to be assigned to
one or more variables. The variables are listed in the INPUT statement,
separated by commas.
The INPUT statement can optionally include a message to be displayed or
printed on the current output device, prompting the user for the desired
input. If present, the prompting message must be given as a string constant
immediately following the keyword INPUT and followed by a semicolon to
current output device: see Section 5.2.1 separate it from the list of variable names.
The specified prompting string is reproduced exactly as written; if
displayed on the screen, it is immediately followed on the same line by the
cursor. If the prompting message is omitted from the INPUT statement, a
question mark (?) is displayed; the question mark can be suppressed by
supplying a null string as the prompting message. For example,
10 P R I HT "WHAT I S Y O U R A G E , P L E A S E ? "
Displays prompting message on its
own line.
20 I HPUT AGE Prompts with ? and waits for
response.
30 I HPUT "YOUR STREET HAME ? " ; ST$
Displays prompting message on
same line as cursor and waits for
response.
40 P R I HT " P L E A S E T Y P E Y O U R F I R S T A H O L A S T H A ME S , " ;
" S E P A R A T E D BY A C O MMA : I I Displays prompting message on its
own line.
S Iil I H P UT "" ; rn• , LH$ Suppresses ? and waits for two
responses separated by a comma.
The INPUT statement in line 20 above displays a question mark to prompt
the user for input, followed by the cursor. The INPUT statement in line 30
displays the prompting message Y O U R STR E E T H A M E ? instead of the
question mark, again followed by the cursor. The INPUT statement in
line 50 displays the cursor only, with no question mark and no prompting
message of any kind.

88 Chapter 5: Input/Output
The INPUT statement can be executed only from within a program; you
can't use this statement in immediate execution.

5.1 .2.1 Multiple Inputs on the Same Line


The INPUT statement can list any number of variables to be read from the
same input line. The values the user supplies for these variables must be
separated by commas. You can mix string and numeric variables in the
same INPUT statement, but the user's responses must each be of the
correct type.
If the user presses I RETURN I (or types a colon or �) without
typing enough values for all the variables listed in the INPUT statement,
Applesoft displays two question marks to show that it expects further
response. If a colon, comma, or � is the first character of a
response, Applesoft interprets the response as O or as the null string
(depending on the type of variable specified) and the program continues
with the next statement.
If the user types more responses than Applesoft expects, or types a colon
into the final expected response, Applesoft displays the message ? E X T R A
1 G N O R E D and program execution continues. If the last response is
shortened by a �. the program continues but no message is
displayed.
Be Kind to Users: Multiple inputs on the same line can be confusing for
your users; it's best not to use them except for "quick and dirty" testing
purposes while you're debugging your code. Instead of asking for
something terribly unfriendly like
P L E A S E T Y P E L A S T N AME , F I R S T N A M E , M I DDLE I N I T I A L :
use a form such as
PLEASE TYPE YOUR F I RST NAME :
followed by
P L E A S E T Y P E Y O U R M I DD L E I N I T I A L ; J U ST P R E S S R E T U R N
I F YOU HAVE NONE
and so on. You'll be able to give much clearer instructions, your user will
have an easier time giving you what you want, and you'll be better able to
detect and deal with errors in the input.

5.1 Input 89
5.1 .2.2 General Rules for Input
Users of your program should know the following general rules for input:
□ If the user types a colon (:) as part of an input line, the remainder of that
input line is ignored. The ASCII null character � has the
same effect.
□ An INPUT statement can be interrupted by � (see
Section 1 .3.2), but only if it is the first character typed on an input line.
In that case, the program halts when I RETURN I is pressed at the end of
that line. A � that is not the first character of the input line
is treated as part of the input, the same as is any other character.
□ If the user types an input line longer than 255 characters, the whole line
is canceled and has to be retyped from the beginning (the Apple beeps
from about the 245th character, but no message is displayed). A response
of more than 239 but fewer than 255 characters is truncated to
239 characters with no warning message displayed.

5.1 .2.3 Rules for String Input


The following rules govern the values the user types for string variables in
the INPUT statement:
□ The user's response to a string variable can be typed with or without
enclosing quotation marks.
□ Applesoft ignores all spaces preceding the first nonspace character.
□ If the first nonspace character is a quotation mark, the input string is
considered to include everything up to (but not including) the next
quotation mark, �. or I RETUR N 1. The string can include
commas and colons, but cannot include quotation marks, because these
would be interpreted as marking the end of the string. Spaces following
the closing quotation mark are ignored, but any other character causes
the response to be rejected with the message ? R E E H TE R.
□ If the first nonspace character is not a quotation mark, the input string is
considered to include everything up to (but not including) the next
comma, colon, �. or I RETURN 1. The string can include
quotation marks, but cannot include commas or colons, because these
would be interpreted as marking the end of the string. Spaces following
the last nonspace character are accepted as part of the input string.
□ If the first nonspace character is a comma, colon, �. or
I R ETURN I, the response is interpreted as the null string and program
execution continues.

90 Chapter 5: Input/Output
□ In general, control characters cause problems and should not be used in
responding to INPUT statements. The following characters cannot be
included in the response:
� Equivalent to G or the backspace key.
� Equivalent to I RETURN 1.
I CONTROL H]] Cancels the input line.
� ASCII null character; causes remainder of input line to
be ignored.
□ The value supplied for a string variable must be a single string or a
constant; it cannot be a string expression involving concatenation,
LEFT $ , MID$ , RIGHT $ or other string operations. Responses such as
AS + BS
L E F T S C MD N TH S , 3 )
R I GH T S C N A ME S , L - C F L + 2>>
are accepted exactly as typed, character for character (up to the first
comma), and are not evaluated as string expressions.

5.1 .2.4 Rules for Numeric Input


The following rules govern the values a user can supply for numeric
variables. If a response is typed that doesn't conform to these rules,
Applesoft displays the message ? R E E NT E R , reissues the prompting
message, and waits for another response.
□ Spaces are ignored in any position.
□ The response is considered to include all nonspace characters up to (but
not including) the next comma, colon, �. or I RETURN 1.
□ The response can include numeric characters and spaces only. Numeric
characters include the digits O to 9, the signs + and -, the period (decimal
scientific notation: see Section 5.2.3 point), and the letter E for scientific notation. A response containing a
nonnumeric character in any position is invalid.

5.1 Input 91
□ Numeric responses consist of the following elements. Any or all of these
elements can be omitted, except that the sign or value of the exponent
cannot appear unless preceded by the letter E. Even forms such as + E
and .E are accepted, and are interpreted as 0. Those that are included
must be given in the order listed:
1. A sign ( + or -)
2. One or more digits
3. A decimal point (.)
4. One or more digits
5. The letter E for scientific notation
6. A sign (+ or -) for the exponent
7. One or more digits
□ If the first nonspace character is a comma, colon, or I RETURN I, the
response is interpreted as O and program execution continues. A response
beginning with � is invalid.
□ The following control characters have special meanings. A response
containing any other control character, in any position, is invalid.
� Equivalent to E) or the backspace key
� Equivalent to the I RETURN I key
! CONTROL ffK} Cancels the input line
� ASCII null character; causes remainder
of input line to be ignored
□ The value supplied for a numeric variable must be a single number; it
cannot be a numeric expression involving arithmetic operations or
function calls. Responses such as
1 /2
BA2 - 4 * A * C
SQR C 2 )
are invalid because of the non-numeric characters.
Programming Tip: It's a good idea to use string variables to accept all
numeric inputs, using the VAL function (see Section 4.2.5) to convert
them to numeric values. This makes it easier to detect and deal with user
errors and to display alternate prompting messages.

92 Chapter 5: Input/Output
5.1 .2.5 An "Input Anything" Routine (

The INPUT statement interprets the colon and the comma (and sometimes
the quotation mark) as special symbols and rejects anything typed after
them in the input line. Here's what you can use if you anticipate that your
user's response may include any of these characters.
The following Applesoft subroutine uses the POKE statement (see
Section 7.1.2) to store a special machine-language routine in the computer's
memory, one byte at a time, beginning at address 768. The
machine-language routine accepts all characters in the input, including
colons, commas, and quotation marks, without "censoring" them, and
assigns them, character by character, to a string variable for further
processing. (The following line numbers are arbitrary; you can locate this
subroutine anywhere you like in your program.)
6 2 frl frlfrl R E M S E T U P " I N P U T A N YTH I HG" R O UT I N E
6 2 frl 1 frl LET I N $ • "X" IN$ must be first variable created.
6 2 frl 2 frl F O R J = 768 T O 7 9 frl These are memory addresses where
machine language is to be stored.
6 2 frl 3 frl READ I Gets a byte of machine language.
6 2 frl 4 frl POKE J, I Stores it at next location.
6 2 frl 5 frl NEXT J Goes back for next byte.
6 2 frl 6 frl DATA 1 6 2 , frl ' 3 2 , 1 1 7 , 2 5 3 , 1 6 frl , 2 , 1 3 8 , 1 4 5 ,
1 frl 5 , 2 frl frl , 1 69 , frl ' 1 4 5 , 1 frl 5 , 2 frl frl , 1 69 , 2 , 1 4 5 ,
1 frl 5 , 6 , 5 7 , 2 1 3 These are the actual bytes of
machine language.
6 2 frl 7 frl RETURN Returns to statement following
point of call.
The DATA statement (see Section 5.1 .4) containing the machine language
must be reproduced in your program exactly as shown.
The following subroutine uses the CALL statement (see Section 7.1.3) to
call the machine-language routine at address 768. (Again, this subroutine
can be located anywhere in your Applesoft program, not necessarily at line
number 63000.)
63 frlfrl frl R E M C A L L " I N P U T A N Y T H I HG" R O UT I N E
6 3 frl 1 e C A L L 768 Calls machine-langu�ge routine.
6 3 frl 2 frl I H $ • M I D $ < I N $ , 1 > IN$ now holds the input that the
machine-language routine accepted.
63 e 3 e RETURN Returns to statement following
point of call.

5.1 Input 93
To accept a line of input from the user, instead of using a statement such as
1 1Hl I NPUT 5 $

substitute this line:


100 GO S U B 63 0 0 0 : L E T S $ C N > ■ I N$
The variable S$ now contains whatever input the user typed, including the
"forbidden" characters; your program can proceed to process the input in
whatever way is appropriate.
Order of Variables: For technical reasons having to do with the way
variables are stored in memory, the string variable used to pass the user's
response between machine language and Applesoft (arbitrarily called IN$
in the example) must be the first variable used or defined in the program.
To be safe, you might want to call the "input anything" setup routine
from line number 0:
0 G O S U B 62 0 0 0

5. 1 .3 The GET Statement


GET L $
GET S $ C N }
GET C 1 $ , C 2 $ , C3$
The GET statement reads a single character from the current input device,
without waiting for I RETUR N I to be pressed. Although it can be used to read
from any peripheral input device (such as the disk drive or a modem:), it is
seldom used in actual practice with anything other than the keyboard.
GET accepts one character for each of the string variables listed following
the keyword GET. Each single character is read as soon as it is typed,
without waiting for the user to press I R ETURN j. The character is not
displayed on the screen, and the cursor is not moved in any way.

94 Chapter 5: Input/Output
Here's an example of a program fragment using GET:
310 P R I N T " P R E S S T H E ' Y ' K E Y TO GO O H : ";
Prompts user for response
semicolon: see Section 5.2.2 (semicolon keeps cursor on same
line).
32 0 GET A s Waits for user to press key.
330 I F A $ < > "Y" AHO A $ < > "y" THEN 320
Keeps cycling until user presses
correct key.
34 0 P R I HT Moves cursor to new line (cancels
effect of semicolon from line 310).
350 PR I HT "THAHK YOU" Politeness from machines is always
welcome.
The GET statement can be executed only from within a program; you can't
use this statement in immediate execution.
If typed in response to a GET, � is treated like any other
character; it does not interrupt program execution.
Following GET With an Operating System Command: A disk
operating system command issued immediately after a GET is not
recognized. For such commands to be executed properly, you must issue
a I RETURN I character immediately after the GET. An easy way to do this
is with an empty PRINT statement:
P R I NT

See your disk operating system manual for more information.


Numeric Inputs with GET: The GET statement is neither designed nor
intended to obtain values for numeric variables. You can attempt to do so
at your own peril, subject to the following limitations:
□ A comma or a colon results in the message ? E X T R A I G H O R E D and is
interpreted as a numeric value of 0.
□ A plus sign, minus sign, �. E, space, or period is
interpreted as a numeric value of 0.
□ Any non-numeric character causes the program to halt with a syntax
error.
It's better to use only string variables with the GET statement, using the
VAL function (see Section 4.2.5) to convert the response to a numeric
value.

5.1 Input 95
5 . 1 .4 The READ and DATA Statements

READ PR I CE
READ A , B , MX C I > , J X , S $ C 2 * J - 1 ) , T S
DATA 1 2 . 9 , H I H O , 1 68
DATA 2 . 236
The READ and DATA statements are used to read information from within·
the Applesoft program itself, rather than from the keyboard or another
input device. There can be any number of DATA statements in a program,
each containing a list of one or more items of information (numbers or
strings) following the keyword DATA and separated by commas. All of the
DATA statements in the program are considered to form one long list of
items, in sequential order by line numbers; each READ statement reads one
or more items from this list.
Each time it executes a READ statement, Applesoft remembers the last
item read from the DATA list. The next READ always begins with the next
item in the list. There is no way to back up or skip forward in the DATA list,
but you can start over from the beginning of the list with the RESTORE
statement (see Section 5.1.5).
An attempt to read past the end of the DATA list halts the program with a
message such as ? O U T O F D A T A E R R O R I N 1 4 65 identifying the line
number of the READ statement in which the error occurred. Leaving part of
the DATA list unread at the end of the program does not cause an error.
The items in a DATA statement are separated by commas and follow the
usual rules for numeric and string input, except that a DATA statement
cannot contain an unquoted colon (:). The number of items in each DATA
statement is limited only by the length of the program line. A DATA
statement can appear anywhere in your program; it need not precede the
READ statement that uses it. There is no limit to the number of DATA
statements in a program.

96 Chapter 5: Input/Output
Here's a sample program showing the use of the READ and DATA
statements:
10 DATA "GO W E S T , Y O U N G M A N "
Item containing a comma; OK
between quotation marks.
20 DATA 3 . 1 4 1 5 9 , 2 , " S AM" Mixed types in same DATA
statement.
30 READ A $ , B Reads GO WEST, YOUNG MAN into
string variable A$ , and 3.14159 into
real variable B; notice that these
items come from two different
DA TA statements.
40 READ ex , D$ , E $ Reads 2 into integer variable C%,
SAM into string variable D$ , and
THE "WORLD" IS FLAT into string
variable E $ ; begins with next item
following previous READ statement.
SB DATA THE "WORLD" I S FLAT
Item containing quotation marks;
notice that this item follows the
READ statement that uses it.
60 PR I NT E S Displays T H E " W O R L D " I S
F L A T.
70 PR I NT A $ Displays G O W E S T ' Y O U N G MAN.
80 D A T A 98 . 6 , 3 7 , -273 . 1 6 These items never read.
90 END
Null items in a DATA statement are interpreted as O or the null string,
depending on the type of variable to which they are assigned in a READ
statement. A null item is read whenever there are no nonspace characters
between
□ the keyword DATA and the end of the program line
□ the keyword DATA and the first comma
□ two consecutive commas
□ the last comma and the end of the program line.
Thus the statement
D A TA , ,

contains three null items.

5.1 Input 97
An attempt to read a string value in a DATA statement with a numeric
variable in a READ statement causes a syntax error. Numeric values can be
read into string variables, but must be evaluated with the VAL function (see
Section 4.2.5) before they can be used as numbers.
Control Characters in DA TA Statements: The characters
I CONTROL H:B], �. I CONTROL f-lK], and �
cannot be embedded in a DATA statement. Any other control character
typed into a DATA statement is treated as an ordinary character and
becomes part of the input. A � character in a DATA
statement does not interrupt the program.
The READ statement can be executed only from within a program; you
can't use this statement in immediate execution.

5. 1 .5 The RESTOR E Statement


R E ST O R E
The RESTORE statement restarts the DATA list from the beginning. After
RESTORE is executed, the next READ statement reads the first item in the
first DATA statement in the program. For example,
10 DATA "GO W E S T , Y O U N G M A N "
20 D A T A 3 . 1 4 1 5 9 , 2 , " S A M"
30 READ A $ , 8 Reads GO WEST, YOUNG MAN into
string variable A$ and 3.14159 into
real variable B.
40 READ ex , DS , E $ Reads 2 into integer variable C%,
SAM into string variable D$ , and
THE "WORLD" IS FLAT into string
variable E$ .
50 DATA THE "WORLD" I S FLAT
60 P R iti T E $ Displays T H E " W O R L D " I s
FLAT.
70 RESTORE Restarts list from beginning.
80 READ Q$ Reads GO WEST, YOUNG MAN into
string variable Q$.
90 P R iti T Q $ Displays GO W E S T ' Y O U N G MAN.
100 P R I NT A S Displays G O W E S T ' Y O U N G MAN
(value of A$ still intact).
110 E ND
120 D A T A 98 . 6 , 37 , - 2 73 . 1 6 These items never read.

98 Chapter 5: Input/Output
There is no way to reposition the DATA list to a specific desired item or line
number. The only other Applesoft statement that affects the positioning of
the DATA list is RUN (see Section 1.2.4), which also restarts the list from
the beginning.

5. 1 .6 Miscellaneous Input Facilities

This section covers Applesoft's facilities for dealing with the remaining
input features of the Apple II: the hand controls and cassette tape input.
Refer also to Appendix 0.

5.1 .6.1 The Hand Controls


If you have a set of hand controls connected to your computer, you can use
the PDL function to read their dial settings. The Apple II series of computers
can accommodate as many as four hand controls, numbered O to 3,
connected either through the 9-pin hand control connector on the
computer's back panel or, in those models where accessible, the GAME I/O
connector inside the case on the main logic board. However, the standard
Apple hand control set consists of only two controls, numbered O and 1.
The PDL function takes one argument, the number of the hand control to be
read, and yields an integer from O to 255 representing the current position of
the dial on that control. For example,
10 L E T X = P O L C fr D Reads hand control 0.
20 LET PX • X • 4 0 / 256 + 1
Reduces to a number from 1 to 40.
30 HTAB C P X > Moves cursor to indicated position
on current line.
40 PR I NT " < " Displays the character < .
S il L E T Y • POL ( 1 ) Reads hand control 1.
60 LET QX = Y • 40 / 256 + 1
Reduces to a number from 1 to 40.
7"' HTAB C Q X ) Moves cursor to indicated position
on current line.
80 PR I NT " > " Displays the character > .
90 I F X • l'l A H D y - "' THEH END
Ends program when both hand
controls read 0.
100 GOTO 1 0 Otherwise repeats the process.

5.1 Input 99
If the argument given to PDL is less than O or greater than 255, the program
halts with the message ? I L L E G A L Q U A HT I T Y E R R O R . If the argument is
between 4 and 255, or if no hand control of the designated number is
connected, the results are unpredictable.
Consecutive Readings: If your program reads two hand controls in
consecutive statements, the reading from the first hand control may
affect the reading from the second. To obtain more accurate readings,
allow several program lines between calls to PDL or use a short delay loop
such as
FOR X • 1 TD 10 : HEXT X

between PDL calls.


Historical Note: The function name PDL stands for paddle, which in
tum is short for game paddle, an older name for the Apple II's hand
controls.
The buttons on the hand controls can be read with the function calls
PEEK function: see Section 7.1.1 P E E K C - 1 6 287 ) Yields a value > 127 if button on
hand control O is being pres�ed;
< = 127 if not.
P E E K C - 1 6 286 ) Yields a value > 127 if button on
hand control I is being pressed;
< = 127 if not.
P E E K C - 1 6 285 ) Yields a value > 127 if button on
hand control 2 is being pressed;
< = 127 if not.
There is no way to read the button on hand control 3.
The PEEK calls listed are also used to read the apple keys on some models
of the Apple II keyboard: @] is equivalent to the button on hand control 0,
and [!) is equivalent to the button on hand control 1.
For More Information: See your Apple computer's reference manual
for detailed technical information on the 9-pin hand control connector
and/or the internal GAME I/0 connector.

5.1 .6.2 Cassette Input


Three Applesoft statements, LOAD, RECALL, and SHLOAD, can be used to
read information from a cassette tape recorder (Apple II, Apple II Plus, and
Apple fie only). LOAD reads an Applesoft program into memory from tape;
RECALL reads the contents of an integer or real array; SHLOAD reads a
shape table for use in high-resolution graphics. For details, see Appendix M.

100 Chapter 5: Input/Output


5.2 Output

This section describes the output facilities available in Applesoft:


□ Section 5.2.1 covers the PR# statement, which controls the destination to
which output is directed.
□ Section 5.2.2 contains a detailed discussion of the PRINT statement,
Applesoft's primary output statement.
□ Section 5.2.3 gives details on the way numbers are formatted when
written with the PRINT statement.
□ Section 5.2.4 describes Applesoft's wide variety of facilities for
controlling the format in which textual information is displayed on the
screen.
□ Section 5.2.5 touches briefly on various miscellaneous output facilities
not covered elsewhere: the Apple H's built-in speaker, annunciator
outputs, utility strobe, and cassette tape output.

5.2. 1 The PR# Statement

PR# 1
PR# X
PR# SLOT - J
The PR# statement specifies the destination to which the computer sends
subsequent output. The expression following the keyword PR# should
evaluate to a number between O and 7, designating the port to which output
is to be sent.
When Applesoft is started up, it is set to send output to the display screen.
Executing a PR# statement with a port number from 1 to 7 instructs
Applesoft to send output instead to the peripheral output device (such as a
prin�r or modem) connected to the designated port. A port number of 0
reestablishes the display screen as the current output device. For example,
the following program fragment writes a string of characters to the device
connected to port 1, then reestablishes screen output:
s 1 fil P R , 1 Sends output to device in port 1.
6 2 fil P R I M T z s Writes contents of string variable Z$
to device in port 1.
63 fil P R , fil Sends future output to screen.
Notice that the character # is part of the keyword PR# and cannot be
omitted.

5.2 Output 101


If You Use DOS or ProDOS: If you have DOS or ProDOS active, any
IN# or PR# statement must be set up as a disk operating system
command to prevent the disk operating system from being disconnected.
The example would look like this:
610 P R I HT C H R $ C 4 ) ; " P R # 1 "
620 P R I HT 2 $
630 P R I HT C H R $ C 4 ) ; " P R # 0 "
See the manual that came with your disk operating system for more
details.
A.Warning If the port designated in an IN# (see Section 5.1.1) or PR# statement
contains a disk controller card, Applesoft attempts to restart the system
from the disk contained in drive 1 connected to that port. When you do
this on purpose, it's the usual way of restarting the system from within
Applesoft; when you do it by mi�take, it can be a catastrophe. So be
careful!
If no output device is connected to the port designated in a PR#
statement, the system hangs. To recover, use I CONTROL H RESET 1.
Using a port number between 8 and 255 in a PR# statement causes
unpredictable and possibly aberrant behavior.
If you are using an Apple Ile with the Apple II 80-Column Text Card, or
an Apple Ile (which contains the equivalent of that card) deactivate it by
typing I ESC I � before using PR# to transfer output to
another port. Leaving the Text Card active while using a printer or while
restarting the system from a disk can produce amusing but confusing
fireworks on the screen.
Although the Text Card is installed in the Apple's special auxiliary slot, it
appears to the computer as if it were connected to port 3. So to reactivate
the Text Card after sending output to another device, type
PR# 3
You can also return output to the 40-colurnn screen with the Text Card
inactive by typing
PR# 0
However, don't use PR# 0 to redirect output directly from the Text Card
to the 40-column screen without first deactivating the Text Card with
I ESC I �- Under certain circumstances, this may cause text
intended for the screen to be written outside the area of memory reserved
for it, possibly destroying your Applesoft program or other important
information.

102 Chapter 5: Input/Output


Using a port number less than O or greater than 255 in a PR# statement
stops the program with the message ? I L L E G A L Q U A N T I TV E R R O R .

5.2.2 The PRINT Statement


PR I NT
P R I NT PS , Q , RX
PR I NT "D I S C R I M I N A N T • " ; B A 2 - 4 * A * C
P R I NT LEFT$ < FN $ , 1 ) + " . " + L N $
P R I NT TAB C M ) ; " * " ; T A B C M + N ) ; " * * * " ;
TAB C M + N + N ) ; " * "
The PRINT statement writes output to the current output device.
Expressions representing the values to be written are listed after the
keyword PRINT, separated by commas or semicolons.
Any expression can be included in a PRINT statement. Each expression in
the list following the keyword PRINT is evaluated. If the value of the
expression is a string, the characters of the string are written to the current
output device (see Section 5.2.1 ); if the value is a number, it is written
according to the rules discussed in Section 5.2.3, "Number Formats." Calls
to the special functions SPC and TAB (see Section 5.2.4) can also be
included in a PRINT list; they do not cause anything to be written, but
control the positioning of the next item.
When an item in the PRINT list is followed by a semicolon, the cursor (if
output is going to the screen) or print head (if to a printer) is left positioned
immediately after the last character in the item. The next item written
begins in the next available column, with no intervening spaces. A
semicolon at the end of a PRINT statement causes the cursor or print head
to be left at the end of that line, and prevents a new line from being started.
For example, the statement
P R I NT 1 ; 2; 3; 4;
produces the output
1 234
and leaves the cursor or print head positioned in the column immediately
following the digit 4. The statement
P R I NT 1 / 3 ; 2 • 4 ; 5 1
produces the output
. 33333333385 1

5.2 Output 103


If two consecutive items in a PRINT list are not separated by either a
comma or a semicolon, a semicolon is understood.
Eliminating Blank Lines: The Apple II's normal display is 40 columns
wide. After Applesoft displays the 40th character on a line, it
automatically sends the cursor to the beginning of the next line. The next
PRINT statement executed starts another new line, causing an
unintended blank line to appear on the screen. (Unwanted blank lines are
especially annoying in inverse mode.)
For example, the statements
10 P R I N T "T H I S M E S S A GE H A S P R E C I S E L Y 4 0
CHARACTERS"
20 P R I NT " S O T H E R E ' S A B L A N K L I N E O N T H E
SCREEN"
display the output
TH I S M E S S A G E H A S P R E C I S E L Y 4 0 C H A R A C T E R S

S O T H E R E ' S A B L A N K L I N E O N THE S C R E E N
To eliminate the blank line, add a semicolon to the end of line 10:
10 P R I NT "TH I S M E S S A G E H A S P R E C I S E L Y 4 0
C H A R A CTE R S " ;
Now you get this:
TH I S M E S S AGE H A S P R E C I S E L Y 4 0 C H A R A CT E R S
S O T H E R E ' S A BL A N K L I N E O N T H E S C R E E N
The second line of this message i s now a lie.
A statement such as
PR I NT A $ + 8$
causes a halt with the message ? S TR I N G T O O L O N G E R R O R if the
combined length of the concatenated strings is greater than 255 characters.
However, you can print the apparent concatenation regardless of length by
using a semicolon:
PR I NT A $ ; 8$
When an item in the PRINT list i s followed by a comma, the cursor or print
head is advanced to the next available tab position: column 17 or 33 of the
current line or column 1 of the next line. The next item written begins at
the tab position. A series of consecutive commas advances the cursor or
print head a corresponding number of tab positions. A comma at the end of

104 Chapter 5: Input/Output


a PRINT statement causes the cursor or print head to be left at the next
available tab position, and may prevent a new line from being started. For
example, the statement
P R I NT 1 , 2 , 3 , 4 ,
produces the output
2 3
4
and leaves the cursor or print head positioned in column 17 of the second
line, directly under the digit 2. The statement
P R I NT 1 / 3 , 2 * 4 , 5 1
produces the output
. 333333333 8 51
Comma Cautions: If any character appears in columns 24 to 32, or in
the case of models II, II Plus, and Ile, if you have the Apple II 80-Column
Text Card installed in your computer and running in "active 80" mode,
then column 33 is not available as a tab position; a comma after
column 17 causes the next item to start at column 1 of the next line.
text window: see Section 5.2.4, If the text window is set to fewer than 33 columns wide, commas in a
Section F.l, and your Apple's reference PRINT statement do not function properly and may cause text to be
manual displayed outside the text window.
A PRINT statement that doesn't end with a comma or semicolon always
starts a new line after writing its last item and leaves the cursor or print
head positioned in column 1 of the new line. The statement
P R I NT
simply starts a new line. If the cursor or print head was already at the
beginning of a line, this statement causes a blank line to be displayed or
printed.
Here's a sample program using some of the features of PRINT:
1l'J L E T A • 5 . 35 : L E T C $ • " F R ED" : L E T GX • 1 6
Sets up series of variables.
20 P R I NT " S T U F F A N D N O N S E N S E "
Displays message and starts new
line.
30 P R I NT Displays a blank line.
40 P R I NT " A • " ; Displays message without starting a
new line.

5.2 Output 105


S il P R I HT A Displays 5.35 on same line as
message from program line 40;
starts new line.
6 11 P R I HT " G X • " ; GX Displays message and value 16 on
same line; starts new line.
711 P R I HT " C $ • " , C S Displays message, advances to next
tab position, and displays string
FRED; starts new line.
S il P R I HT A • G X Displays value of expression
A * G% (85.6) and starts new line.
When executed, this program produces the following output:
STUFF AHO HDHSEHSE

A • 5 . 35
GX • 1 6
Ct • FRED
85 . 6
Abbreviation for PRINT: You can use a question mark (?) as an
abbreviation for the keyword PRINT; if you use it, it appears as P R I HT in
a program listing. If you type
1 ll ll ? A$
L I ST

Applesoft displays
1 11 11 PR I HT A $

5.2.3 Number Formats

This section describes the formats in which Applesoft displays or prints


numeric values. Numbers are not always formatted in the way you might
expect; this is particularly true for numbers more than nine digits long or for
exceptionally small numbers.
Numeric values in Applesoft must be in the range -1 *10 38 to 1 *10 38. Any
A A

number whose absolute value is less than approximately 3*10 -39 is


A

converted to 0. True integer values to be assigned to integer variables (such


as A%) must be in the ran:ge -32767 to +32767.

106 Chapter 5: Input/Output


A number typed from the keyboard or a numeric constant used in an
Applesoft program can have as many as 38 digits. However, only nine digits
are significant, and the last digit is rounded off. An Applesoft statement that
you type as
P R I NT 1 . 2345678765 4 3 2 1

displays
1 . 2 3 4 5 6 7 88

on the screen.
Integers are always converted to real form before being used in arithmetic
calculations, and the results are converted back to integer form when
assigned to an integer variable. Conversion from real to integer form is by
truncation to the next lower integer, not by rounding to the nearer integer.
Applesoft displays and prints numbers according to the following rules:
□ If the number is negative, it is preceded by a minus sign (-); if it is O or
positive, no sign is used.
□ If the number is an integer with an absolute value from O to 999999999, it
is formatted as an integer.
□ If the number is not an integer and its absolute value is between .01 and
999999999.2, it is formatted with a decimal point in the usual way.
□ In all other cases, the number is formatted in scientific notation. (See
Table 5-1.)
Table 5-1 shows examples of the formats used for displaying and printing
numbers.

Table 5-1. Number Formats

Number Output Format


+1 1
-1 -1
6523 6523
-23.460 A -23.46
45,72 ·A 10 5 4572000
1 . 10 20 1E+20
-12.34567896 • 10 10 -1.2345679E+ 11
1000000000 1E+09
999999999 999999999

scientific notation: the representation of The format Applesoft uses for scientific notation is shown in Figure 5-1.
numbers in terms of powers of 10

5.2 Output 107


Figure 5-1. Format for Scientific Notation
sign exponent symbol

I
SX .
I
X X X X X X X X ESDD

V each x is a digit

sign of exponent
digits of exponent

A sign is shown only if the number is negative. There is always exactly one
nonzero digit before the decimal point and up to eight digits after it, with
trailing zeros suppressed. There are never any leading zeros; the digit before
the decimal point is always nonzero. If there is only one digit to print after
all trailing zeroes are suppressed, no decimal point is shown. The letter E
(for exponent) is always followed by a sign and a two-digit exponent. The
value of a number represented in this form is the number before the E
times 10 raised to the power after the E. For example,
P R r MT 35 * 345 14 A Yields l.18450085E+37.
P R I M T - 3 . 1 4 1 5 9 * 567 5 Yields -1.84104669E+ 14.
A

PR r M T 1 1 999 Yields 1.00lOOlE-03.


P R I M T - 3 1 999 Yields -3.003003E-03.

5.2.4 Formatting T�xt on the Screen


This section deals with Applesoft's facilities for controlling the way text is
formatted and presented on the display screen. For further information on
text formatting, see Section 5.2.2.
□ The TEXT and HOME statements are used to clear text and graphics
from the screen.
□ SPC, TAB, HTAB, VTAB, and POS control the position of the cursor,
which determines where characters are displayed on the screen.
□ NORMAL, INVERSE, and FLASH control the form in which text
characters are presented on the screen.
□ The SPEED= command sets the rate at which characters are displayed.

108 Chapter 5: Input/Output


-
5.2.4.1 The Text Window
The area within which text is displayed and scrolled on the screen is known
as the text window. Normally, the text window is the full screen.
Section F.l describes how you can create one or more text windows that
occupy only part of the screen. See your Apple's reference manual for a
more technical discussion.

5.2.4.2 The TEXT Statement


TEXT
The TEXT statement instructs Applesoft to begin displaying text on the
screen; it is customarily used to switch from graphics to text display. The
text window is set to the full screen (24 lines, 40 or 80 characters per line
depending on your model and switch settings). The Applesoft prompting
character ( 1 ) is displayed in the bottom-left corner of the screen, followed
by the cursor.
If the display is already in text mode, the TEXT statement is equivalent to
the statement VTAB 24.

5.2.4.3 The HOME Statement


HOME
HOME clears the currently defined text window and sends the cursor to the
top-left corner of the window. If the text window is set to the full screen,
the cursor is sent to the beginning of line 1. If the computer is displaying
mixed text and graphics (four lines of text at the bottom of the screen),
HOME clears the four text lines and sends the cursor to the beginning of
line 21.
Helpful Hint: To move the cursor to the top-left corner of the screen
without clearing any text, use
VTAB and HTAB statements: see VTAB 1 : H T A B 1
Sections 5.2.4.7 and 5.2.4.6
5.2.4.4 The SPC Function
The SPC (for space) function is used in PRINT statements (see
Section 5.2.2) to write a specified number of spaces to the current output
device. The numeric argument given to the function specifies the number of
spaces to be written. If this value is a real number, Applesoft truncates it to
the next lower integer.

5.2 Output 109


The SPC function can be called only from within a PRINT statement. SPC
differs from TAB (see Section 5.2.4.5) in that it advances the cursor (or
print head, if the current output device is a printer) a specified number of
columns from its current position, rather than to a specific horizontal
position from the beginning of the current line. If the cursor is spaced past
the right edge of the screen or text window, it returns to the beginning of
the next line and continues spacing. For example, assuming the text
window is set to the full screen and the cursor is initially at the left edge,
the statements
1 il PR I NT SPC C S ) ; "HELLO"
20 P R I NT "TH E S E " ; S P C C 1 il ) ; " A R E " ; S P C
C 4 ) ; " I NTE R E ST I NG" ; S P C ( 1 2 ) ;
"T I MES"
display the following on the screen:
HELLO
THESE ARE I NT E R E ST I NG
T I MES
Notice how the output of line 20 wraps around when it reaches the edge of
the screen (column 40).
If SPC is the last item in a PRINT statement, Applesoft acts as if the
statement ended with a semicolon. The cursor is left positioned the
specified number of spaces after the end of the previous item; no new line is
started. The next item displayed begins immediately following the last
space.
The argument given to SPC must be in the range 0 to 255 or the program
halts with the message ? I L LEGAL Q U A N T I TY E R R O R . However, several
calls to SPC can be strung together in the form
PR I NT SPC ( 25 5 ) ; SPC ( 2 55) ; SPC ( 2 55)
to provide arbitrarily large numbers of spaces.
Semicolons Optional: Semicolons are optional between SPC items:
P R I NT " L ET" ; S P C ( 1 0 ) " A L L " S P C ( 1 5 ) ;
"REJO I CE"

l lO Chapter 5 : Input/Output
5.2.4.5 The TAB Function
The TAB function is used in PRINT statements (see Section 5.2.2) to
advance the cursor to a specified horizontal position measured from the
beginning of the current output line. The numeric argument given to the
function specifies the position to which the cursor is to be moved. If this
value is a real number, Applesoft truncates it to the next lower integer.
The TAB function can be called only from within a PRINT statement. TAB
differs from SPC (see Section 5.2.4.2) in that it advances the cursor (or print
head, if the current output device is a printer) to a specific horizontal
position from the beginning of the current line, rather than a specified
number of columns from the current cursor position. If the cursor is
advanced past the right edge of the screen or text window, it returns to the
beginning of the next line and continues advancing. For example, assuming
the text window is set to the full screen and the cursor is initially at the left
edge, the statements
1 1!l PR I NT TAB ( 1 5 ) ; "THE F L E ET ' S I N ! "
2 1!l P R I N T T A B C 1 1!l ) ; " H E L L O " ; T A B C 3 1!l ) ;
"TH E R E , " ; TAB ( 4 5 ) ; " S A I L OR ! "

display the following on the screen:


THE FLEET ' S I N !
HELLO THERE ,
SA I LOR !

Notice how the output of line 20 wraps around when it reaches the edge of
the screen (column 40).
TAB Moves Forward Only: Unlike the HTAB statement, which moves
the cursor to an absolute horizontal position from the left edge of the
screen or the text window, TAB moves the cursor in a forward direction
only. If the specified tab position is less than the current cursor position,
TAB has no effect; it never moves the cursor to the left on the current
line (use HT AB for this purpose).
If TAB is the last item in a PRINT statement, Applesoft acts as if the
statement ended with a semicolon. The cursor is left at the specified tab
position; no new line is started. The next item displayed begins at the tab
position.
The argument given to TAB must be in the range 0 to 255 or the program
halts with the message ? I L L E G A L Q U A N T I TY E R R O R . An argument
value of 0 moves the cursor to 256 positions from the beginning of the
current line.

5.2 Output 111


Semicolons Optional: Semicolons are optional between TAB items:
P R I NT "DOW N " ; TAB C 1 4 > " Y O U " T A B C 27 > ;
"GO"

5.4.2.6 The HTAB Statement


HTAB 1 1!
HTAB N
HTAB 4 1 - L E N C S $ )
HTAB (for horizontal tab) moves the cursor to a specified horizontal
position from the beginning of the current output line. The expression
following the keyword HTAB specifies the position to which the cursor is to
be moved. If this value is a real number, Applesoft truncates it to the next
lower integer.
Unlike the TAB function, which moves the cursor in a forward direction
only, the HTAB statement can move the cursor in either direction to a
specified horizontal position. For example, in 40-column mode, the program
5 HOME
1 " HTAB 6 : P R I NT " I S TH E " ;
1 5 F O R Z • 1 TO S il l! : N E X T Z
2 1! HTAB 1 : P R I NT "TH I S " ;
2 5 F O R Z • 1 TO s e e : N E X T Z
3 1! HTAB 1 3 : P R I N T " P R O P E R O R D E R "
displays the following on the screen:
TH I S I S T H E P R O P E R O R D E R
If you want to use HTAB to display several text items on the same line, you
need a semicolon at the end of each PRINT statement to avoid starting a
new line.
If there is a text window set, the specified tab position is interpreted relative
to the left edge of the window. However, HTAB. behaves as though there
were 40 columns in each line of the window, regardless of the actual width
to which the window has been set; that is, position 1 is considered to be the
leftmost column of the current line, position 41 the leftmost column of the
next line, position 81 the leftmost column of the line after that, and so on. If
the cursor is advanced past the right edge of the screen or text window, it
returns to the beginning of the next line and continues advancing.
HTAB can carry the cursor outside the boundaries of the text window, but
only long enough to display one character; the cursor then returns to the left
edge of the window.

1 12 Chapter 5: Input/Output
80-Column Text Card Users: If your computer is an Apple II, an
Apple II Plus, or an early Apple Ile, HTAB is designed to operate with a
40-column screen only. If you attempt to advance the cursor beyond
column 40, it wraps around to the next line, even if you have the Apple II
80-Column Text Card installed and running in "active 80" mode. To tab to
a position between columns 41 and 80, use
POKE statement: see Section 7.1.2 POKE 1 4 03 , XX
where XX is the number of the column to which you want to tab. See
Section F.1 and the BO-Column Text Card Manual for more
information.
The column number specified to HTAB must be in the range 0 to 255 or the
program halts with the message ? I L L E G A L Q U A H T I TY E R R O R . A value
of 0 moves the cursor to 256 positions from the beginning of the current line.
A Programming Tip: Many programmers find HTAB to be more
convenient to use than TAB, because it is an independent statement and
need not be embedded in a PRINT statement. This makes it easier to
change, if necessary, during program development.

5.2.4. 7 The VTAB Statement


VTAB 1 0
VT A B H
VTAB 2 5 - H %
VTAB (for vertical tab) moves the cursor vertically to a specified line on the
screen. The expression following the keyword VTAB specifies the line to
which the cursor is to be moved. If the value of this expression is a real
number, Applesoft truncates it to the next lower integer.
The top line of the screen is line 1; the bottom line is line 24. VTAB can
move the cursor either up or down on the screen, but never to the left or
right; it remains at the same horizontal position as before the move. This
sample program uses VTAB:
10 HOME Clears text from screen.
2 0 VTAB 6 Moves cursor to line 6.
3 0 P R I H T " L I H E 6" Displays imaginative message.
40 F O R Z • 1 T O 500 : HEXT z
Delays loop so user can see the
order and position of text display.
50 VTAB 1 8 Moves cursor to line 18.

5.2 Output 113


S il P R H I T " L I N E 1 0 11 Displays another imaginative
message.
7 il FOR 2 • 1 TO S il il : H E X T 2
Another delay loop.
S il VTAB 1 2 Moves cursor to line 12.
S il P R I HT " T H E M I DDL E " Displays last message.
VTAB ignores the setting of the text window, if any. The specified line
number is always taken to relate to the entire screen.
The line number specified to VTAB must be in the range 1 to 24 or the
program halts with the message ? I L L E G A L Q U A H T I T Y E R R O R . If VTAB
moves the cursor to a line below the bottom of the text window, all
subsequent text is displayed on that same line.

5.2.4.8 The POS Function


The POS (for position) function yields the current horizontal position of the
cursor, relative to the left edge of the text window. The value yielded is in
the range O to 39. A value of O represents the left edge of the window.
POS must be followed by an argument in parentheses. What you use for an
argument expression doesn't matter, but if Applesoft can't evaluate it as a
legal expression, you get an error halt. The argument given to POS is
ignored, and has no effect on the operation of the function. However, you
can't leave it out-you must include an argument expression of some kind
to "keep the parentheses apart."
A Difference of Opinion: Notice that POS numbers columns beginning
with 0, whereas TAB and HTAB number them beginning with 1. Thus,
assuming the cursor is at the beginning of a line, the statement
P R I NT TAB 1 il ; P O S C il )
prints the value s, and
HTAB 4 3 : PR I HT POS C X )
prints 2 (since HTAB 43 tabs to the third column of the next display line).
Notice in the second case that the value of variable X makes no
difference.

1 14 Chapter 5: Input/Output
5.2.4.9 The INVERSE Statement
I NVERSE
The INVERSE statement causes subsequent text output to be displayed in
black-on-white instead of the usual white-on-black (where white means the
phosphor color of your display, whatever that is). The normal
white-on-black display can be restored with the NORMAL statement. (See
Section 5.2.4.11.) For example,
10 I HVE R S E Sets inverse display.
2 0 PR I NT "BLACK - O H -WH I TE " Displays BLAC K - O H - WH I TE in
black-on-white.
3 0 NORMAL Restores normal display.
4 0 P R I NT "WH I TE - O M -BLACK" Displays wH I TE - O M -BLACK in
white-on-black.
INVERSE affects only subsequent output characters sent to the screen with
PRINT statements. It has no effect on characters already on the screen or
on keyboard input "echoed" to the screen. Note: lowercase letters can be
displayed in inverse video only when the 80-column card is active.
Don't overdo it: INVERSE is most effective when you use it sparingly.

5.2.4. 1 0 The FLASH Statement


FLASH
The FLASH statement causes subsequent text output to alternate
approximately twice a second between black-on-white and the usual
white-on-black (where white means the phosphor color of your display,
whatever that is). The normal white-on-black display can be restored with
the NORMAL statement. (See Section 5.2.4.1 1) For example,
1 0 FLASH Sets flashing display.
2 0 PR I H T "FLASHY" Displays flashy F L A S H Y.
30 N O R M A L Restores normal display.
4 0 PR I M T "DRAB" Displays drab D R A B.
FLASH affects only subsequent output characters sent to the screen with
PRINT statements. It has no effect on characters already on the screen or
on keyboard input "echoed" to the screen.

5.2 Output 1 15
When FLASH Flops: FLASH doesn't work on characters with ASCII
codes (see Section 4.2.1 and Appendix C) above 95, the most important of
which are the lowercase letters ; instead of making them flash, it turns
them into gibberish.
FLASH doesn't work at all if you have an Apple Ile, or an Apple Ile with
the Apple II SO-Column Text Card installed and running in "active 80"
mode.
FLASH is most effective when used very sparingly. Reserve it for only the
most important messages or unusual uses. Cavalier use of FLASH has been
known to drive users to delirium.

5.2.4. 1 1 The NORMAL Statement


t-l O R M A L
The NORMAL statement causes subsequent text output to be displayed in
the usual white-on-black (where white means the phosphor color of your
display, whatever that is). It is usually used to cancel the effects of the
INVERSE or FLASH statement. For example,
10 I t-l V E R S E Sets inverse display.
20 P R il'-IT "EL A C K - □ t-1 - WH I TE " Displays B L A C K - 0 1'-1 - W H I T E in
black-on-white.
30 t-l O R M A L Restores normal display.
40 P R I t-I T "WH I T E - O t-1 - B L A C K " Displays W H I T E - Q t-I - B L A C K in
white-on-black.
S B FLASH Sets flashing display.
6 0 P R I t-IT " F L A S H Y " Displays flashy F L A S H Y .
7 0 t-l O RM A L Restores normal display.
8 0 P R I t-l T "DRAB" Displays drab DRAB.
NORMAL affects only subsequent output characters sent to the screen with
PRINT statements. It has no effect on characters already on the screen.

1 16 Chapter 5: Input/Output
5.2.4. 1 2 The SPEED = Statement
SPEED• 255
SPEED• X
SPEED• Z - 6 * F
The SPEED= statement sets the rate at which output characters are sent to
the display screen or other output device (such as a printer). The slowest
rate is O; the fastest is 255. The normal speed setting (if you don't do
anything to change it) is 255. For example,
1 1! SPEED• 0 Sets slowest possible speed.
20 P R I HT "THE TORTO I S E " Displays T H E TORTO I S E slowly.
30 SPEED• 2 5 5 Restores normal speed.
40 P R I HT "THE H A R E " Displays THE H A R E quickly.
SPEED Is Not a Variable: Notice that the equal sign is part of the
keyword SPEED=; it doesn't represent an assignment to a variable
named SPEED. A statement such as
LET SPEED • X
causes a syntax error. The only way to find out the current speed setting
is to keep track of it yourself with a variable, as in the following example:
11! LET X • 250 Sets initial value for speed.
20 SPEED• X Sets speed to value of X.
30 P R I HT " C U R R E NT S P E E D I S " ; X
Displays current speed.
40 L E T X • X - 25 Decreases value of X by 25.
50 I F X > • 0 THEH GOTO 20 Repeats until X becomes negative.
60 SPEED• 255 : EHD X is too low; ends the program.
The speed setting is not reset to its normal value by RUN, CLEAR, or
I CONTROL H RESET 1.
The speed setting specified to SPEED= must be in the range O to 255 or the
program halts with the message ? I LLEGAL QUA HT I TV ERROR.
SPEED= has no effect on graphics.

5.2 Output 117


5.2.5 Miscellaneous Output Facilities

This section covers Applesoft's facilities for dealing with the remaining
output features of the Apple II: the built-in speaker, annunciator outputs,
utility strobe, and cassette tape output. Most of these features are controlled
by means of PEEK and POKE (see Sections 7.1.1 and 7.1.2); details can be
found in Appendix F. The annunciators and utility strobe are seldom used,
and are mentioned here just for the sake of completeness.

5.2.5. 1 Controlling the Speaker


for technical information on the built-in The Apple II has a small, built-in speaker that you can use to add sound to
speaker: see your Apple's reference your programs. The easiest way to use it is by sending the ASCII bell
manual character �. ASCII code 7) to the display screen. This causes
the computer to emit a short beep.
Historical Note: ASCII code 7 was originally used to ring a small bell on
teletype machines, to let the teletype operator know that a message was
coming in. On the Apple II it sends a !-kilohertz tone (1000 cycles per
second) to the Apple II's speaker for 1/10 second.
Here's a program to ring the computer's "bell" a number of times specified
by the user:
10 P R I NT " E N T E R A H U M B E R F R OM 1 T O 9 C S T O STOP ) : I I •
Prompts user for input.
20 GET A $ Accepts single character from
keyboard.
30 I F A $ • 11 5 11 T H E N E N D Stops if user typed s .
40 I F V A L C A O < 1 T H E N 2 0 If character typed i s out of range
then tries again.
50 FOR X • 1 T O VAL C A $ ) Loop requested number of times.
60 P R I NT C H R $ ( 7 ) Sounds "bell."
70 NEXT X Loops back to 50.
80 P R I NT Leaves a blank line.
90 GOTO 1 0 Starts again.
The only other way for Applesoft programs to produce sound from the
speaker is with a PEEK or POKE to address -16336. This causes the speaker
to emit a single click. By combining such clicks in the appropriate patterns
and frequencies, you can produce musical tones and a variety of other
sounds. Experiment for yourself!

118 Chapter 5: Input/Output


5.2.5.2 Annunciator Out ut
The Apple II, Apple II Plus, and Apple Ile have four annunciator outputs,
which are pins of the hand control connector on which electrical impulses
can be transmitted. The signals on these pins are most commonly used to
control devices such as lamps and relays connected to the computer
through the hand control connector. The annunciator outputs can be turned
on and off with PEEK or POKE to the appropriate addresses; see Section F.4
for details and your Apple's reference manual for further technical
information.

5.2.5.3 The Utilit Strobe


The Apple II's utility strobe is a pin of the hand control connector that can
be triggered to send an electrical impulse lasting one-half microsecond. Like
the annunciators, it can be used to control a variety of devices connected to
the computer through the hand control connector. The utility strobe can be
triggered with a PEEK or POKE to address -16320. See Section F.4 for details
and your Apple's reference manual for further technical information.

5.2.5.4 Cassette Out ut


Two Applesoft statements, SAVE and STORE, can be used to write
information to a cassette tape recorder (Apple II, Apple II Plus, and
Apple Ile only). SAVE writes the Applesoft program currently in memory to
tape; STORE writes the contents of an integer or real array. For details, see
Appendix M.

5.2 Output 1 19
Chapter 6 Graphics


121
This chapter describes Applesoft's facilities for creating, changing,
displaying, and storing both low- and high-resolution graphic designs:
□ Section 6.1, "Low-Resolution Graphics," deals with 16-color graphics on a
40-by-48 grid.
□ Section 6.2, "High-Resolution Graphics," deals with 6-color graphics on a
280-by-192 grid.
□ Section 6.3, "Shape Tables," discusses the use of shape tables for
animation sequences.
□ Section 6.4, "Graphics in Text Mode," discusses MouseText, a set of
graphics you can use in text mode.

6. 1 Low-Resolution Graphics

The low-resolution graphics screen consists of 1920 blocks (40 columns by


48 rows) in 16 colors. This section describes the facilities available in
Applesoft for using low-resolution graphics:
□ The GR statement (see Section 6.1.1) instructs Applesoft to begin
displaying low-resolution graphics.
□ The COLOR= statement (see Section 6.1.2) controls the colors displayed
on the screen.
□ The PLOT statement (see Section 6.1.3) plots individual blocks on the
screen.
□ The HLIN statement (see Section 6.1.4) draws horizontal lines.
□ The VLIN statement (see Section 6.1.5) draws vertical lines.
□ The SCRN function (see Section 6.1.6) lets you determine what color is
currently displayed at a particular position on the graphics screen.

6. 1 . 1 The GR Statement

GR
The GR (for graphics) statement instructs the computer to display
low-resolution graphics. If the screen has been displaying text, it is changed
from 40 (or 80) columns by 24 lines of text to 40 columns by 40 rows of
graphics, with space for four lines of text at the bottom. (Text display can
be restored with the TEXT statement-see Section 5.2.4.) GR clears the
screen to black, moves the text cursor to the beginning of the bottom line
(line 24), clears any text window that may have been set, and sets the
low-resolution display color to O (black).

122 Chapter 6: Graphics


After executing a GR statement, you can convert the display to full-screen
graphics (a 40-by-48 grid with no space for text) with the statement
POKE statement: see Section 7.1.2 P O K E - 1 63 0 2 , 11
This statement changes the bottom four lines of text to eight rows of colored
blocks. To clear these rows to black, add
CALL statement: see Section 7.1.3 C A L L - 1 998
Note that the POKE statement must be executed after GR. If you execute
the POKE first, GR resets the screen to mixed graphics and text.
Switching From Hi-Resolution Page 2: If you execute a GR statement
while displaying high-resolution page 2 (see Section 6.2.2), GR clears its
usual screenful of memory but leaves you looking at page 2 of
low-resolution graphics and text. To avoid this problem, always use the
TEXT statement before switching from high-resolution page 2 to low
resolution.
For More Information: See Section F.3 for more information on the
use of the various text and graphics memory pages. See your Apple's
reference manual for further technical information on the Apple II's
graphics display capabilities.

6. 1 .2 The COLOR = Statement


COLOR• 1 2
COLOR• C C J >
COLOR• e x - 4 ) / 1 6
The COLOR= statement sets the display color for plotting low-resolution
graphics. There are 16 colors available, represented by numbers from 0
to 15 as shown in Table 6-1. When you enter low-resolution graphics, the GR
statement sets the display color to black (0).

6.1 Low-Resolution Graphics 123


Table 6-1. Color Codes for Low-Resolution Graphics

Code Color
0 Black
1 Magenta
2 Dark blue
3 Violet
4 Dark green
5 Gray 1
6 Medium blue
7 Light blue
8 Brown
9 Orange
10 Gray 2
11 Pink
12 Green
13 Yellow
14 Aqua
15 White

Colors in a Monochrome World: If you're using a monochrome


display (black-and-white, or some other single phosphor color), the
different colors appear on your screen as various patterns of shading.
The following short program displays each of the 16 available colors in a
horizontal bar across the screen:
1 B GR Displays low-resolution graphics.
2 8 F O R X • 8 TO 1 5 Executes loop for each color.
38 COLOR• X Sets next color.
HLIN statement: see Section 6.1.4 4 8 H L I N 8 , 39 A T X * 2 Draws a bar of this color across the
screen, leaving a blank row above it.
58 NEXT X Goes back for next color.
COLOR Isn't a Variable: Notice that the equal sign is part of the
keyword COLOR=; it doesn't represent an assignment to a variable
named COLOR. A statement such as
LET COLOR • X
causes a syntax error. The only way to find out the current display color
is to keep track of it yourself with a separate variable, as in the example.
You can specify a color code higher than 15, but the series of color values
simply repeats. That is, 16 is equivalent to 0, 18 is equivalent to 2, 35 is
equivalent to 3, and so on. However, a color value less than O or greater
than 255 stops the program with the message ? 1 L L E G A L Q U A N T 1 T V
ERROR.

124 Chapter 6 : Graphics


6 . 1 .3 The PLOT Statement

P L OT 2 0 , 1 2
PLOT X - 6 , Y + 2
P L O T T H E T A * 4 0 / C 2 * P I > , 2 4 - C S I N C TH E T A >
* 23)
The PLOT statement places a block of the current low-resolution display
color at a specified position on the screen. The first expression following the
keyword PLOT specifies the column in which the block is to be plotted
(numbered O to 39, from left to right); the second expression, separated from
the first by a comma, designates the row (numbered O to 39 for mixed text
and graphics, 0 to 47 for full-screen graphics, from top to bottom). For
example, the following program plots a block of pink in column 20, row 2 of
the screen:
1 0 GR Displays low-resolution graphics.
2 0 COLOR • 1 1 Sets display color to pink.
3 0 PLOT 2 0 , 2 Plots a block of pink in column 20,
row 2.
Figure 6-1 shows the system of coordinates used to designate positions on
the low-resolution graphics screen. Position 0,0 is the top-left corner and
position 39,0 the top-right. When displaying mixed graphics and text, the
bottom-left corner is position 0,39 and the bottom-right is 39,39; in
full-screen graphics, the bottom-left corner is 0,47 and the bottom-right
is 39,47.

6.1 Low-Resolution Graphics 125


Figure 6-1. Screen Coordinates for Low-Resolution Graphics
0, 0 39, 0

0, 39 39, 39
(or 0, 47) ._____________, (or 39, 47)

PLOT With M'ixed Graphics and Text: If Applesoft is displaying


mixed graphics and text and the plotting coordinates designate a row
from 40 to 47, a text character instead of a block of color is displayed at
the specified coordinates. The particular character displayed depends on
the current low-resolution display color. Here's a program to demonstrate
this effect:
1 0 GR Displays mixed low-resolution
graphics.
2 0 F O R Y • 0 TO 47 Loops over all screen rows.
3 0 FOR X • 0 TO 39 Loops over all screen columns.
4 0 COLOR • X Uses color corresponding to
column number (colors O to 15
repeat after column 15).
5 0 PLOT X , y Plots a block at column X, row Y.
60 NEXT X Loops to next column.
70 NEXT y Loops to next row.
Try changing line 10 to
10 TEXT
to see the effect on the full screen.
A column coordinate outside the range O to 39 or a row coordinate outside
the range O to 47 causes the program to halt with the message ? 1 L L E G A L
Q U A N T I TY E R R O R .

126 Chapter 6 : Graphics


6 . 1 .4 The HLIN Statement
H L I N 5 , 2 0 AT 35
HL I N X , Y AT Z
H L I N Q - 3 , J * 58 A T V X
The HLIN (for horizontal line) statement draws a horizontal line on the
screen in the current low-resolution display color (see Section 6.1.2). The
two expressions following the keyword HLIN, separated by a comma,
designate the columns in which the line is to begin and end; the expression
following the keyword AT specifies the row in which the line is to be
drawn. The first end point may be less than, equal to, or greater than the
second. For example,
1 " GR Displays low-resolution graphics.
2 0 COLOR • 4 Sets color to dark green.
3 0 HL I N 1 0 , 3 0 AT 2 0 Draws a horizontal green line in
row 20 from column 10 to
column 30.
HLIN in Text Instead of Graphics: If you use HLIN while displaying
text instead of graphics, or with a row coordinate from 40 to 47 while
displaying mixed graphics and text, Applesoft displays a row of
characters instead of a bar of color. For example, if line 10 were changed
to
1" TEXT
the result would be a row of dollar signs instead of a bar of dark green. In
most cases, when you see patterns like these on your screen it means you
forgot to include a GR statement.
A column coordinate outside the range O to 39 or a row coordinate outside
the range O to 47 causes the program to halt with the message ? 1 L L E G A L
Q U A N T I TY E R R O R .
The HLIN statement has no visible effect if you use it while displaying
high-resolution graphics.

6.1 Low-Resolution Graphics 127


6.1 .5 The VLIN Statement
Vl l t-1 5 , 2 8 AT 3 5
Vl l t-1 X , V A T Z
VL i l'I Q - 3 , J • 58 AT VX

The VLIN (for vertical line) statement draws a vertical line on the screen in
the current low-resolution display color (see Section 6.1.2). The two
expressions following the keyword VLIN, separated by a comma, designate
the rows in which the line is to begin and end; the expression following the
keyword AT specifies the column in which the line is to be drawn. The first
end point may be less than, equal to, or greater than the second. For
example,
1 8 GR Displays low-resolution graphics.
2 8 COLOR • 4 Sets color to dark green.
3 8 VL i l'I 1 8 , 3 8 A T 2 8 Draws a vertical green line in
column 20 from row 10 to row 30.
VLIN in Text Instead of Graphics: If you use VLIN while displaying
text instead of graphics, or if part of the line being drawn goes beyond
row 39 while displaying mixed graphics and text, Applesoft displays text
characters instead of blocks of color. For example, if line 10 were changed
to
18 TEXT

the result would be a row of flashing o's and a dollar sign instead of a bar
of dark green.
A column coordinate outside the range O to 39 or a row coordinate outside
the range O to 47 causes the program to halt with the message ? I L L E GA L
Q U A N T I TY E R R O R .

The VLIN statement has no visible effect if you use it while displaying
high-resolution graphics.

128 Chapter 6: Graphics


6 . 1 .6 The SCRN Function
The SCRN (for screen) function reads the color currently displayed at a
designated position on the low-resolution graphics screen. This function
takes two arguments, the first specifying the column and the second the
row of the desired position. It yields a number from O to 15 representing the
color displayed at that position. For example, the expression
SCRH CS , 9)
yields the code (see Table 6-1) for the color displayed at column 5 , row 9.
The SCRN function is not intended for use with high-resolution graphics.
For Experts Only-Strange Extensions: Although the ordinary
limits for coordinates on the low-resolution graphics screen are 39 and 47,
SCRN actually accepts values up to 47 for both arguments. But if the
column parameter is greater than the usual limit of 39, odd things
happen. The code yielded by SCRN gives the color for the block whose
column is the designated column minus 40, and whose row is the
designated row plus 16.
If the row-plus-16 number is in the range 40 through 47, and if mixed
graphics and text are being displayed, then the code yielded is not a color
code, but is related to the text character at that position in the text area
below the graphics (see "For Experts Only-Reading the Text Screen,"
below).
If the row-plus-16 number is in the range 48 to 63, SCRN yields a
meaningless result.
For Experts Only-Reading the Text Screen: When text is being
displayed, SCRN yields numbers in the range O to 15 whose value is either
the high-order four bits (if the row number is odd) or the low-order four
bits (if the row number is even) of the character in column C + 1 and
row (R + 1) / 2, where C and R are the column and row numbers given as
arguments to SCRN. Thus the following expression yields the character
at position X, Y:
CHRS C SCRH e x - 1 , 2 * C Y - 1 ) + 1 ) * 1 6
+ SCRH e x - 1 , 2 * C Y - 1 ) ) )

6.1 Low-Resolution Graphics 129


6.2 High-Resolution Graphics

There are two separate regions in the Apple H's memory, designated page 1
and page 2, that can be used for displaying high-resolution graphics. Each
consists of 53,760 points (280 columns by 192 rows) in six colors. This
section describes the facilities available in Applesoft for using
high-resolution graphics:
□ The HGR statement (see Section 6.2.1) instructs Applesoft to begin
displaying page 1 of high-resolution graphics.
□ The HGR2 statement (see Section 6.2.2) instructs Applesoft to begin
displaying page 2 of high-resolution graphics.
□ The HCOLOR= statement (see Section 6.2.3) controls the colors
displayed on the high-resolution screen.
□ The HPLOT statement (see Section 6.2.4) plots individual points and
lines on the high-resolution screen.
Section 6.2.5 tells how to protect your programs and high-resolution
graphics from overwriting each other in the computer's memory.

6.2. 1 The HGR Statement


HGR
The HGR (for high-resolution graphics) statement instructs Applesoft to
display page 1 of high-resolution graphics. If the screen has been displaying
text, it is changed from 40 (or 80) columns by 24 lines of text to 280 columns
by 160 rows of high-resolution graphics, with space for four lines of text at
the bottom. The graphics area of the screen is cleared to black; the
high-resolution display color is not affected. HGR doesn't affect the contents
of the text screen, the setting of the text window, or the location of the text
cursor; the cursor is not visible unless it is in one of the bottom four lines of
the screen.
After executing·an HGR statement, you can convert the display to
full-screen graphics (a 280-by-192 grid with no space for text) with the
statement
P O K E - 1 63 0 2 , 0

This statement changes the bottom four lines of text to high-resolution


graphics. To return to mixed graphics and text, use
P O K E - 1 63 0 1 , 0

130 Chapter 6: Graphics


Notice that the first POKE statement must be executed after HGR. If you
execute the POKE first, HGR resets the screen to mixed graphics and text.
The TEXT statement returns to text display with the text window set to the
full screen and the cursor at the bottom of the screen. To turn off
high-resolution graphics and return to text display with the text window
and cursor intact, use the statement
POKE - 1 63 8 3 , 8

.A.Warning If you use the reserved word HGR as the first three characters of a
variable name, the HGR statement may be executed before a syntax error
is detected. For example, executing the statement
HGR I P • 4
unexpectedly turns on high-resolution graphics and may destroy part of
your program.
For More Information: If you intend to use HGR with an Applesoft
program longer than about 6000 (decimal) bytes, see Section 6.2.5 on how
to protect your program and graphics from overwriting each other.
See Section F.3 for more information on the use of the various text and
graphics memory pages, and Section H.l for the memory locations
occupied by the high-resolution graphics pages. See your computer's
reference manual for further technical information on the Apple II's
graphics display capabilities.

6.2.2 The HGR2 Statement


HGR2
The HGR2 (for high-resolution graphics, page 2) statement instructs
Applesoft to display page 2 of high-resolution graphics. If the screen has
been displaying text, it is changed from 40 (or 80) columns by 24 lines of
text to 280 columns by 192 rows of high-resolution graphics. The screen is
cleared to black; the high-resolution display color is not affected. HGR2
doesn't affect the contents of the text screen, the setting of the text
window, or the location of the text cursor.

6.2 High-Resolution Graphics 131


The TEXT statement (see Section 5.2.4) returns to text display with the
text window set to the full screen and the cursor at the bottom of the
screen. To turn off high-resolution graphics and return to text display with
the text window and cursor intact, use the statements
P O K E - 1 63 Bll , 0 Switches from page 2 to page 1
P O K E - 1 63 0 3 , 0 Switches from graphics to text
Avoid Mixing Graphics and Text With HGR2: After executing an
HGR2 statement, you can convert the display to mixed graphics and text
(a 280-by-160 grid with four lines of text at the bottom) with the
statement
P O K E - 1 63 0 1 , 0
However, when you use this statement while displaying high-resolution
page 2, the four lines of text are taken from text page 2 instead of the
usual page 1. Since Applesoft uses the same memory locations allocated
to text page 2 for program storage, you end up displaying garbage in the
bottom four lines of your screen. For this reason, most programmers avoid
mixing graphics and text when using high-resolution page 2.
.&.Warning If you use the reserved word HGR2 as the first four characters of a
variable name, the HGR2 statement may be executed before a syntax
error is detected. For example, executing the statement
HGR2P I E CES = 4
unexpectedly turns on high-resolution graphics and may destroy part of
your program.
For More Information: If you intend to use HGR2 with an Applesoft
program longer than about 14000 (decimal) bytes, see Section 6.2.5 on
how to protect your program and graphics from overwriting each other.
See Section F.3 for more information on the use of the various text and
graphics memory pages, and Section H.l for the memory locations
occupied by the high-resolution graphics pages. See your computer's
reference manual for further technical information on the Apple H's
graphics display capabilities.

132 Chapter 6: Graphics


6.2.3 The HCOLOR = Statement
HC□L□R • 6
HC□L□R• C C J >
HC□L□R • e x - 4 ) / 8
The HCOLOR= (for high-resolution color) statement sets the display color
for plotting high-resolution graphics. There are six colors available,
represented by numbers from O to 7, as shown in Table 6-2.

Table 6-2. Color Codes for High-Resolution Graphics

Code Color
0 Black 1
1 Green
2 Violet
3 White 1
4 Black 2
5 Orange
6 Blue
7 White 2

Color in a Monochrome World: If you're using a monochrome display


(black-and-white, or some other single phosphor color), the different
colors appear on your screen as various patterns of shading.
The high-resolution display color is not affected by HGR, HGR2, or RUN.
Until your program executes an HCOLOR= statement, the display color for
high-resolution graphics is indeterminate.
HCOLOR Isn't a Variable: Notice that the equal sign is part of the
keyword HCOLOR=; it doesn't represent an assignment to a variable
named HCOLOR. A statement such as
LET HCOLOR • X
causes a syntax error. The only way to find out the current display color
is to keep track of it yourself with a separate variable.

6.2 High-Resolution Graphics 133


Curious Behavior: As you wander deeper into the recesses of the
· Apple H's graphics system, you'll begin to notice that the colors in
high-resolution graphics don't always act as you might expect. For
example, carefully drawn vertical lines may refuse to be visible, a white
line crossing a field of green may leave jagged blocks of orange in its
wake, or a point plotted with HCOLOR= 3 (white 1) may look blue if its
column coordinate is even, green if the column coordinate is odd, and
white only if a point is plotted in the next column as well. These strange
phenomena are a result of the way the Apple H's high-resolution graphics
features interact with the color circuitry in your television set. See your
computer's reference manual for further explanation.
If you specify a color code higher than 7, your program halts with the
message ? I L LEGAL Q U A HT I TV E R R O R.

6.2.4 The HPLOT Statement


HPLOT 1 4 8 , 8 8
H P L OT X - 1 6 , V + 1 2 T O X + 1 6 , V - 1 2
H P L OT 7 8 , 4 8 TO 2 1 8 , 4 8 TO 2 1 8 , 1 2 8 TO 7 8 , 1 2 8
T O 78 , 4 8
H P L O T TO THETA * 2 8 8 / C 2 * P I > , 96 -
C S I H C T H E T A > * 95 )
The HPLOT (for high-resolution plot) statement plots points and lines on
the high-resolution graphics screen in the current high-resolution display
color. The first expression in each pair specifies a column (numbered 0
to 279, from left to right); the second expression, separated from the first by
a comma, designates a row (numbered O to 159 for mixed text and graphics,
0 to 191 for full-screen graphics, from top to bottom). For example, the
following program plots a white point at column 100, row 50 of the screen:
1 8 HGR Displays high-resolution graphics.
211 H C O L O R • 3 Sets display color to white 1.
3 11 H P L OT 1 11 11 , 5 11 Plots a point at column 100, row 50.
..&.Warning I Be sure to precede HPLOT by either HGR or HGR2 or you will write over
lots of memory, including your program and variables.

134 Chapter 6: Graphics


Figure 6-2 shows the system of coordinates used to designate positions on
the high-resolution graphics screen. Position 0,0 is the top-left corner and
position 279,0 the top-right. When displaying mixed graphics and text, the
bottom-left corner is position 0,159 and the bottom-right is 279,159; in
full-screen graphics, the bottom-left corner is 0,191 and the bottom-right
is 279,191.

Figure 6-2. Screen Coordinates for HiM-Resolution Graphics


0, 0 279, 0

0, 159 279, 159


(or 0, 191) .______________. (or 279, 191)

To draw a line with HPLOT, specify the starting and ending points,
separated by the keyword TO. The next example draws a white line across
the screen:
1 0 HGR Displays high-resolution graphics.
20 H C O L O R • 3 Sets display color to white l.
3 8 H P L O T 0 , 5 8 TO 2 7 9 , 58 Draws a line across row 50.
You can draw a series of connected lines in the same HPWT statement by
using a series of TO clauses. Each line begins where the last one ended. The
following program, for example, draws a rectangle, as illustrated by the
solid lines in Figure 6-3:
1 8 HGR Displays high-resolution graphics.
28 H C O L O R • 3 Sets display color to white 1.
38 H P L O T 7 8 , ◄ 8 TO 2 1 8 , ◄ 8 TO 2 1 8 , 1 2 8 T O 7 8 ,
1 2 0 TO 1 0 , ◄ 8 Draws a rectangle.

Figure 6-3. Drawing a Rectangle With HPLOT

(start here: ) 70, 40 --... .._ 210, 40


.... ....
..... .....
...... ......
...... .....
..... .....
..... .....
..... .....
70, 120 ............. 2 10, 120

6.2 High-Resolution Graphics 135


You can extend the series of lines almost indefinitely within the same
HPLOT statement, subject only to the limit of 239 characters in a program
line.
You can also continue from wherever the last HPLOT statement ended, by
writing the keyword TO immediately after the word HPLOT. For example,
adding the line
48 H P L O T TO 2 1 8 , 1 28

to the previous program causes it to draw in the diagonal of the rectangle,


represented by the dashed line in Figure 6-3. Applesoft assumes that the
starting point (which ordinarily would have appeared between the words
HPLOT and TO) is the last point plotted.
The color of the new line drawn by HPLOT TO is the same as that of the
last point plotted. Even if you insert a new HCOLOR= statement between
lines 30 and 40, the line drawn by the HPLOT TO in program line 40 appears
in the same color as those drawn in line 30.
To change the color of the line, use a whole new HPLOT:
35 HCOLOR • s Changes color to blue.
48 HPLOT 7 8 , 4 8 TO 2 1 8 , 1 28
Continues drawing from last point.
HPLOT With M'ixed Graphics and Text: If the screen is displaying
mixed text and graphics, an attempt to plot a point whose row coordinate
is in the range 160 to 191 has no visible effect. However, if you draw a line
either beginning or ending in rows 160 to 191, Applesoft displays as much
of the line as it can. If you later switch to full-screen graphics with
POKE -16302,0 the hidden portion of the line appears.
If the column coordinate given to HPLOT is outside the range 0 to 279, or the
row coordinate outside the range O to 191, the program halts with the
message ? I L L E G A L QUA HT I TY E R R O R .

136 Chapter 6: Graphics


6.2.5 Protecting High-Resolution Graphics

The two high-resolution graphics pages lie pretty much in the center of
Apple II memory allocation: see things: page 1 resides at memory addresses 8192 to 16383
Section HJ (hexadecimal $2000 to $3FFF) and page 2 at addresses 16384 to 24575
(hexadecimal $4000 to $5FFF). Because Applesoft program storage begins
at location 2048 (hexadecimal $800) and works its way up, it's easy for your
program and graphics to get in each other's way. For example, if you're
using the HGR statement (see Section 6.2.1) to display page 1 of
high-resolution graphics, you have only 6144 bytes of program and variable
space (8192 minus 2048) before your program overwrites the graphics area.
This section tells how to prevent them from colliding.
One way to protect your program and graphics from each other is to use the
HIMEM: statement (see Section 7.2.1) to set the upper limit of program
memory at 8192. This is a reasonable method to use for short programs; but
Applesoft tends to use a lot of memory, and longer programs would soon run
out of space.
Another method that allows the program a bit more breathing room is to use
the second page of graphics instead of the first (HGR2 instead of HGR). This
has the benefit of starting the graphics at a higher memory location, so you
can set HIMEM: to 16384 instead of 8192, allowing 14336 bytes (16384
minus 2048) for your program and variable space. The disadvantage of this
method is that you lose the four lines of text at the bottom of the screen,
which are available with HGR but not with HGR2.
A third method, probably the best for long programs with lots of variables, is
to use the wizardry of the POKE statement to change the start, instead of
the end, of Applesoft's program storage space. The following statements
start program and variable storage above graphics page 1, beginning at
address 16384 (hexadecimal $4000):
POKE 1 03 , 1
P O K E 1 0 4 , 64
P O K E 1 63 8 4 , ll
These statements start program and variable storage above high-resolution
page 2, beginning at address 24576 (hexadecimal $6000):
POKE 1 03 , 1
P O K E 1 0 4 , 96
P O K E 2 4 5 7 6 , ll

6.2 High-Resolution Graphics 137


No matter where you start program space in memory, your next command
should be
HEW
to clear out any old variables and system control information so you can
start a fresh program beginning at the new location. (If your computer is
equipped with one or more disk drives, you can accomplish the same thing
by loading a new program from a disk with the RUN command.)

6.3 Shape Tables


Applesoft has a number of special facilities that allow you to manipulate
shape tables defining shapes on the high-resolution graphics screen.
Because shape tables have the advantages of both flexible design and very
fast execution, they are ideal for applications such as on-screen animation.
This section contains detailed information on creating and manipulating
shape tables.
For Hackers Only: Since the advent of the Apple II series of computers,
a number of excellent graphics software packages have appeared on the
market. Available at most computer stores, these packages take the
hard-core technical work (binary arithmetic and machine-language
manipulation) out of designing and using shape tables. The information in
this section is intended for those programmers who enjoy "twiddling the
bits" themselves.
To use this section effectively, you'll need to know about bits and bytes
and the rudiments of hexadecimal arithmetic. This information is
available in any basic text on computer science; see the bibliography in
the owner's manual that came with your computer. All computer memory
addresses in this section are in hexadecimal; all other numbers, unless
otherwise noted, are in decimal.

6.3. 1 Creating a Shape Table

An Applesoft shape definition consists of a sequence of plotting vectors that


are stored in a series of consecutive bytes in the computer's memory. One or
more such shape definitions, with their indexes (see Section 6.3.1.4), make
up a shape table.

138 Chapter 6: Graphics


6.3. 1 .1 Plotting Vectors
Each byte in a shape definition has three sections. Each section can contain
plotting vector: a code representing a a plotting vector, specifying whether or not to plot a point at the current
single step in drawing a shape on the screen position and in what direction to move (up, down, left, or right)
screen before processing the next vector. Thus each byte can represent up to three
plotting vectors.
Figure 6-4 shows how the three sections are arranged within each of the
bytes that make up a shape definition. In each plotting vector, bit P
specifies whether to plot a point before moving, and the pair of bits
designated DD specify the direction in which to move before processing the
next vecror.

Figure 6-4. Plotting Vectors in a Byte


section: C B A

bit number: !7 6 5 4 3 2 1 0 !
specifies: D D P D D P D D

if DD = 00 move up
= 01 move right
= 10 move down
= 11 move left
if P = 0 don't plot
= 1 plot a point

Notice that the last section in each byte (the two high-order bits, labeled C
in the figure) does not include a P bit. The value of P in such a section is
always assumed t,o be O (don't plot); thus section C can only specify a move
without plotting.

6.3 Shape Tables 139


6.3. 1 .2 How Plotting Vectors Are Interpreted
The DRAW and XDRAW statements (see Section 6.3.2) read through each
byte in the shape definition, from the first byte in the definition to the last.
Within each byte, the sections are processed from right to left: section A,
then B, then C. When a byte is encountered that contains all zeros, the
shape definition is complete.
At any section in the byte, if all the remaining sections contain only zeros,
then those sections are ignored. Thus a byte can't end with a move in
section C of 00 (move up without plotting) because that section, containing
only zeros, is ignored. Similarly, if section C is 00 (ignored), then section B
cannot be a move of 000 (move up without plotting), since that is also
ignored. And a vector of 000 in section A ends your shape definition unless
there is a 1 bit somewhere in section B or section C.

6.3. 1 .3 Coding a Shape Table


Suppose you want to draw a shape like that shown in Figure 6-5a. To
convert the shape into an Applesoft shape definition, follow these steps:
1. Draw the shape on graph paper, one dot per square.
2. Decide where to start drawing the shape and draw a path through each
point in the shape, using only 90-degree angles on the turns, as in
Figure 6-5b.
3. Redraw the shape as a series of plotting vectors, each vector moving one
place up, down, left, or right, and distinguish those vectors that plot a
point before movipg. This step is illustrated in Figure 6-5c; vectors that
plot before moving are marked in the figure with a dot at the beginning
of the direction arrow.
4. "Unwrap" the vectors and write them out in sequential order, as in
Figure 6-5d.

140 Chapter 6: Graphics


Figure 6-5. Plotting a Shape
a. • • •
• •
• •
• •
• • •

b.

c.

Now you're ready to code the plotting vectors as a shape definition table.
Figure 6-6 gives the binary codes corresponding to each possible vector. For
each vector in the shape, determine the proper bit code and place it in the
next available section in the table, as shown in Figure 6-7. If the code won't
fit (for instance, the vector in section C can't plot a point) or is a 00 (or 000)
at the end of a byte, then just fill that section with zeros.

6.3 Shape Tables 141


Figure 6-6. Codes for Plotting Vectors

I
vector code

t 000

-
-+ 0()1 or 0l mo,e oo!J
l 010 or 10
01 1 or 1 1

-t 100
1 ... ... -.
-l
101
1 10
lll

Figure 6-7. Shape Definition Table

-'t -'f
section C B A C B A
byte 0
010
l
lll

- -t
2
100
3

-lt
01 100
4
101

-t
..,;.,.
i 010 101

-l
110 1 10
011 1 10
lll
00 000 000 - denotes end of shape
definition
cannot plot
or move up

The final step is to convert the binary codes representing the plotting
vectors into hexadecimai fonn so you can type them into the computer.

142 Chapter 6: Graphics


Table 6-3. Hexadecimal Byte Codes

Binary Hex
0000 0
0001 1
0010 2
0011 3
0100 4
0101 5
0110 6
0111 7
1000 8
1001 9
1010 A
1011 B
1100 C
1101 D
1110 E
1111 F

As shown in Table 6-3, each hexadecimal code corresponds to a group of


four bits; so each row of eight bits in your definition table is represented by
two such codes (called hexadecimal digits). This step is illustrated in
Figure 6-8. The final shape definition for the shape in Figure 6-5 is
1 2 3F 2 0 6 4 2D 1 5 36 1 E 0 7 0 0

Figure 6-8. Converting the Shape Definition to Hexadecimal

__
bytes
section
byte 0
_,......___0 0 1 0
C B A
=
recoded in hex
12
000 1
I 00 1 1 1111 = 3F
2 00 1 0 0000 = 20
3 0110 0100 = 64
4 0010 1 10I = 2D
5 000 1 0101 = 15
6 00 1 1 0110 = 36
7 000 1 1 1 10 = IE
8 0000 011 1 = 07
9 0000 0000 = 0 0 - denotes end of shape definition
_.. ,_,,
hex: digit 1 digit 2

6.3 Shape Tables 143


6.3. 1 .4 The Shape Table Index
There is still a little more information you need to provide before you have a
complete shape table: the table must have an index. This is simply a list
indicating where in memory the computer can find a particular shape. The
computer needs the index so that it can find the shape later, when your
Applesoft program tries to draw the shape on the screen.
The form of a complete shape table, including the index, is shown in
Figure 6-9. The shape table's starting location, whose address is called S in
the figure, contains the number of shape definitions in the table
(between 00 and FF) in hexadecimal. The next byte (address S + 1) is
unused; it is followed by a sequence of two-byte pairs giving the locations of
the shapes in the table. (Notice that the shape locations are given with the
bytes reversed-low-order byte first-and that the locations are specified
relative to address S, the start of the table itself, and not in absolute
memory addresses.) For simplicity, the shape definitions themselves are
usually placed immediately after the index.

144 Chapter 6: Graphics


Figure 6-9. Form of a Complete Shape Table

start = S byte S + O n (O to FF) +- total number of shape definitions


+l unused
+2 lower 2 digits D 1: index to first byte of shape
}
+3 upper 2 digits definition #l, relative to S
+4 lower 2 digits D2: index to first byte of shape
index +5 upper 2 digits definition #2, relative to S

. . .
. . .
+2n lower 2 digits Dn: index to first byte of shape
}
+2n + 1 upper 2 digits definition #n, relative to S

l
S + DI first byte
shape definition # 1
last byte = 00

S + D2 first byte

shape last byte = 00


definitions

S + Dn first byte

last byte = 00

6.3 Shape Tables 145


Figure 6-10 shows the complete shape table for our example. Since there's
only one shape in the table, location S contains the value 1 . Bytes S + 2 and
S + 3 are needed to specify the shape's location; the shape definition itself
can start in the next available byte, S + 4. So index byte S + 2 contains the
value 04 and index byte S + 3 contains the value 00. Next come the bytes of
the shape definition, as derived in Figure 6-8. The table ends with the O byte
marking the end of the shape definition.

Figure 6-10. A Complete Shape Table


start
(store address
in ES and E9)

byte 0 01 -number of shapes


1 00
2 04 } index to shape definition # 1, relative to start
3 00
first byte- 4 12
5 3F
6 20
7 64
8 2D
9 15 shape definition # 1
A 36
B IE
C 07
last byte - D 00

6.3. 1 .5 Loading a Shape Table Into Memory


Now that you've figured out how to code your shape in the form of a shape
table, you have to get it into the computer's memory so Applesoft can draw
it on the screen. You also have to tell Applesoft where in memory to look for
the shape table.
First you must choose a starting address. This address must be less than the
highest memory address available in your system, and must not be located
in the high-resolution graphics page that you'll be using to display the
shapes Oocations 2000 through 3FFF for page 1, 4000 through 5FFF for
page 2). For this example, we'll use hexadecimal address lDFC, which is
just below high-resolution page 1.

146 Chapter 6 : Graphics


•Warning Be sure you don't place your shape table in an area that conflicts with
your program or variable space, or with vital internal information used by
the system. See "Protecting Your Shape Table," in this section, for
information on how to keep your program and shape table out of each
other's way; see Appendix H for the memory locations of important
system information.
While you're in the process of creating the shape table, you'll probably want
to type the table into memory directly from the keyboard using the Monitor
program. Then you can draw the shape on the screen with an
immediate-execution DRAW statement (see Section 6.3.2.1 ), see if it looks
the way you want it, and go back and change it if it doesn't. See your
computer's reference manual for information on the use of the Monitor
program.
Once your shape table looks correct, you'll want to be able to use it from
within a program. Your program can store the table in memory by using
POKE (see Section 7.1.2). To do this, you have to convert the starting
address of the table, and each byte of the table itself, from hexadecimal to
decimal, then store the decimal values in memory one at a time.
The shape table we've been developing consists of the following
hexadecimal bytes:
01 00 04 00 12 3F 20 64 2D 15 36 1E 07 00
The equivalent decimal values are the following:
1 0 4 0 18 63 32 100 45 21 54 30 7 0
The starting address we've chosen for the table, hexadecimal lDFC, is
equivalent to 7676 decimal. So the following statements in a program store
the shape table in memory:
111 F O R x • 7676 TO 7689 Memory locations where shape
tables will go.
2 11 R E A D A Reads byte of table.
3 11 P o K E x , A Stores at next location.
◄ II HEXT x Goes back for next byte.
5 11 DATA 1 , ll , 4 , ll , 1 8 , 63 , 3 2 , 1 11 11 , 4 5 , 2 1 , 5 4 , 3 11 , 7 , II
Contents of table.
Another way for a program to store a shape table in memory is to load it
from a disk or tape cassette. Details are given in Section 6.3.1.6.

6.3 Shape Tables 147


Now that you have your shape table in memory, you have to tell Applesoft
where to find it. Applesoft looks for the table's starting address in
hexadecimal locations E8 (low-order byte) and E9 (high-order byte), so you
have to arrange somehow to store the correct starting address in these
locations.
If you've been using the Monitor program to type the shape table into
memory from the keyboard, you can type its address into locations E8
and E9 the same way. From within a program, you can do it with two more
POKE statements. The hexadecimal addresses E8 and E9 are equivalent to
decimal 232 and 233; the two bytes of the table's starting address, 1 D and
FC, are equivalent to 29 and 252. So the following POKE statements will do
the trick:
SB POKE 232 , 2 5 2 : POKE 233 , 29
Your shape table is now stored correctly in the computer's memory, ready
to be drawn on the screen from within your program with a ORAW
statement.
A Reminder: Remember to store the two bytes of the starting address in
reverse order, with the low-order byte before the high-order byte. This
convention is always followed when storing memory addresses in the
Apple II's memory.
When you use SHLOAD (see Section 6.3.2.5) to load a shape table from a
tape cassette, the starting address is set up for you automatically in the
proper locations.
ProDOS Users Take Note: ProDOS deals with memory in 256-byte
chunks. Thus in the first example cited, you set HIMEM: to 7680, which is
exactly 30 times 256.
A Warning If you locate your shape table above the high-resolution graphics page and
your system is equipped with one or more disk drives, be careful not to
run into the memory space occupied by the disk operating system. Check
the disk operating system manual for the exact starting memory location.

148 Chapter 6: Graphics


Protecting Your Shape Table: In choosing a location in memory for
your shape table, it's important to keep it out of the way of your Applesoft
program, so the two don't overwrite each other. One way to do this is
simply to use HIMEM: (see Section 7.2.1) to set the upper limit of program
memory to the starting address of the table. In the example, HIMEM: is
set to 7676. This too is done automatically when you use SHLOAD to get
the table from a tape cassette.
Unfortunately, this method leaves very little room for your program and
variables-in the example, only 5628 bytes (7676 minus 2048); You can
buy a little more space for your program by setting HIMEM: to the
beginning of the graphics page you're using (8192 for page 1, 16384 for
page 2), as suggested in Section 6.2.5. You can then locate the shape table
above the graphics page: that is, above location 16384 if you're using
page 1 , 24576 if you're using page 2.
Perhaps the best method is to locate the program and variables above the
graphics page, again as described in Section 6.2.5. This leaves room for
the shape table below the start of the graphics page. If you're using
graphics page 1, that's 6144 bytes (8192 minus 2048)-enough room for a
very extensive shape table!

6.3. 1 .6 Saving and Loading a Shape Table


To save your shape table on a disk, you need to know two things:
□ The starting address of the table (lDFC in the example)
□ The length of the table in bytes (14 in the example-hexadecimal
OOOE-including the "stop" byte).
Next, you must choose a filename under which to store your shape table on
the disk. We'll use SHAPEl for this example.
To save the table on a disk in immediate execution, put the disk in the disk
drive and issue the following command:
BSAVE S H A P E 1 , A $ 1 DF C , L $ 0 0 0 E
binary file: a file containing "raw" This command says "store a binary file named SHAPEl on the disk,
information not expressed in text form containing the current contents of memory starting at hexadecimal
address lDFC, and 0OOE (hexadecimal) bytes long."
If You're Not Using Drive 1: If you're using a disk drive other than the
main startup drive, the BSAVE command should also include port and
drive parameters specifying which disk drive to use; see your disk
operating system manual for details.

6.3 Shape Tables 149


To issue the same command from within an Applesoft program, use the
statement
P R I HT C H R S C 4 ) ; "BSAVE S H A P E 1 , A $ 1 DF C ,
L$08 "E"
Again, see your disk operating system manual for details.
To load the table back into memory from the disk, you can use the
command
BLOAD SHAP E 1
in immediate execution, or the statement
P R I HT C H R $ C 4 > ; " B L O A D S H A P E 1 "
from within a program. Notice that you don't have to include the starting
address and the table length; this information is picked up automatically
from within the disk file itself. However, the starting address is not stored
automatically in the special addresses where Applesoft looks for them, so
you (or your program) have to do that for yourself:
POKE 232 , 252 : POKE 233 , 29
To save your shape table on a tape cassette (Apple II, Apple II Plus, and
Apple Ile only) you need to know three things:
□ The starting address of the table (lDFC in the example);
□ The last address of the table (1E09 in the example);
□ The difference between the first two items (hexadecimal 000D,
decimal 14).
Item 3, the difference between the last address and the first address of the
table, must be stored in locations O (low-order byte) and 1 (high-order byte).
From the Monitor, type
II : II D 11 11
and press I R ETURN 1. Now you must write to the cassette first the table
length from locations O to 1, then the shape table itself:
11 . 1 W 1 DF C . 1 E ll 9W
Don't press I RETURN I until you have put a cassette in your tape recorder,
rewound it, and started it recording.
To load the shape table back from the tape, use the SHLOAD statement (see
Section 6.3.2.5).

150 Chapter 6: Graphics


6.3.2 Using Shape Tables
The commands in this section are used to draw and manipulate on the
screen shapes defined by a shape table in memory:
□ DRAW and XDRAW draw shapes from a shape table onto the
high-resolution screen.
□ SCALE= controls the sc ale at which shapes are drawn on the screen.
□ ROT= controls the rotation of shapes on the screen.
□ SHLOAD loads a shape table into memory from a tape cassette (Apple II,
Apple II Plus, and Apple Ile only).
As a preview of what the commands in this section can do, here's a sample
Applesoft program for you to try. The program first stores in memory the
shape table developed in Section 6.3.1, using the POKE statement (see
Section 6.3.1.5). Then it uses the statements described in this section to
produce a somewhat surprising effect on the screen. See if you can guess
what the program will display, then type it, switch to 40-column display,
and run it:
10 F O R X • 7676 TO 7689 Memory locations where shape table
will go.
20 READ A Reads byte of table.
30 POKE X, A Stores at next location.
40 HEXT X Goes back for next byte.
50 DATA 1 , 0 , 4 , 0 , 1 8 , 63 , 3 2 , 1 0 0 , 4 5 , 2 1 , 5 4 , 3 0 , 7 , 8
Contents of table.
60 POKE 232 , 252 : POKE 233 , 29
1 0 0 HGR2
1 1 8 HCOLOR • 3
1 2 8 F O R R • 1 TO 5 8
1 3 0 ROT• R
1 48 SCALE• R
1 5 0 X D R AW 1 A T 1 4 8 , 96
1 60 HEXT R
1 7 8 GOTO 1 2 8
When you get tired of watching the show, interrupt the program by pressing
� to regain control of the system.

6.3 Shape Tables 151


6.3.2.1 The DRAW Statement
DRAW 5
D R A W 1 AT 1 4 0 , 96
D R A W S H A P E AT X C E HT E R + X O F F SE T , Y C E H T E R
+ YOFFSET
The DRAW statement draws a shape from a shape table (see Section 6.3.1)
on the high-resolution graphics screen at a specified location. The
expression following the keyword DRAW gives the index number of the
desired shape in the shape table currently in memory. The location at
which the shape is to be drawn is specified by a pair of expressions
following the keyword AT, separated by a comma. The first expression
gives the horizontal screen position of the shape's starting point; the second
gives the vertical position.
The designated shape is drawn in the current display color, scale, and
rotation, as specified in the most recently executed HCOLOR= , SCALE= ,
and ROT= statements.
•Warning You must specify the color, scale, and rotation of the shape before DRAW
is executed. If any of these have not been specified, the results are
random: odd dots may appear, bizarre shapes may be drawn, and memory
may be overwritten.
Assuming that a shape table is already loaded into memory (see
Section 6.3.1.5), the following program draws the first shape in the table at
column 50, row 100:
1 0 HGR Displays high-resolution graphics.
20 HCOLOR• 3 Sets color to white 1.
30 ROT• 0 Orients shape as originally defined.
40 SCALE • 5 Enlarges shape five times.
5 0 DRAW 1 AT 5 0 , 1 0 0 Draws shape 1 at column 50,
row 100.
If you omit the keyword AT and the screen coordinates 50 DRAW 1,
Applesoft puts the shape on the screen starting at the last point plotted by
the most recently executed HPLOT, DRAW, or XDRAW statement. (The
shape drawn on the screen may not actually begin at the last point
previously plotted. If the first plotting vector in the shape doesn't actually
plot a point, there is an offset between the first visible point in the shape
and the last point plotted.) If no such statement has been executed, the
results are unpredictable.

152 Chapter 6: Graphics


If the shape number specified is less than O or greater than the actual
number of shapes in the shape table, the program halts with the message
? I L L E G A L Q U A N T I TY E R R O R .

•Warning If you execute DRAW without first loading a shape table into memory,
the system may hang (use I CONTROL H RESET I to recover), or Applesoft
may draw random shapes anywhere in the high-resolution graphics area
of memory (locations 8192 to 24575 decimal), whether or not HGR or
HGR2 has previously been executed. This can have disastrous
consequences if your program is longer than about 6000 bytes.

6.3.2.2 The XDRAW Statement


XDRAW 5
XDRAW 1 AT 1 4 8 , 88
X D R A W S H A P E A T X C E HT E R + XOFFSET , VCEHTER
+ VOFFSET

The XDRAW statement works exactly the same as DRAW, except that the
color used to draw the shape is the complement of the color already existing
at each point plotted. The following pairs of colors are complements:
□ black and white
□ violet and green
□ blue and orange
XDRAW is most commonly used to erase a previously drawn shape. The
following program, which assumes that a shape table has already been
loaded into memory (see Section 6.3.1.5), illustrates the point by drawing
and then erasing the same shape, leaving the screen blank:
1 8 HGR2 Displays full-screen high-resolution
graphics.
2 8 HCOLOR• 3 Sets color to white 1.
3 8 ROT• 8 Orients shape as originally defined.
4 8 SCALE • 5 Enlarges shape five times.
5 8 DRAW 1 A T 5 8 , 1 8 8 Draws shape at column 50, row 100.
68 FOR 2 • 1 TO 5 8 8 : HEXT 2
Stalls for a short time.
78 X D R A W 1 AT 5 8 , 1 8 8 Erases the shape.

6.3 Shape Tables 153


Animation With DRA W and XDRA W.· If you use DRAW and XDRAW
alternately in a loop, you can do animation:
10 HGR2 Displays full-screen
high-resolution graphics.
20 HCOLOR• 3 Sets color to white 1.
30 ROT• 0 Orients shape as originally
defined.
◄0 scALE• 5 Enlarges shape five times.
50 F O R X • 1 TO 2 0 0 Loops 200 times.
s0 D R A W 1 AT 5 0 + x , 1 0 0 Draws shape in a different
column each time.
70 XDRAW 1 AT 5 0 + X, 100 Erases shape.
80 I'! E X T X Repeats loop.
If the shape number specified is less than O or greater than the actual
number of shapes in the shape table, the program halts with the message
? I L L E G A L Q U A N T I TY E R R O R .
•Warning I f you execute XDRAW without first loading a shape table into memory,
the system may hang ( use I CONTROL H RESET I to recover), or Applesoft
may draw random shapes anywhere in the high-resolution graphics area
of memory (locations 8192 to 24575 decimal), whether or not HGR or
HGR2 has previously been executed. This can have disastrous
consequences if your program is longer than about 6000 bytes.

6.3.2.3 The SCALE = Statement


SC A L E • 1 0
SCALE • Z / 4
The SCALE= statement sets the scale factor (relative size) for the
high-resolution graphics shape to be drawn by DRAW or XDRA W. The
expression following the keyword SCALE= specifies the scale factor, which
can range from 1 (reproduces the shape exactly as originally defined) up to
a maximum of 255 (draws the shape 255 times the size originally defined).

154 Chapter 6: Graphics


Assuming that a shape table is already loaded into memory (see
Section 6,3.1.5), the following program draws the first shape in the table at
three different positions on the screen and in three different sizes:
10 HGR 2 Displays full-screen high-resolution
graphics.
2 1! HCOLOR• 3 Sets color to white 1.
3 1! ROT• " Orients shape as defined.
40 SCALE• 1 Uses original size.
S il D R A W 1 AT 1 0 0 , 1 0 0 Draws shape at column lOO,
row 100.
6 1! s cALE • 2 Scales to twice original size.
1 0 D R A W 1 AT 1 s 0 , 1 0 0 Draws at column 150, row 100.
00 SCALE• 3 Scales to three times size.
9 1! DRAW 1 AT 20 0 , 1 0 0 Draws at column 200, row 100.
A scale setting of O is considered equivalent to the maximum setting (255).
If the scale setting specified is less than O or greater than 255, the program
halts with the message '? I L L E G A L Q U A H T I TY E R R O R .
Scale factors are useful only up to a certain point. Large scale settings
produce some rather outlandish results on the screen.
SCALE Isn't a Variable: Notice that the equal sign is part of the
keyword SCALE=; it doesn't represent an assignment to a variable
named SCALE. A statement such as
LET S C A L E • X
has no effect on the scale setting. The only way to find out the current
scale setting is to keep track of it yourself with a separate variable.

6.3.2.4 The ROT = Statement


ROT• 1 6
ROT• 3 2 + 2 * R

The ROT= (for rotation) statement sets the angular rotation for the
high-resolution graphics shape to be drawn by DRAW or XDRAW. The
expression following the keyword ROT= specifies the rotation in units of
5.625 degrees (1/64 of a circle). ROT= 0 orients the shape exactly as
defined in the shape table, ROT= 16 rotates the shape 90 degrees clockwise,
ROT= 32 rotates it 180 degrees, and so on. The process repeats starting at
ROT= 64.

6.3 Shape Tables 155


Assuming that a shape table is already loaded into memory (see
Section 6.3.1.5), the following program draws the first shape in the table,
five times its original size, at two different positions on the screen, once
oriented as originally defined and once rotated by 45 degrees:
1 Ill HGR2 Displays full-screen high-resolution
graphics.
2 fll H C O L O R • 3 Sets color to white 1.
3fll S C AL E • 5 Scales shape to five times original
size.
4 fll R O T • Ill Orients shape as originally defined.
S Iil D R A W 1 A T 1 5 Ill , 1 Ill Ill Draws shape at column 50, row 100.
G Iil R O T • 8 Rotates shape 45 degrees.
7 8 D R A W 1 A T 1 B fll , 1 8 B Draws shape at column 100,
row 100.
The amount of rotation obtainable is somewhat dependent on the current
scale setting. For SCALE= 1, Applesoft recognizes only four rotation
values (0, 16, 32, 48); for SCALE= 2, it recognizes eight rotation values (0, 8,
16, ... ); for SCALE= 3, it recognizes twelve rotation values; and so on. For
scale settings of 16 or more, the full range of rotation values is available. For
unrecognized rotation values, Applesoft usually orients the shape with the
next smaller rotation that it recognizes.
ROT Isn't a Variable: Notice that the equal sign is part of the keyword
ROT=; it doesn't represent an assignment to a variable named ROT. A
statement such as
LET ROT • X
causes a syntax error. The only way to find out the current rotation
setting is to keep track of it yourself with a separate variable.
If the rotation setting specified is less than O or greater than 255, the
program halts with the message ? I L L E G A L Q U A N T I TY E R R O R .

6.3.2.5 The SHLOAD Statement


SHLOAD
11, 11 Plus, lie The SHLOAD (for shape load) statement loads a shape table from a tape
cassette. The shape table is loaded just below the upper limit of available
program and variable space (HIMEM:); HIMEM: is then set to just below
the shape table to ,:>rotect it.

156 Chapter 6: Graphics


To use SHLOAD in immediate execution, turn on your tape recorder with
the proper tape inserted and cued up to the proper place. Then type
SHLDAD
and press I RETUR N 1. You should hear one beep when the shape table's
length has been read successfully, and another when the table itself has
been read.
You can also use SHLOAD from within a program (with appropriate
prompting messages) to allow users to load their own shape tables:
1 BB P R I N T " C U E UP Y O U R S H A P E T A P E A N D P R E S S T H E
P L A Y BUTTON . "
1 1B P R I N T " T H E N P R E S S T H E R E T U R N K E Y TD L O A D T H E
SHAPE TABLE . " Prompts user with instructions.
1 2B G E T ST A L L $ Waits for keypress.
1 3B SHLDAD Loads shape table from tape.
14B P R I NT "TABLE L D ADED- - P L E A S E SHUT O F F YOUR
R E C O RD E R . " Tells user table is loaded.
lf you load a second shape table replacing the first one, you or your program
should reset HIMEM: to avoid wasting memory. See Section 6.3.1.5 for more
information on shape tables and memory usage.
More Ways to Hang Your System: If you try to use SHLOAD without a
tape recorder connected, turned on, and set to play, the system hangs
indefinitely. Use I CONTROL H RESET I to regain control.
If a variable name begins with the reserved word SHLOAD, as in
SHLOADER = 59, SHLOAD may be executed before a syntax error is
detected. In such a case, the system patiently waits (forever, if necessary)
for a shape table to be loaded from a tape cassette. Again, use
I CONTROL H RESET I to recover.
For More Information: For information on saving a shape table on
tape, see Section 6.3. 1.6. See Appendix M for a list of all statements
dealing with tape cassettes.

6.3 Shape Tables 157


6.4 Graphics in Text Mode (MouseText)

It is possible to put graphics on the screen without first using GR or HGR.


You must have either an Apple Ile, or an enhanced Apple Ile with an
80-column card.
If you have the required equipment, try entering this program, which
displays 32 uppercase characters in inverse mode:
18 DS •CHR S C 4 >
2B P R I HT D S ; " P R # 3 R E M Tu r n o n B B - c o l umn v i d e o
3B P R I HT
4B I HVERSE
SB P R I H T " A B C D E F G H I J K LM H O P QRSTUVW X YZ C I L \ "
6B H O RM A L
7B EHD
Run the program and observe the screen. Then, add two new lines:
45 P R I HT C H R $ C 2 7 )
55 P R I HT C H R S C 2 4 )
Line 45 turns on MouseText, a set of graphics that you can use in your
programs. Line 55 turns it off. These characters are an alternate
representation of certain inverse uppercase characters. They can be used
both in 40-column and 80-column displays.
Note that some of the MouseText characters are meant to be used in
tandem-for example, the ones represented by F and G in your program
listing produce a running figure. Another pair, x and y, produces a file
folder.

158 Chapter 6: Graphics


•0
Figure 6-11. MouseText Characters

X d m
"'

-

A B C D E F G

..
+l I

� ••• 1' �

- L ➔u
J K L M N 0

+t
-- � II
a
- ., ...
s w

-
R T V

C ::a
X y z
I ♦ \
I .I L

A

6.4 Graphics in Text Mode (MouseText) 159


Chapter 7 Utility Statements



• 0�
�'(
..






161
The features covered in this chapter are concerned with low-level control of
the programming environment.
□ Section 7.1, "System Utilities," discusses facilities for direct access to
specific locations in the computer's memory from within an Applesoft
program.
□ Section 7 .2, "Memory Management," describes the ways in which
Applesoft programs can control the limits of program space.
□ Section 7 .3, "Debugging," tells how to trace the execution of a running
program for debugging purposes.

7. 1 System Utilities

This section describes statements and functions that give Applesoft


programs direct access to the Apple II's memory:
□ PEEK (see Section 7.1.1) examines the contents of a memory location.
□ POKE (see Section 7.1.2) alters the contents of a memory location.
□ CALL (see Section 7.1.3) and USR (see Section 7.1.4) allow Applesoft
programs to execute machine-language subroutines stored in the
computer's memory.
□ WAIT (see Section 7.1.5) suspends program execution until a specified
signal is received from a peripheral device.

7. 1 . 1 The PEEK Function


The PEEK function directly examines the contents of a specified location in
memory. The argument given to PEEK is the decimal address of the desired
memory location. PEEK yields the contents of the specified location, which
will be an integer from O to 255. For example, the following program
displays the contents of addresses 100 through 120:
1 8 F O R A DDR • 1 1! 11 Til 1 2 B Loops through desired addresses.
2B P R I NT " L O C A T I O N " ; ADDR ; " H OLDS THE V A L U E " ;
P E E K < ADDR > Displays contents of location.
3B N E X T ADDR Goes back for next address.
Certain locations in the memory of the Apple II hold special system
information or produce special effects whenever their contents are read.
One important use of PEEK is manipulating these special locations. See
Appendix F for details.

162 Chapter 7: Utility Statements


The following program yields the borders of the current text window:
18 HOME
28 P R I NT "THE C U R R E NT TEXT W I NDOW'' : P R I NT
38 P R I NT " - BEG I N S AT C O LUMN " P E E K ( 3 2 )
48 P R I NT " A N D I S " P E E K ( 33 ) " C O L UMNS W I DE . " : PR I NT
58 P R I NT " - I TS TOP EDGE I S ROW " P E E K ( 3 4 >
68 P R I NT " A H D I TS BOTTOM I S R OW " P E E K ( 3 5 )
If PEEK is given a negative argument value, it adds 65536 (2 to the 16th
power) to obtain an equivalent positive address. For example,
This Is Equivalent To
PEEK ( - 1 6384 ) PEEK ( 49 1 52 >
PEEK C-1> PEEK (65535)
PEEK < - 3 2 768 ) PEEK ( 3 2 7 68 )
PEEK < -6558 8 > PEEK ( 36 )
If the argument is not in the range -65535 to +65535, the program halts with
the message ? I L L E G A L Q U A N T I T Y E R R O R .

7. 1 .2 The POKE Statement


P O K E 34 , 8
P O K E - 1 63 8 2 , 8
P O K E ADDR , < 2 * D 1 + 3*D2 > / ( U - V)
The POKE statement stores a specified value into a location in the
computer's random-access memory. The first expression following the
keyword POKE gives the decimal address of the memory location; the
second expression, separated from the first by a comma, gives the value to
be stored in that location. For example,
POKE 34 , 8
stores value 8 in location 34.

�Warning Be certain that the address in which you are storing doesn't contain part
of your program or some vital system information that you don't want to
change. An ill-advised POKE can hang the system, drop you into the
Monitor, or alter the operation of the system or of your program in
unpredictable and possibly disastrous ways. In the event of catastrophe,
use I CONTROL H R ESET I to regain control of the system. See Appendix H
for the locations of vital system pointers that shouldn't be tampered with.

7.1 System Utilities 163


Certain locations in the memory of the Apple II hold special system
information or produce special effects whenever a value is stored in them.
One important use of POKE is manipulating these special locations. For
example, POKEs to memory locations 32 through 35 are used to set the
borders of text windows. See Appendix F for details.
If POKE is given a negative target address, it adds 65536 (2 to the
16th power) to obtain an equivalent positive address. For example,
This ls Equivalent To
P O K E - 1 6384 , 0 P O K E 49 1 5 2 , 0
P O K E - 3 2 7 68 , 1 1 2 P O K E 3 2 768 , 1 1 2
POKE -655 0 2 , 8 POKE 34 , 8
If the target address is not in the range -65535 to +65535, or if the specified
value is not in the range O to 255, the program halts with the message
? I L L E G A L Q U A N T I TY E R R O R.

7 . 1 .3 The CALL Statement

CALL 5 49 1 5
C A L L - 936
C A L L R O UT I N E C J )
The CALL statement executes a machine-language subroutine from within
an Applesoft program. The decimal address of the desired subroutine
follows the keyword CALL. Control is transferred to the subroutine at the
designated address; when the subroutine is finished, execution continues
with the statement following the CALL. For example,
C A L L 6 4 668
executes the machine-language subroutine beginning at address 64668.
A Warning Make sure the address you give in the CALL statement is the beginning of
a valid machine-language subroutine! A misdirected CALL can have
unpredictable and probably unpleasant consequences, such as hanging
the system or dropping you into the Monitor. If this happens to you, use
I CONTROL H RESET I to regain control of the system.
The Apple II's built-in firmware contains a number of useful subroutines
accessible with the CALL statement. See Appendix F for details.

164 Chapter 7: Utility Statements


You can also use CALL to execute machine-language subroutines of your
own, which you have stored in memory with the POKE statement (see
Section 7.1.2), typed from the keyboard via the Monitor, or loaded into the
computer from a disk or tape.
If CALL is given a negative target address, it adds 65536 (2 to the 16th
power) to obtain an equivalent positive address. For example,
This Is Equivalent To
CALL -936 CALL 64 6 0 0
C A L L - 868 C A L L 6 4 668
C A L L - 1 998 CALL 63538
If the target address is not in the range -65535 to +65535, the program halts
with the message ? I L L E G A L Q U A IH I TV E R R O R .

7 . 1 .4 The USR Function

The USR (for user-supplied routine) function executes a machine-language


function routine stored in the computer's memory by you, the user. Such a
routine typically perforrns some high-speed computation that cannot be
done efficiently, or cannot be expressed at all, in Applesoft. The argument
supplied to the USR function is passed unchanged to the machine-language
routine, and the result yielded by the routine is passed back as the value of
the USR call.
Notfor Everyone: This feature is intended for expert programmers
only, and requires a knowledge of machine-language programming.
Readers with fewer than sixteen fingers are advised to skip this section.
The function routine to be executed with USR can be stored in the
computer's memory with the POKE statement, typed from the keyboard via
the Monitor, or loaded into the computer from a disk or tape. When USR is
called, the value supplied as an argument is placed in the floating-point
accumulator in the computer's memory (hexadecimal locations $9D
to $A3); control is then transferred via a machine-language JSR Gump to
subroutine) instruction to hexadecimal address $QA (decimal 10).
Locations $QA to $QC (decimal 10 to 12) must contain a machine-language
JMP (jump) instruction to the beginning of the machine-language routine.
The routine should leave its result in the floating-point accumulator and
return control to Applesoft with an RTS (return from subroutine)
instruction. The contents of the floating-point accumulator are then passed
back to your Applesoft program as the value yielded by USR.

7.1 System Utilities 165


Here is a trivial example showing the use of the USR function. The
machine-language routine shown here simply takes the argument value it
receives and multiplies it by 8:
l CALL - 1 5 1 Leaves Applesoft; enters Monitor.
" 8A : 4C B B 83 Sets up machine-language jump to
hexadecimal address $300.
" 8 3 8 8 : 1 8 AS 9D 69 8 3 85 9D 6 8
Enters short machine-language
routine to multiply contents of

·�
l P R I NT U S R ( 3 )
floating-point accumulator by 8.
Returns to Applesoft.
Executes routine with argument
value 3.
2◄ Result displayed on screen.
At hexadecimal address $0A, there is a JMP (opdcode 4C) to hexadecimal
address $300. (As usual in 6502 machine language, the low-order byte of the
address, 00, precedes the high-order byte, 03.) Beginning at address $300 is
a machine-language routine to multiply the value in the floating-point
accumulator by 8. Back in Applesoft, when the function call USR (3) is
executed, the argument value 3 is placed in the floating-point accumulator
and control is passed to the machine-language routine via the JMP at
location $0A. The machine-language routine gets the value in the
floating-point accumulator, multiplies it by 8, puts the result (24) back into
the floating-point accumulator, and returns control to Applesoft with an
RTS instruction (opcode 60). The value 24 is then passed back as the result
of the USR call.
To obtain a two-byte integer from the value in the floating-point
accumulator, your machine-language routine should do a JSR to
address $E01C. Upon return, the integer value is in locations $AO
(high-order byte) and $Al (low-order byte).
To convert an integer result to its floating-point equivalent, so that the
function can return that value, place the two-byte integer in registers A
(high-order byte) and Y (low-order byte). Then do a JSR to address $E2F2.
Upon return, the floating-point value is in the floating-point accumulator.

7 . 1 .5 The WAIT Statement


WA I T 4 9 3 4 7 , 1 5
WA I T 4948 1 , 2 4 8 , 1 92
WA I T ADDR X , M 1 X , M 2 X

166 Chapter 7 : Utility Statements


For Experts Only: This feature is intended for expert programmers
only, and requires an understanding of bit-masking operations. If you
mask: a pattern of bits for use in bit-level think a mask is something you wear on Halloween, you can safely afford
logical operations to skip this section. You won't miss a thing.
The WAIT statement suspends program execution until a specified bit
pattern appears at a specified memory location. It is typically used to cause
a program to pause until a status signal is received from a peripheral device.
For example, a printer running out of paper might cause a program to WAIT
until it receives a signal from the printer that it has paper.
The first expression following the keyword WAIT designates the address of
the memory location to be tested. The second expression represents a
one-byte mask specifying which bits of the designated location are of
interest: a 1 bit in the mask means that the corresponding bit of the memory
location is to be tested; a 0 bit means it is to be ignored. The optional third
expression is another one-byte mask specifying the bit value to be tested for
in each position of the memory location: a 1 bit in the mask tests for a 0 bit
in the corresponding position of the memory location, and vice-versa (!). If
the second mask is omitted, all bit positions specified by the first mask are
tested for a 1 bit. For example,
WA I T ADDR , 2 5 5 Waits for a 1 bit anywhere in
location ADDR.
WA I T ADDR , 2 5 5 , 2 5 5 Waits for a O bit anywhere in
location ADDR.
WA I T ADDR , 1 Waits for low-order bit of location
ADDR to become 1.
WA I T ADDR , 1 2 8 , 1 2 8 Waits for high-order bit of location
ADDR to become 0.
WA I T ADDR , 3 , 2 Waits for low-order bit of location
ADDR to become 1 or second
low-order bit to become 0.
When WAIT is executed, the contents of the location specified by the first
expression are exclusive-ORed with the mask represented by the third
expression (if any); the result is then ANDed with the mask represented by
the second expression. If the result is nonzero (that is, if any of the bits of
interest are in the specified state), then program execution proceeds; if the
result is 0 (none of the bits of interest are in the specified state), then the
test is repeated. Thus program execution is suspended until one of the
specified bits is set to the specified state by an outside agency (presumably
a signal from a peripheral device).

7. 1 System Utilities 167


.A.Warning If the specified bit pattern never appears, program execution hangs
forever. Make sure that the memory location you're testing is receiving
information that will eventually test true. The only way to interrupt a
WAI T is with I CONTROL H RESET I-
If WAIT is given a negative target address, it adds 65536 (2 to the 16th
power) to obrain an equivalent positive address. For example,
This Is Equivalent To
W A I T - 1 6 1 89 , 1 5 W A I T 4 93 4 7 , 1 5
If the target address is not in the range -65535 to +65535, or if either of the
masks is not in the range O to 255, the program halts with the message
? I L L E G A L Q U A N T I TY E R R O R .

7.2 Memory Management


The features discussed in this section are used to control the way Applesoft
allocates memory space for your program:
□ The HIMEM: statement (see Section 7.2.1) sets the upper limit of
available program memory.
□ The LOMEM: statement (see Section 7.2.2) sets the lower limit of
available program memory.
□ The FRE function (see Section 7.2.3) determines the amount of
remaining memory space available to the program.

7 .2. 1 The HIMEM: Statement


H I ME M : 8 1 92
The HIMEM: statement sets the highest memory address available to an
Applesoft program for storage of program lines and variables. The upper
limit of available program memory is set to the value of the expression
following the keyword HIMEM:. The area above this address is available for
use by the disk operating system, high-resolution graphics, or
machine-language programs.
Notice that the colon is part of the keyword HIMEM: and is required.

168 Chapter 7: Utility Statements


Applesoft automatically sets HIMEM: to the address of the highest writable
memory (RAM) address available on your computer. On systems equipped
with disk drives, loading the disk operating system automatically resets
HIMEM: to a lower value in order to protect the area of memory occupied by
the disk operating system itself. See your disk operating system manual for
further inforrnation.
You can change the setting of HIMEM: only by
□ executing the HIMEM: statement
□ typing � to the Monitor program
□ restarting the system
□ loading a machine-language program.
.AWarning Resetting HIMEM: above its current value is an extremely dangerous
practice that can result in writing over the disk operating system or other
vital system information. Wise programmers carefully investigate
reserved memory areas before writing to them.
A common use of HIMEM: is protecting your program and high-resolution
graphics from overwriting each other. See Section 6.2.5 for details.
Helpful Hintfor Disk Operating System Users: The current value of
HIMEM: is stored in decimal memory locations 115 and 116; to obtain that
value, use the expression
P E E K ( 1 1 6 ) * 256 + P E E K ( 1 1 5 )
If HIMEM: is given a negative address, it adds 65536 (2 to the 16th power) to
obtain an equivalent positive address. For example,
This Is Equivalent To
H I MEM : - 5 7 3 4 4 H I MEM : 8 1 92
If the specified address is not in the range -65535 to +65535, the program
halts with the message ? I L L E G A L Q U A HT I TY E R R O R .
If the specified address is lower than the current setting of WMEM:, or
doesn't allow enough room for the program already in memory, the program
halts with the message ? O U T O F M E M O R Y E R R O R .

7.2 Memory Management 169


7 .2.2 The LOMEM: Statement

L O M E M : 2 4 5 76
The LOMEM: statement sets the lowest memory address available to an
Applesoft program for storage of variables. The lower limit of available
program memory is set to the value of the expression following the keyword
LOMEM:. The area below this address is available for high-resolution
graphics or machine-language programs. LOMEM: also resets all variables to
their initial values and wipes out all functions defined with DEF FN (see
Section 2.4.3).
Notice that the colon is part of the keyword LOMEM: and is required.
Applesoft ordinarily begins to store variables at the end of the program in
memory. Each time you add, delete, or change a program line, Applesoft
resets LOMEM: to a location just above the final line of the program.
Executing the NEW command (see Section 1.2.1) or typing �
to the Monitor resets LOMEM: to its initial value.
The value of LOMEM: can only be increased from its current setting. An
attempt to set LOMEM: to a lower value than the one already in effect halts
the program with the message ? O UT O F M E M O R Y E R R O R .
�Warning Changing LOMEM: during the course of a program is a most dangerous
practice that can cause portions of the program or of Applesoft's internal
control information to become unavailable, which in tum causes the
program to act in outlandish ways (if at all).
Helpful Hint: The current value of LOMEM: is stored in decimal
memory locations 105 and 106; to obtain that value, use the expression
PEEK C 1 06) * 256 + P E E K ( 1 0 5 )
If LOMEM: is given a negative address, it adds 65536 (2 to the 16th power)
to obtain an equivalent positive address. For example,
This Is Equivalent To
L OM E M : - 4 9 1 5 2 L O M E M : 1 6384
If the specified address is not in the range -65535 to +65535, the program
halts with the message ? I L L E G A L Q U A N T I TV E R R O R .
If the specified address is higher than the current setting of HIMEM:, or
lower than the address of the highest memory location occupied by the
current operating system (plus any currently stored program), the program
halts with the message ? O U T O F M E M O R Y E R R O R .

170 Chapter 7 : Utility Statements


7 .2.3 The FRE Function

The FRE function yields the number of bytes of unused writable (RAM)
memory available to the running program. For example,
L E T AVA I L • F R E C B )
sets AVAIL to the amount of available memory remaining.
Notice that the name of the function is FRE, not FREE.
FRE requires an argument in parentheses. The argument given to FRE is
ignored, and has no effect on the operation of the function. However, you
can't leave it out-you must include an argument expression of some kind
to "keep the parentheses apart." What you use for an argument expression
doesn't matter, but if Applesoft can't evaluate it as a legal expression, you
get an error halt.
If the number of free bytes exceeds 32767, FRE yields a negative result;
adding 65536 gives you the actual number of free bytes:
I F F R E C B > < B T H E N A VA I L • F R E C B > + 6 5 5 3 6
If you have set HIMEM: beyond the highest RAM address in your Apple II,
FRE may yield a value higher than the computer's actual memory capacity.
The reliability of such a value is to be taken lightly.
How Applesoft Manages Free Space: The amount of free space
reported by FRE is the number of bytes remaining below the string
storage space and above the numeric array and string pointer array space
(see Section H.2). When Applesoft changes the contents of a string
variable during the course of a program (say from "CAT" to "DOG"), the
characters in the old string ("CAT") are not erased from memory;
Applesoft simply allocates some fresh space to hold the new string
("DOG"). As a result, characters left over from unused strings take up
"dead space" and slowly fill memory from HIMEM: down to the top of the
array space.
Applesoft automatically clears out these leftover characters when the
bottom of string space "collides" with the top of array space. But if you're
using any of the free space for machine-language programs or for
high-resolution graphics, they may be overwritten.

7.2 Memory Management 171


Light Housecleaning: The automatic "housecleaning" just described
takes time (anywhere from a fraction of a second to over two minutes,
depending on the number of string variables your program is using).
Furthermore, such housecleaning occurs at unpredictable moments­
whenever your string and array spaces happen to collide. If it happens
while Applesoft is in the middle of displaying a message on the screen, for
instance, it can cause unfortunate confusion for your program's user, who
is left waiting for the computer to finish displaying a half-delivered
message.
The FRE function provides a tool for warning the user that the computer
will be busy for a while. The address of the current beginning of string
space is kept in locations 111 and 112 of the computer's memory; the end
of array space is kept in locations 109 and 110. Whenever Applesoft needs
to allocate more memory, it compares the contents of these locations; if
they differ by less than 1, Applesoft does its automatic housecleaning.
Since Applesoft checks these locations, so can you. When the difference
between them starts getting close to 0, it's time to display some kind of
"don't worry" message and force housecleaning. Using a statement of the
form
I F C P E E K C 1 1 2 ) * 2 56 + P E E K C 1 1 1 ) ) -
C P E E K C 1 1 0 ) * 256 + P E E K C 1 09) ) > 2
T H E N P R I NT " P L E A S E S T A N D BY . . . "
: Q • FRE C 0 >

periodically within your program forces housecleaning to occur and


prevents such confusion.
Since the housecleaning can take as long as several minutes each time it
occurs, don't do it too often. It's best to use FRE (0) when you need a
pause anyway-such as after you write information onto a disk, or while
the user is reading information on the display screen.

7 .3 Debugging Facilities
This section details two Applesoft commands used as debugging aids:
TRACE and NOTRACE. They're useful when a program isn't behaving as
intended and you need to find out why.

172 Chapter 7: Utility Statements


7 .3.1· The TRACE Command

TRACE
TRACE causes Applesoft to display the line number o f each statement it
executes. Each line number displayed is preceded on the screen by a
number sign (#). For example, the program
1 111 TRACE
2 1! I • I + 1 I • I + 1
3 1! J • J + 1 J • J + 1
4 1! GOTO 2 1!
displays the output
# 2 1! # 2 1! # 3 1! # 3 1! # 4 1! # 2 1! # 2 1! # 3 1! # 3 1! # 4 1!
# 2 1! # 2 1! # 3 1! # 3 1! # 4 1! # 2 1! # 2 1! # 3 1! # 3 1! # 4 1!
# 2 1! #20 # 3 1! # 3 1! # 4 1! # 2 1! # 2 1! # 3 1! # 3 1! # 4 1!
# 2 1! # 2 1! # 3 1! # 3 1! # 4 1! # 2 1! # 2 1! # 3 1! # 3 1! # 4 1!
# 2 1! # 2 1! # 3 1! # 3 1! # 4 1! # 2 1! # 2 1! # 3 1! # 3 1! # 4 1!

until you press �-


As the example shows, TRACE can be used from within a program as well
as in immediate execution. A more realistic use in debugging would be to
test for some error condition and turn on tracing only if the error condition
holds:
I F X > Y THEN TRACE
Be sure to remove the TRACE statements from your program after you've
found and exterminated the bug!
Tracing and Display Formatting: When the program being traced
contains display-formatting statements-VTAB, HTAB, TAB,
semicolons, commas (see Section 5.2.4)-line numbers displayed by
TRACE may appear in a confused fashion or may be overwritten entirely.
Once tracing has been started, it can be canceled only by
□ executing the NOTRACE statement
□ restarting the system
□ typing � to the Monitor program.

7.3 Debugging Facilities 173


7.3.2 The NOTRACE Command
NOTRACE
The NOTRACE command cancels the effects of TRACE. After this
command is executed, line numbers are no longer displayed on the screen
as Applesoft executes them.

174 Chapter 7: Utility Statements


Chapter 8 Programming: Bringing It All Together

175
Good programs don't just happen. Programs that are efficient, economical,
and easy to debug and to modify are the result of careful planning. This
chapter presents a method to facilitate such planning, using as its example
a program to calculate postage fees for United States mail. A copy of this
program is included on the ProDOS BASIC Programming Examples disk;
a complete listing can be found in Appendix N.
□ Section 8.1, "Planning the Program," shows how to develop a list of
program specifications and how to convert the list into a kind of program
outline.
□ Section 8.2, "Writing the Code," shows how to refine the outline
developed in Section 8.1 into a final Applesoft program.

8.1 Planning the Program

Although you can afford to be "quick and dirty" for casual or one-time-only
applications, you'll need to do some preliminary planning for more serious
ones. In general, the more planning you do the more efficient and bug-free
your finished program will be.
To demonstrate some of the principles of program planning, this chapter
develops a program to calculate postage rates on certain classes of mail sent
in the United States.

8.1 . 1 Program Specification


Program planning begins with deciding what your program is to do or what
problem you want it to solve. You might want to design a space-war game, a
tax planner, or a data base management system. It doesn't matter how
simple or how complex the task-whatever it is, you have to decide in
detail what the program is supposed to do.
To make writing the program easier, it's a good idea to begin with a list of
program specifications. This list specifies what information the program
need&, what the program should and should not do, how the results are to be
presented, and so forth.

8 . 1 . 1 . 1 What the Program Needs


It's fairly simple to determine what information a postage rates program
needs. Since the goal is to determine how much it costs to mail an item, and
since cost is a function of mail class and weight, the program needs

176 Chapter 8: Programming: Bringing It All Together


someone or something to tell it what weight item is being mailed in what
class. To keep things simple, the program gets this information from the
program user:
□ The user tells the program the class of mail.
□ The user also tells the program the weight of the item, since postage
rates are based both on class and weight.
When the program has the weight and class of mail (for instance, three
ounces of first class), it needs to determine the postage based on some scale.
It must either calculate the postage with a formula or look up the rate in a
table stored in the computer's memory. Since all computers are inherently
stupid and must be told everything, you have to include formulas or tables
with which your computer can work:
□ The program includes formulas and/or tables of postage rates for various
weights and classes of mail.
□ The program includes information on the maximum allowable weight.
This last specification is a matter of postal regulations; first class mail above
12 ounces is called priority mail and is charged at a different rate; 70 pounds
is the maximum weight for priority mail; and so forth. Program planning,
then, calls for information often outside the programmer's immediate
purview. That's why God created libraries and telephones-so that
programmers can obtain information they don't already have.

8.1 . 1 .2 What the Program Will and Won't Do


Deciding on the limits of a program is often as important as determining
what the program is supposed to accomplish. United States mail has four
classes, several types within certain classes, optional extras like insurance
and various forms of registry, and so forth. To make designing and writing
the program simpler, we'll assume that our postage is never below first
class, and further that we never insure or register mail (what fools these
mortals...). We'll also assume that packages sent by overnight delivery
(express mail) never weigh more than nine pounds and always travel in the
same postal zone:
□ The program is limited to express, first class, and priority mail (one zone
only).
□ The heaviest express mail package is nine pounds; first class and priority
mail can be of any weight, up to Post Office limits.
I By the Way: There is no guarantee that this program agrees with
current postal regulations!

8.1 Planning the Program 177


8.1 . 1 .3 Validating the Data
Now that the program has information both from the user and from its own
internal resources (charts of rates and so on), it must check the validity and
consistency of the information.
First for validity: Does the information the user typed make sense in terms
of what the program expected? If the program needs a digit for the weight of
a letter, what should it do if it gets a word? In designing any program, it's
important to remember:
□ Most humans do not possess genetic information about what to type into
computers.
□ Most humans make mistakes.
The program, then, must display clear instructions telling the user what to
enter (kind of information needed) and what form to use (letters, digits,
words):
□ The program displays a list of classes of mail on the screen, with
instructions for the user about what to type.
□ After it gets the class of mail, the program solicits the weight from the
user with proper instructions.
□ There is a mechanism for accepting valid information and rejecting
invalid information (that is, there are error-handling provisions).
Naturally, if the program rejects invalid information, it must try again to get
valid information from the user:
□ If information is rejected as invalid, the program continues to solicit
information until it gets what it needs.
Now to consistency: Although a user might plausibly ask the cost of sending
a five-pound package via first class mail, only the program knows (by
checking its table of limits) that five pounds is too heavy for first class. It
must notify the user that some other action is called for:
□ If information is rejected as inconsistent, the program notifies the user
with appropriate recommendations for further action.

178 Chapter 8: Programming: Bringing It All Together


8.1 . 1 .4 Displaying the Results
The specifications must also include the form in which the results are to be
given to the user. In this case we'll keep it simple:
□ The final calculated postage charge is displayed on the display screen
with appropriate labeling.
Finally, the specifications must tell what the program does when its job is
completed. Here, it repeats the whole process until the user types in some
kind of "I'm done" signal:
□ The program continues to solicit information to calculate new postage
charges until the user enters an "end" signal.

8.1 . 1 .5 Final Specifications


Reordering the list of specifications ihto a more logical form, we obtain this
final list:
□ The program displays a list of classes of mail on the screen, with
instructions for the user about what to type.
□ The program is limited to express, first class, and priority mail (one zone
only).
□ The user tells the program the class of mail.
□ After it gets the class of mail, the program solicits the weight from the
user with proper instructions.
□ The user tells the program the weight of the item.
□ The program includes information on the maximum allowable weight.
□ The heaviest express mail package is nine pounds; first class and priority
mail can be of any weight, up to Post Office limits.
□ There is a mechanism for accepting valid information and rejecting
invalid information.
□ If information is rejected as invalid, the program continues to solicit
information until it gets what it needs.
□ If information is rejected as inconsistent, the program notifies the user
with appropriate recommendations for further action.
□ The program includes formulas and/or tables of postage rates for various
weights and classes of mail.
□ The final calculated postage charge is displayed on the screen with
appropriate labeling.
□ The program continues to solicit information to calculate new postage
charges until the user enters an "end" signal.

8.1 Planning the Program 179


Reviewing the list, you can see that the program's actions fall into a natural
chronological order:
1. Computer displays prompting messages.
2. User responds.
3. Program checks validity of responses.
4. If any information is invalid, program solicits new information.
5. Program checks consistency of responses.
6. If any information is inconsistent, program solicits clarified information.
7. Program processes validated information.
8. Program displays results and goes back to step 1.
You'll find that most interactive programs-programs that carry on a
"dialogue" with a human sitting at the computer-involve most of these
categories in roughly the same order.

8.1 .2 Program Layout

Before rushing to put fingers to keyboard, it's best to take your planning at
least one step further. Now is the time for program layout. Here you plan
the form for each section of the program as described in both the
specification list and the chronological order list.
The program layout technique presented here is called stepwise
refinement.-Jl,lhat this means is laying out broad sections of the program,
then going back and refining each section step by step.

8.1 .2. 1 The Initial Layout


Here is an initial layout of the Postage Rate program in the broadest terms:
Repeat
Display menu
Accept class
Accept weight
Compute charge
Display results
until done

180 Chapter 8: Programming: Bringing It All Together


The layout says that there are five general sections to the program
(Display menu, Accept class, Accept weight, Compute charge, and
Display results), and that the program is to repeat this sequence of steps
in order until somehow told to stop.
Each section can now be treated as an independent module, to be designed
and coded separately. The smaller the chunks of program you work with
and the more independent each chunk is, the less chance for error and the
easier the program is to debug.

8 . 1 .2.2 Refining the Layout


Now that we have the program laid out in skeletal form, we can begin to put
some flesh on the bones. Here is the first refinement, in which each of the
broad steps in the initial layout is spelled out in more detail:
Repeat
Display menu:
List choices
Accept class:
Instruct user how to choose
Repeat
Get postage class from user
until valid menu item
Accept weight:
Repeat
Instruct user how to type
Get weight from user
until consistent
Compute charge:
Calculate from formula or look up in table
Display result:
Format result with dollar sign, trailing zeros
Label and display result
Wait for signal from user before proceeding
until user signals end

8.1 Planning the Program 181


At this point, many programmers would take outline in hand and attack the
keyboard. But a couple of the modules need further refinement: both the
Accept weight and the Compute charge modules need to do specialired
processing depending on the class of mail specified by the user. The new
information in the Compute charge module comes from examining postage
rate charts. First class mail is fairly regular, so a formula can be used to
compute the charge. Express mail follows no regular pattern, so it's easier to
create a table of charges. Priority mail requires a combination of both
formula and table. The final program layout looks like this:
Repeat
Display menu:
List choices
Accept class:
Instruct user how to choose
Repeat
Get postage class from user
until valid menu item
Accept weight:
Repeat
Instruct user how to type
Get weight from user:
Check validity of response
Express?
If item more than 9 pounds
then suggest alternative
First class?
If item more than 12 ounces
then suggest alternative
Priority?
If item less than 12 ounces
then suggest alternative
If item more than 70 pounds
then suggest alternative
until valid and consistent

182 Chapter 8: Programming: Bringing It All Together


Compute charge:
Express?
Look up charge in table
First class?
Calculate chargefromformula
Priority?
If item less than 10 pounds
then look up charge in table
otherwise calculate charge from formula
Display result:
Format result with dollar sign, trailing zeros
Label and display result
Wait for signal from user before proceeding
until user signals end

8.2 Writing the Code


Now that you've refined the program layout to a sufficient level of detail,
you're finally ready to start writing code. The layout is only a guide; it isn't
the last word. As you write and test the actual program, you may find you
need to make changes in your original design. That's perfectly all right; use
the design to keep you on track.
What follows in this section represents one way to turn the outline into a
working program. It isn't the only way; a hundred programmers would
produce a hundred different programs for the same task. It does, however,
work. Because it's been developed in an orderly, methodical way, it's also
logically organized and easy for a person to follow. This is an important
consideration, because it makes the program easy to debug and easy to
modify. (Almost all serious programs need to be modified at some time or
other, often by someone other than the original programmer.)

I Note to Purists: Any resemblance between the following program and


true top-down structured code is purely coincidental.

8.2 Writing the Code 183


8.2. 1 Preliminaries

Your program should begin with a block of REM statements identifying the
program and describing what it does. Most programmers add their own
name and the date of the program's current version:
1 0 R E M P O STAGE R A T E S Name of program.
20 Colon leaves line empty.
3 0 R E M D E T E R M I N E S P O ST A G E F E E S
What program does.
4 0 R E M F O R E X P R E S S , 1 ST C L A S S ,
5 0 R E M A N D P R I O R I TY M A I L Empty line inserted by embedding
I CONTROL Kl] (line feed) at end of
REM statement in line 50.
6 0 R E M V 3 1 0 / 0 5 /83 Number and date of this version.
7 0 R E M B Y J O H N S C R I BBL E M O H G E R & S C OT K AM I H S
Programmers' credit line.

8.2.2 Display the Menu

Now you can refer to your outline and base your code directly on it. Notice
the REM statements introducing the different sections. All comments
shown in the second column could also be included as REM statements:
1 0 0 R E M M E N U O F P O STAGE C L A S S E S
j c o NTR oL Hl] here.
'""-=--,,=-=-,.....,

1 1 0 H OM E Begins with a clear screen.


1 2 0 T I TL E $ • " P O STAGE R A T E S "
1 3 0 P R I NT
1 4 0 H T A B 2 1 - L E H C T I TL E $ ) / 2
Formula to center title.
150 P R I N T T I TL E $
1 60 VTAB 6
170 P R I NT " 1 . E X P R E S S "
180 P R I NT " 2 . F I R S T C L A S S "
190 P R I N T " 3 . P R I O R I TY "
200 P R I NT
210 P R I NT " 4 . E N D THE P R OGRAM"
The escape hatch.

184 Chapter 8: Programming: Bringing It All Together


8.2.3 What's the Postage Class?

This section finds out what mail class the user wants. Note that
I CONTROL 1-Q], the line feed character, sets off the REM statements for
easier reading (line 300):
3 8'1 R E M I CONTROL 1-Q] here.
G E T C L A S S OF MA I L I CONTROL 1-QJ here.
3 1 0 VTAB 1 4
3 2 0 P R I N T " P r e !!l !!I t h e n u m b e r o f y o u r c h o i c e : ., ;
Semicolon keeps response on same
line.
330 GET C $ Only one keypress needed-cuts
down on error possibilities; note use
of string variable to get number­
avoids type mismatch errors.
335 REM I CONTROL f-Q] here.
V A R I □us C H E C K S Another j CONTROL f{I) (last time
this is noted).
340 I F C $ • "4" THEH EHD Ends program if user types a 4 .
350 I F VAL C C $ ) > 0 AHO VAL C C $ ) < 4
THEH 380 Skips next two lines if valid choice
typed.
360 PR I HT CHR $ C 7 > ; CHRH 7> ; Beeps twice to get attention.
3 7 0 G O T □ 33 0 Response was invalid; tries again.
3 0 0 P R I HT C $ Since choice accepted via GET, it
isn't displayed on the screen;
displays it back to user.
390 C • VAL C C U Needs this value later to determine
what section of program to branch
to for proper processing.

8.2 Writing the Code 185


8.2.4 What Does It Weigh?

Now the program asks the user for the weight of the letter or package. The
program makes sure that the user follows the instructions and types a
number for the weight and a symbol (0 or P) for ounces or pounds. Notice
that the program accepts both the numeric weight of the item and the
ounce/pound designation in the same string (line 530).
S ell R E M
G E T W E I G H T O F I TE M
5 1 5 VTAB 16
5 1 0 P R I H T " P l e a 5 e e n t e r t h e WE I GHT - a n u mb e r p l u 5
an O ( fo r ounc e 5 ) or a P ( fo r pound 5 ) - and
p r e 5 5 t h e R E T U R H k ey : " ;
Prompting message to tell user what
information to type and how to type
it.
5 2 0 C A L L - 868 Clears to end of line; useful to erase
any errors that might be typed.
530 I H P U T " " ; W $ Empty string suppresses question
mark.
5 4 0 W 1 $ • R I GH T $ C W $ , 1 ) Rightmost letter should be either 0
or P; use it later to see if weight is
consistent with postal regulations.
5 5 0 W • VAL CW$ ) How many ounces or pounds?
555 REM
W A S E H T E R E D W E I GH T V A L I D ?
560 I F W > 0 AHD ( W 1 $ • "0" OR W 1 $ • " P " ) THEH 7 1 0
If a weight was typed, and if last
character was either O for ounces
or P for pounds, then proceeds.
570 P R I HT CHR S ( 7 ) ; CHRS ( 7 ) ;
Beeps twice to get attention.
If the program has progressed this far, then everything typed by the user is
valid from the computer's point of view. However, the user's choices still
may not be consistent with postal regulations or the program's limitations.
First class letters must weigh less than 12 ounces, the program can't handle
express mail above a certain weight, and so on. This section of code uses
the value of variable C (set in line 390) to direct control to the proper
subroutine to check for consistency.

186 Chapter 8: Programming: Bringing It All Together


7 1110 R E M
C H E C K C O N S I STE N C Y
7 1 " O N C G O S U B 1 1110 11 0 , 1 1 11 11 11 , 1 2 11 0 0
Branches to appropriate subroutine
to see if weight typed is within
postal rules or program limitations
for mail class chosen.
7 2 11 I F N O T E F L AG T H E N 9 1 11 If no inconsistency detected in
subroutine then proceed with
processing.
7 3 11 G O S U B 6 0 0 0 0 REM K EYSTALL
Waits for user to acknowledge
message.
7 4 11 K E Y S T A L L • 11 Clears error flag set in subroutine.
7 5 11 C L E A R Resets all variables, clears arrays,
and so on.
7 6 11 G O T O 1 11 11 Restarts program loop.

8.2.5 Compute the Charge


Now that everything checks out all right, the program can proceed to
calculate the postage. The calculation is different for each of the three
classes of postage, so there are three separate calculating routines. Again,
what routine the program goes to depends on the value of C, the number
representing the postal class chosen by the user.
9 11 11 R E M
F I ND A P P R O P R I ATE CODE F O R P R O C E S S I N G
Everything is valid and consistent;
now program can solve for the
postage rate!
9 1 11 O N C G O S U B 1 11 11 11 , 2 11 11 11 , 3 0 0 0
Branches to proper calculating
routine.
9 2 11 G O S U B 6 1 0 0 0 R E M F O RMATTE R
Formats result for display.
93 11 P R I NT

8.2 Writing the Code 187


8.2.6 Display the Results

It's finally time to display the results!


935 R E M
D I S P L A Y R E S U LTS
940 P R I NT " P O STAGE N E E D E D : $ " ; T S
Finally, the postage due!
950 GOSUB 60 0 0 0 : R E M K E Y ST A L L
Doesn't go on until user is ready.
96 0 C L E A R Prepares for restart...
97 0 G O T O 1 0 0 . . . and does it.

8.2. 7 Calculating Routines

The following three subroutines do the actual rate calculations, based on


formulas, tables, or both. The rates for express mail are fairly
straightforward; they are based on a table created in the express mail
consistency-checking routine at line 10000. First class rates couldn't be
simpler; a little arithmetic is all that's needed. Priority mail is another story,
however; when you get to it, you'll find an explanation.
999 R E M
SUBROUT I NES BEG I N HERE
1 0 0 0 REM
E X P R E S S MA I L C A L C U L A T I O N
1010 w • I MT cw + • 99 > Weight must be increased to
compensate for fractions; postal
rates read "NOT MORE THAN
x POUNDS."
1 020 T a R cw> Rate array filled in express mail
consistency-checking routine
(line 10000).
1 0 30 RETURN Ends routine.
2 0 0 0 REM
F I RST CLASS CALCULAT I ON

188 Chapter 8: Programming: Bringing It All Together


2 0 1 0 T • . 2 0 + I N T C W + . 99 - 1 ) * . 1 7
First class rate is 20 cents first
ounce plus 17 cents for each
additional ounce or portion thereof
(January 1984 rates).
2 0 2 0 RETURN Ends routine.
Although there is something approaching a pattern to priority mail charges,
the pattern is obscure at best. This is especially true for the first ten pounds.
Pounds 1 through 5 are charged by the half-pound; pounds 6 through 10 are
full-pound charges. It's simpler and quicker to use a table for these charges
(lines 3030 to 3140) than to figure out a formula.
Weights over five pounds follow a more regular pattern than the first five;
they are all charged in full-pound increments. Furthermore, each five
pounds costs $2.38. Unfortunately, the cost for pound 6 is different from the
cost for pound 7, and so on. What it boils down to is that five-pound lots can
be charged at the same rate (line 3170), and anything that isn't a multiple
of 5 must be looked up in a table (lines 3180 to 3220).
If all this strains credulity, refer to United States Mail Service poster 103,
November 1981.
3 0 0 0 REM
P R I O R I T Y MA I L C A L C U L A T I O N
30 1 0 w • I HT cw + • 99 > Compensates for partial ounces or
pounds.
3020 I F w > 1 0 THEN 3 1 60 Goes to line 3160 for weights greater
than ten pounds (ounce weights
converted to pounds in consistency
subroutine starting at line 12000).
3025 REM
PR I OR I TV RATES TO 1 0 P OUNDS
3030 I F W < • 1 THEN T • 2 . 24
3 0 4 0 I F W > 1 AND W ( ■ 1 . 5 THEN T • 2 . 3 0
Rates in half-po-µnd increments.
3050 IF W > 1 . 5 AND W <= 2 THEN T • 2 . 54
3060 IF W > 2 AND W <• 2.5 THEN T • 2 . 78
3070 IF W > 2 . 5 AND W <• 3 THEN T • 3.01
3072 IF W > 3 AND W <• 3.5 THEN T • 3 . 25
3 0 78 IF W > 3 . 5 AND W <• 4 THEN T • 3 . 49
3080 IF w > 4 AND W <• 4.5 THEN T • 3 . 73
3Q90 IF w > 4 . 5 AND W <• 5 THEN T • 3 . 97

8.2 Writing the Code 189


3 1 0 1! I F W > 5 A N D W < • 6 T H E N T • 4 . 4 4
Rates by the pound now!
3 1 1 ll I F W > 6 AND w < · 7 THEN T • 4 . 92
3 1 2 1! I F W > 7 A N D W < • 8 T H E N T • 5 . 39
3 1 3 1! I F W > 8 AND W < • 9 THEN T • 5 . 87
3 1 4 1! I F W > 9 THEN T • 6 . 35
3 1 5 1! G O T O 3 2 4 1! Branches to RETURN statement.
3 1 6 1! R E M
P R I O R I TY R A T E S F O R O V E R 1 1! P O U ND S
3 1 7 1! T 1 • I N T C W / 5 - 1 ) * 2 . 38 + 3 . 9 7
First five pounds cost $ 3.97; each
added five pounds cost $ 2.38.
3 1 8 1! W 1 • W - I NT C W / 5 ) * 5
How many odd pounds are there
(pounds that are not multiples of 5
and must be charged at a special
rate)?
3 1 9 1! IF W1 • 1 THEH T2 • . 47
3 2 1l ll IF W1 • 2 THEH T2 • . 95
3 2 1 1! IF W1 • 3 THEH T2 • 1 . 42
3 2 2 1! IF W1 • 4 THEN T2 • 1 . 9 1!
3 2 3 11 T • T 1 • T2 Adds the five-pound-multiples rate
to the odd-pounds rate.
3 2 4 1! R E T U R N Ends routine.

8.2.8 Consistency-Checking Routines


The next three routines make sure that first class letters aren't too heavy,
that the requested rate can be calculated by the program and, in general,
that the program can deliver what the user wants. The express mail routine
begins by loading its rates into a table. (It gets the rates from a DATA list;
DATA lists are excellent places to store information you might need in a
program.) Then it checks to see if it has a rate for the package being sent.
First class just makes sure that the package weighs 12 ounces or less; that's
the maximum weight for a first-class item. Priority mail also has an easy
job; it just makes sure the package weighs more than 12 ounces but not
more than 70 pounds.
1 ll ll ll ll R E M
E X P R E S S MA I L C O H S I S T E H C Y C H E C K
1 1l ll 1 1l DATA 9 . 3 5 , 9 . 3 5 , 9 . 5 5 , 9 . 9 1! , 1 1l . 3 1l , 1 11 . 65 ,
1 1 . ll ll , 1 1 . 4 1! , 1 1 . 7 5 , ll
Express mail rates; 0 at end is "last
item" flag.

190 Chapter 8: Programming: Bringing It All Together


1 BB20 x • 0 Sets up counter to check how many
rates are read from DATA list.
1 0030 X • X + 1 Increments counter.
1 B B 4 0 READ R C X > Puts price into proper array
1 0 0s0 I F R CX) . 0 THEN 1 0 0 7 0
element.
Price of O marks end of list.
1 0 0 6 0 GOTO 1 0 0 3 0 Gets next price.
1 0070 X • X - 1 X includes count of "last item" flag
from 10050; subtracts it from count
since it's a "dummy" item.
1 0 000 IF W 1 $ • "P" THEN 1 0 1 0 0
Next line is for ounces only.
1 B B90 w • w 1 1 6 Converts ounces to pounds.
1 0 1 B B I F w < • x TH E N 1 0 1 4 0 If weight in pounds is covered by
the rate chart, then goes ahead.
1 0 1 1 0 PR I NT
1 0 1 2 0 P R I NT C H R $ C 7 ) ; C H R $ C 7 ) ; "TDD H E A V Y F D R
MY TABL E S - P L E A S E C A L L THE P O S T O F F I C E "
Sorry; can't help you.
1 0 1 3 0 E F L AG • 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 0 1 4 0 RETURN Ends routine.
1 1 0 0 0 REM
F I R S T C L A S S C O N S I STE N C Y C H E C K
1 1 0 1 0 IF W 1 $ • "□" AND W < 1 2 . 0 1 THEN 1 1 06 0
OK if not more than 12 ounces.
1 1 0 2 0 P R I NT
1 1 0 3 0 P R I N T C H R $ C 7 > ; C H R $ C 7 ) ; " T D D H E A VY F D R
F I RST CLASS"
Sorry-inconsistent!
1 1 0 4 0 P R I N T " T R Y P R I O R I T Y MA I L "
Suggests alternative.
1 1 0 s 0 E F L AG • 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 1 060 RETURN Ends routine.
1 2 0 B B REM
P R I O R I TY MA I L C O N S I STE N C Y C H E C K
1 20 1 0 IF W 1 $ • "P" THEN 1 2 090
If in pounds, then skips down.

8.2 Writing the Code 191


1 2020 IF w > 1 2 THEN 1 2 000 Skips down if weight is between 12
and 16 ounces.
1 2 0 3 0 P R I NT
1 2 0 4 0 P R I NT C H R $ C 7 ) ; C H R $ C 7 ) ; " T O O L I GH T F O R
F O R P R I O R I T V MA I L - " Too light!
1 2 0 5 0 P R I NT "TRY F I RST C L A S S "
Suggests alternative.
1 2060 EF LAG • 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 2 0 1 0 GOTO 1 2 1 5 0 Branches to end of routine.
1 20a0 w • w 1 16 Converts ounces to pounds.
1 2090 1F w <• 1 0 THEN 1 2 1 5 0 Final check: is item on the charts?
12100 PR I NT
1 2 1 1 0 P R I N T C H R $ C 7 > ; C H R $ C 7 ) ; " T O O H E AV Y F O R
F O R P R I O R I T Y MA I L - 11 Off the charts.
1 2 1 2 0 P R I NT "TRY O N E O F T H E A I R E X P R E S S C O M P A N I E S
Too big for the Post Office!
1 2 1 3 0 E F L AG • 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 2 1 5 0 RETURN Ends routine.
To Be Truly Friendly: A truly friendly program would automatically
convert too-heavy first class mail to priority mail and too-light priority
mail to first class, would present a list of air freight companies (with
phone numbers, of course) for mail too heavy for the Post Office, and so
on. We'll leave it to you to add such niceties.

8.2.9 The Keystall Routine


The keystall routine interrupts execution of the program and waits for the
user to press a key before going on. The GET statement in line 60040
actually does the waiting; when the user presses a key, the program
continues. What key the user presses doesn't matter-the program doesn't
care what value is assigned to A$.
59999 R E M
UT I L I T Y R O UT I H E S Routines useful for various tasks but
ancillary to rest of program.
60 0 0 0 REM
K E V ST A L L Routine to interrupt program until
user presses a key.
6 0 0 1 0 VTAB 2 4 Moves cursor to screen bottom.

192 Chapter 8: Programming: Bringing It All Together


60020 I NV E R S E Sets text to appear black-on-white.
60030 P R I NT " P R E S S R E T U R N TO GO O H • • • II •
60040 GET A S Waits for keypress.
60050 N O RM A L Restores ordinary white-on-black.
60 060 RETURN Ends routine.

8.2. 1 O The Formatting Routine

After the postage charge is calculated, the program branches to this final
subroutine. Here the final result is checked to see how it will look when it is
displayed. Does it have a decimal point? Applesoft suppresses trailing zeros
after a decimal point, but people are used to seeing them when dealing with
dollars and cents. The formatting subroutine adds trailing zeros as needed.
6 1 0 0 0 REM
MON E Y F O RMATT E R Adds zeros after the decimal point
where needed.
61 0 1 0 T S • STR S C T > Turns the calculated postage fee
into a string.
61 020 I F T • I NT C T > T H E N T S • T S + " , 0 0 "
If charge is in whole dollars, adds a
decimal point and two zeros.
6 1 030 I F A S C < R I GH T S C T S , 2 » • 46 T H E N T S • T S + " 0 "
If second character from the right is
a decimal point (ASCII code 46)
then number has only one digit to
right of decimal-so adds a "O" to
the string.
61 040 RETURN Ends the routine.

8.3 Final Advice to the New Programmer


The program planning methods discussed and demonstrated in this chapter
won't necessarily work for everyone. Different people have different
programming styles, and some people won't be comfortable with the
(perhaps) coldly logical model presented here. What's important is to find a
style that works for you. Programming is a logical art; it shouldn't be a
confining one. Be as creative as your own internals will let you be,
remembering that poets also plan.

8.3 Final Advice to the New Programmer 193


Keep in mind as you learn to program, please, when a bug is as hard to find
as cheap gas, that deep down at the bit level-down where the computer
deals with the only things it really understands-there are only reros and
ones.

194 Chapter 8: Programming: Bringing It All Together


Appendix A Summary of Applesoft Statements and Functions

..


195
This appendix lists abbreviated descriptions of all Applesoft statements and
functions. Each description is preceded by a syntactic definition and at least
one example; see Appendix B for definitions of syntactic terms used here.
References in square brackets at the end of each description give the
section or appendix of this manual where more detailed information about
the feature can be found.

-
ABS

Syntax: ABS c aexpr>


Example: ABS < - 2 . 7 7 )
Yields the absolute value (value without regard to sign) of the argument.
The example yields 2.77. [2.4.1.1]

-
ASC

Syntax: Ase < sexpr>


Example: A S C ( "Q U E ST" )
Yields the ASCII code for the first character in the argument. The example
yields 81 (ASCII code for Q). [4.2.5.4, C]

Assignment Statement

Syntax: c LET 1 avar = aexpr


c L E T 1 svar = sexpr
Examples: L E T A • 23 . 567
A $ • " H UMBUG"
Assigns the value of the expression following = to the variable preceding it.
LET is optional. [2.2]

-
ATN

Syntax: ATH <aexpr>


Example: ATH < . 8 7 7 1 >
Yields the arc tangent, in radians, of the argument. The example yields
.720001187 (radians). [2.4.1.8]

196 Appendix A: Summary of Applesoft Statements and Functions


-
CALL
Syntax: C A L L aexpr
Example: CALL -922
Executes a machine-language subroutine at the specified decimal memory
address. The example issues a line feed. [7.1.3, F]

-
CHR$
Syntax: C H R $ c aexpr>
Example: CHR$ (65)
Yields the character corresponding to the ASCII code given as an argument.
The example yields the letter A. [4.2.5.3]

CLEAR
Syntax: CLEAR
Example: CLEAR
Resets all variables and internal control information to their initial state.
Program code is unaffected. [1.2.2]

COLOR =
Syntax: C O L O R • aexpr
Example: COLOR• 1 2
Sets the display color for plotting low-resolution graphics. The example sets
the display color to green. [6.1.2]

-
CONT
Syntax: c□HT
Example: CONT
Resumes program execution after it has been halted by STOP, END,
� or (sometimes) I CONTROL H RESET j. [l.3.3]

Appendix A: Summary of Applesoft Statements and Functions 197


-
cos
Syntax: cos caexpr>
Example: cos ( 2 )
Yields the cosine of the argument, which must be expressed in radians. The
example yields -.416146836. [2.4.1.6]

-
DAT�

Syntax: DATA [lit.era! I string I real I int,eger]


[ { , [literal I string I real I integer] } ]
Example: DATA J O H N SM I TH , " C ODE 3 2 " ,
23 . 45 , -6
Great.es a list of it.ems for use by READ starements. In the example, the first
it.em is the string " JOHN SMITH", the second is the string "CODE 32", the
third is the real number 23.45, and the fourth is the inreger -6. [5.1.4)

DEF FN

Syntax: D E F F N name (name) = aexpr


Example: D E F F N C UBE C X > • X * X * X
Defines a new function for use in the program. The example defines a
function that yields the cube of its argument. [2.4.3]

-
DEL

Syntax: D E L linenum , linenum


Example: DEL 23 , 56
Deleres a range of consecutive lines from the program. The example deleres
lines 23 to 56, inclusive. [1.1.5]

198 Appendix A: Summary of Applesoft Statements and Functions


-
DIM

Syntax: D I M name[ xis) subscript


[ { , name[ xis) subscript} )
Example: D I M M A R K ( 5 0 , 3 ) , HAME S ( 5 0 )
Defines and allocates space for one or more arrays. The example defines a
two-dimensional real array MARK, whose first subscript varies from O to 50
and whose second varies from O to 3, and a string array NAME$ with one
subscript that varies from O to 50. [4.1.1)

DRAW

Syntax: DRAW aexpr [AT aexpr , aexpr)


Examples: D R A W 4 AT 5 0 , 1 0 0
DRAW 4
Draws a shape at a specified point on the high-resolution graphics screen
from the shape table currently in memory. The first example draws shape
number 4, beginning in column 50, row 100, using the current color, scale,
and rotation settings; the second example draws shape 4 at the last point
plotted by HPLOT, DRAW, or XDRAW. [6.3.2.1]

-
END
Syntax: EHD
Example: EHD
Terminates the execution of the program and returns control to the user. No
message is displayed. [3.6.2]

-
EXP
Syntax: E X P c aexpr>
Example: EXP C2>
Yields the mathematical exponential of its argument (the constant
e = 2. 7182818 raised to the power specified by the argument). The example
yields e squared, or 7.3890561. [2.4.1.9)

Appendix A: Summary of Applesoft Statements and Functions 199


FLASH

Syntax: FLASH
Example: FLASH
Causes all text displayed on the screen with subsequent PRINT statements
t,o flash between white-on-black and black-on-white. May not work properly
for lowercase letters (and other characters with ASCII codes above 95) if
the 80-Column Text Card is installed and running in "active-80" mode.
[5.2.4.10]

-
FN
Syntax: F N name < aexpr>
Example: F N C U BE ( 6 )

Applies a designated function t,o the value of the argument expression.


Assuming the definition for the function CUBE given under DEF FN, the
example yields the value 216. [2.4.3]

-
FOR

Syntax: F O R name = aexpr TO aexpr [STEP aexpr]


Examples: FOR J • 1 TO 1 0
F O R M A R K • 0 TO 1 0 0 S T E P 5
F O R N UMBE R • 2 0 T O - 2 0 STEP - 2
Marks the beginning of a loop, identifies the index variable, and gives the
variable's starting and ending values and (optionally) the amount by which
it is t,o change (step) on each pass through the loop. The first example
begins a loop whose index variable J takes on all values from 1 t,o 10,
stepping by 1; the second begins a loop whose index variable MARK takes
on values from 0 t,o 100, stepping by 5; the third begins a loop whose index
variable NUMBER takes on values from 20 t.o -20, stepping by -2. [3.3.1]

200 Appendix A: Summary of Applesoft Statements and Functions


-
FRE
Syntax: F R E < expr>
Example: FRE < B >

Yields the amount of remaining memory, in bytes, available to the program.


Also forces "garbage collection" of dead strings. The argument is ignored,
but must be a valid Applesoft expression. [7.2.3]

-
GET
Syntax: G E T var
Example: GET A N SWE R $

Accepts a single character from the keyboard without displaying it on the


screen and without requiring that the I RETURN I key be pressed. Program
execution is suspended until the user presses a key. In the example, the
character typed is assigned to the variable ANSWER$. [5.1.3]

GOSUB
Syntax: G O S U B linenum
Example: G O S U B 2 5 ll

Executes a subroutine beginning at the designated line number (250 in the


example). [3.4.1]

GOTO
Syntax: G O T O linenum
Example: G O T O 4 ll ll

Sends control unconditionally to the designated line number (400 in the


example). [3.1I

Appendix A: Summary of Applesoft Statements and Functions 201


-
GR

Syntax: GR
Example: GR
Converts the display to 40 rows of low-resolution graphics with four lines of
text at the bottom. The screen is cleared to black, the cursor is moved to the
beginning of the last line, and the low-resolution display color is set to black.
[6.1.l]

HCOLOR =

Syntax: HC□L□R • aexpr


Example: HCOLOR• 1

Sets the display color for plotting high-resolution graphics. The example
sets the display color to green. [6.2.3]

-
HGR

Syntax: HGR
Example: HGR

Converts the display to 160 rows of high-resolution graphics with four lines
for text at the bottom. The screen is cleared to black and page 1 of
high-resolution graphics is displayed. The contents of the text display, the
location of the cursor, and the high-resolution display color are unaffected.
[6.2.1]

-
HGR2

Syntax: HGR2
Example: HGR2

Converts the display to full-screen ( 192 rows) high-resolution graphics with


no text. The screen is cleared to black and page 2 of high-resolution
graphics is displayed. The contents of the text display, the location of the
cursor, and the high-resolution display color are unaffected. [6.2.2]

202 Appendix A: Summary of Applesoft Statements and Functions


HIMEM:
Syntax: H I M E M : aexpr
Example: H I MEM : 32767

Sets the address of the highest memory location available to the Applesoft
program, including its variables. The example sets the end of program and
variable storage to 32767. Used to protect an area of memory for data,
high-resolution graphics, or machine-language code. [7.2.1]

-
HLIN

Syntax: H L I l'I aexprl, aexpr2 A T aexpr3


Example: H L i l'I 1 0 , 2 0 A T 3 0

Draws a horizon�! line in low-resolution graphics, using the current


low-resolution display color. The example draws a line across row 30 from
column 10 to column 20. [6.1.4]

HOME
Syntax: HOME
Example: HOME

Clears all text from the text window and moves the cursor to the top-left
comer of the window. [5.2.4.3]

HPLOT
Syntax: H P L O T aexpr, aexpr [ { ro aexpr , aexpr} ]
H P L O T TO aexpr, aexpr [ { ro aexpr , aexpr} ]
Examples: HPLOT 75 , 2 0
H P L O T 4 8 , 1 1 5 T O 79 , 8 4 T O 1 1 0 ,
1 1S
HPLOT TO 2 7 0 , 1 0

Plots a point or line on the high-resolution graphics screen in the current


high-resolution display color. The first example plots a single point at
column 75, row 20; the second example draws lines from column 48,
row 115 to column 79, row 84 to column 110, row 115; the third draws a line
to column 270, row 10 from the last point plotted with HPLOT, using the
color of the last point plotted (not necessarily the current display color).
(6.2.4]

Appendix A: Summary of Applesoft Statements and Functions 203


-
HTAB

Syntax: H T A B aexpr
Example: HTAB 2 3
Positions the cursor to a specified column of the text display. The example
moves the cursor to column 23. If you have the Apple II 80-Column Text
Card, see the manual accompanying that product for further information on
using HTAB. [5.2.4.6]

IF ...THEN

Syntax: I F expr T H E H statement [ { : statement} ]


I F expr T H E H [GO T O] linenum
I F expr [TH E H] GOTO linenum
Examples: I F AGE < 1 8 T H E H A • 8 : B • 1
: C • 2
I F A H SWE R S • " Y E S " T H E H GOTO
1 88
I F H > M A X T H E H GOTO 2 5
IF H > MAX THEH 25
I F H > M A X GOTO 2 5
Executes or skips one or more statements, depending on the truth of a
stated condition. The first example sets A to 0, B to 1, and C to 2 if the value
of AGE is less than 18; the second branches to line 100 if the value of
ANSWER$ is the string "YES"; the last three all branch to line 25 if the
value of N is greater than that of MAX. In all cases, if the stated condition is
false, execution continues with the next program line. [3.2.2]

204 Appendix A: Summary of Applesoft Statements and Functions


-
IN#

Syntax: I N" aexpr


Example: I N" 2

Specifies the source for subsequent input. The example causes subsequent
input to be read from the device at port 2. [5.1.1]

iNPUT

Syntax: 1 N P U T [string] var [ { , var} ]


Examples: I MPUT A%
I N P U T " T Y P E AGE , T H E M A C OMMA ,
T H E M H A M E " ; A 6E , N AME $
Reads a line of input from the current input device. The first example reads
a value into variable A%; the second displays a prompting message and
then reads values into variables AGE and NAME$. [5.1.2]

-
I NT

Syntax: I NT caexpr>
Examples: I NT ( 98 . 6 )
I NT C - 2 7 3 , 1 6 )
Yields the integer part of the argument value. The examples yield 98
and -274, respectively. [2.4.1.3]

INVERSE

Syntax: I NV E R S E
Example: I NV E R S E
Causes all text displayed on the screen with subsequent PRINT statements
to appear in black-on-white instead of the usual white-on-black. May not
work properly for lowercase letters (and other characters with ASCII codes
above 95) if the 80-Column Text Card is installed and running in "active-80"
mode. [5.2.4.9]

Appendix A: Summary of Applesoft Statements and Functions 205


LEFT$
Syntax: LEFH c sexpr, aexpr>
Example: LEFTS C "APPLESOFT" , 5 )

Yields a specified number of characters from the beginning of a string. The


example yields the string "APPLE". [4.2.4.1]

-
LEN
Syntax: L E H c sexpr>
Example: L E H < "NEVE R A DULL MOME NT" )

Yields the length of a string in characters. The example yields 19. [4.2.2]

-
LET
See "Assignment Statement."

-
LIST

Syntax: L I S T (linenurnl] [-linenum2]


L I ST [linenurnl] [ , linenurn2]
Examples: L I ST
L I ST 1 5 1
L I S T 2 "'11 - 3 1 !1
L I S T 2 1! 1 , 3 1 !1

Displays all or part of the program on the screen, or writes it to the current
output device. The first example lists the entire program; the second lists
line 150 only; the last two list lines 200 to 300, inclusive. [1.2.3]

206 Appendix A: Summary of Applesoft Statements and Functions


-
LOAD

Syntax: L O A D [name]
Examples: LOAD
L O A D DEMO
Reads a program into memory from a disk or tape. The first example reads a
program from a tape cassette; the second reads from a disk file named
DEMO (casette tape cannot be used with Apple Ile). If you have one or more
disk drives, see your disk operating system manual for further information.
[1.2.6, M]

-
LOG

Syntax: LOG caexpr>


Example: LOG C 2 >
Yields the natural logarithm of the argument. The example yields
.693147181. [2.4.1.10]

LOMEM:

Syntax: L OM E M : aexpr
Example: L O M E M : 2 4 5 76
Sets the address of the lowest memory location available to the program for
variable storage. The example sets the beginning of variable storage
to 24576. [7.2.2]

·
-
MID$

Syntax: M I Ds csexpr , aexpr [ , aexpr]>


Examples: M I D $ C " A H A P P L E A DA Y " , 4 , 5 )
M I D $ C " A H A P P L E A DA Y " , 4 )
Yields a specified number of characters beginning at a specified position in
a given string. The first example yields the string APPLE"; the second yields
the string "APPLE A DAY". [4.2.4.2]

Appendix A: Summary of Applesoft Statements and Functions 207


-
NEW
Syntax: HEW
Example: HEW
Clears the current program from memory and resets all variables and
int.emal control information to their initial stat.es. [1.2.1]

-
NEXT
Syntax: N E X T [ avar [ { , avar} ] ]
Examples: NEXT
N E X T I NDE X
NEXT J , I
Marks the end of a loop and causes the loop to be repeat.ed for the next
value of the index variable, as specified in the corresponding FOR
stat.ement. The first example ends the most recently ent.ered loop; the
second ends the loop whose index variable is INDEX; the third ends the pair
of nest.ed loops whose index variables are J and I. [3.3.2]

NORMAL
Syntax: N O RM A L
Example: N O RM A L
Causes all t.ext displayed on the screen with subsequent PRINT stat.ements
to appear in the usual white-on-black; cancels the effects of INVERSE or
FLASH. [5.2.4.11]

NOTRACE
Syntax: HOTRACE
Example: NOTRACE
Stops the display of line numbers for each stat.ement execut.ed; cancels the
effects of TRACE. [7.3.2]

208 Appendix A: Summary of Applesoft Statements and Functions


ON ... GOSUB

Syntax: O H aexpr Gosue linenum [ { , linenum} ]


Example: O H I D GOSUB 1 0 0 , 2 0 0 , 2 3 , 4 0 0 5 ,
500

Chooses a subroutine to execute depending on the value of an expression.


The example transfers control to the subroutine beginning at line 100, 200,
23, 4005, or 500, depending on whether the value of ID is 1, 2, 3, 4, or 5; if ID
has none of these values, execution continues with the next statement.
[3.4.3)

ON ... GOTO

Syntax: O H aexpr GOTO linenum [ { , linenum} )


Example: O H I D GOTO 1 0 0 , 2 0 0 , 23 , 4 0 0 5 ,
500

Chooses a line number to branch to depending on the value of an


expression. The example transfers control to line 100, 200, 23, 4005, or 500,
depending on whether the value of ID is 1, 2, 3, 4, or 5; if ID has none of
these values, execution continues with the next statement. [3.2.1]

ONERR GOTO

Syntax: O H E R R GOTO linenum


Example: O H E R R GOTO 5 0 0

Replaces Applesoft's normal error-handling mechanism with a subroutine


beginning at a specified line number. The example establishes an
error-handling subroutine beginning at line 500. [3.5.1, E]

-
POL
Syntax: PDL c aexpr>
Example: PDL C 1 >
Reads the current dial setting on a designated hand control. The example
reads the dial on hand control 1. [5.1.6.1, F.4]

Appendix A: Summary of Applesoft Statements and Functions 209


-
PEEK
Syntax: P E E K c aexpr>
Example: PEEK C37>
Yields the contents of a specified location in memory. The example yields
the contents of location 37, which contains the current vertical position of
the text cursor on the display screen. [7.1.1, F.l]

-
PLOT
Syntax: P L O T aexpr , aexpr
Example: P L O T 1fil , 2 0
Plots a single block of the current display color at a specified position on the
low-resolution graphics screen. The example plots a block at column 10,
row 20. [6.1.3]

-
POKE
Syntax: P o K E aexpr , aexpr
Example: P O K E - 1 63 0 2 , 0
Stores a value in a specified location in memory. The example stores the
value O at location 49234 (65536 - 16302), causing the display to switch from
mixed graphics and text to full-screen graphics. [7.1.2, F]

-
POP
Syntax: POP
Example: POP
Removes the most recent return address from the control stack, causing the
next RETURN statement to send control to the statement following the
second most recently executed GOSUB. [3.4.4]

210 Appendix A: Summary of Applesoft Statements and Functions


-
POS

Syntax: Pas c expr>


Example: P O S C il>
Yields the current horizontal position of the cursor on the text display. The
argument is ignored, but must be a valid Applesoft expression. [5.2.4.8]

-
PR#

Syntax: P R I aexpr
Example: PR# 1
Specifies the destination for subsequent output. The example causes
subsequent output to be sent to the device at port 1. [5.2.1]

PRINT

Syntax: P R I H T [ { expr [ , I ; ] } ]
Examples: P R I NT
P � I HT A $ , " X • " ; X
Writes a line of output to the current output device. The first example
writes a blank line; the second writes the value of variable A$, followed at
the next available tab position by the string "X = ", followed immediately
by the value of variable X. (5.2.2]

-
READ

Syntax: R E A D var [ { , var} ]


Example: R E A D A , BX , C $
Reads values from DATA statements in the body of the program. The
example reads values into variables A, B%, and C$. [5.1.4]

Appendix A: Summary of Applesoft Statements and Functions 211


RECALL
Syntax: R E C A L L name[x]
Example: RECALL MX

11, 11 Plus, lie


I Reads values into an array from a tape cassette. The example reads
values into array MX [M]

-
REM
Syntax: R E M {character}
Example: R E M TH I s A R E M A R K

Includes remarks in the body of a program for the benefit of a human


reader. [1.1.7]

RESTORE
Syntax: R E ST O R E
Example: R E ST O R E
Causes the next READ statement executed to beginning reading at the first
item of the first DATA statement in the program. [5.1.5]

RESUME
Syntax: R E S UME
Example: R E S UME

At the end of an error-handling routine (see ONERR GOTO), causes


resumption of the program at the beginning of the statement in which the
error occurred. [3.5.2]

RETURN
Syntax: RETURN
Example: RETURN
The last statement in a subroutine returns control from a subroutine to the
statement following the GOSUB that called the subroutine. [3.4.2]

212 Appendix A: Summary of Applesoft Statements and Functions


RIGHT$

Syntax: R I GH H (sexpr , aexpr>


Example: R I GH T S C " A P P L E S O FT" , 4 )
Yields a specified number of characters from the end of a string. The
example yields the string "SOFT". [4.2.4.3]

-
RND

Syntax: R H O c aexpr>
Example: RHO ( 1 )
Yields a random number between O and 1. Zero and negative argument
values yield repeatable sequences of random numbers. [2.4.2]

ROT =

Syntax: R O T • aexpr
Example: ROT• 1 6
Sets the angular rotation for high-resolution shapes to be drawn with DRAW
or XDRAW. The example causes the shape to be rotated 90 degrees
clockwise. [6.3.2.4]

-
RUN

Syntax: R U H [linenum I name]


Examples: RUH
R U H S il il
RUH DEMO
Executes an Applesoft program. The first example executes the program
currently in memory from the beginning; the second executes the program
in memory , starting at line 500; the third loads and executes a program from
a disk file named DEMO. [1.2.4]

Appendix A: Summary of Applesoft Statements and Functions 213


-
SAVE

Syntax: SAVE [name]


Examples: SAVE
SAVE DEMO
11, II Plus, lie Writes the Applesoft program currently in memory to a disk or tape. The
first example writes the program to a tape cassette; the second writes it to
a disk file named DEMO. [1.2.5, M]

SCALE =
Syntax: S C A L E • aexpr
Example: S C A L E • 1 111

Sets the scale factor for high-resolution shapes to be drawn with DRAW or
XDRAW. The example causes the shape to be drawn ten times bigger than
the definition given in the shape table. [6.3.2.3]

-
SCRN
Syntax: s c R Ii < aexpr , aexpr>
Example: S C R N ( 1111 , 2 111 >

Yields the code for the color currently displayed at a designated position on
the low-resolution graphics screen. The example yields the code for the
color at column 10, row 20. [6.1.6]

-
SGN
Syntax: S G N caexpr>
Example: SGN C - 1 4 4 )

Yields a value of -1, 0, or + 1, depending on the sign of the argument. The


example yields -1. [2.4.1.2]

214 Appendix A: Summary of Applesoft Statements and Functions


SHLOAD
Syntax: S H L □AD
Example: SHL □ AD

II, II Plus, lie I Loads a shape table into memory from a tape cassette. [6.3.2.5, M]

-
SIN

Syntax: S I M caexpr>
Example: SIM <2>
Yields the sine of the argument, which must be expressed in radians. The
example yields .909297427. [2.4.1.5)

-
SPC
Syntax: sPc caexpr>
Example: SPC (8)
Introduces a specified number of spaces into the line being written by a
PRINT statement. The example writes eight spaces. [5.2.4.4)

SPEED =
Syntax: S P E E D • aexpr
Example: S P E E D • S il
Sets the rate at which text characters are to be sent to the display screen or
other input/output device. The slowest rate is O; the fastest is 255.
[5.2.4.12]

-
SQR

Syntax: S Q R caexpr>
Example: SQ R C 2 >
Yields the positive square root of the argument; the example yields
1.41421356. [2.4.1.4]

Appendix A: Summary of Applesoft Statements and Functions 215


-
STOP
Syntax: STDp
Example: STOP

Terminates the execution of the program and returns control to the user. A
message is displayed identifying the program line in which the STOP
statement appears. (3.6.1]

STORE
Syntax: STORE name[x]
Example: STORE MX
I I , II Plus, lie I Stores values from an array onto a tape cassette. The example stores the
contents of array MX. [M]

-
STR$
Syntax: STR S caexpr>
Example: STR S < 1 2 . 4 5 )
Yields a string representing the numeric value of the argument. The
example yields the string "12.45". [4.2.5.1, I]

-
TAB

Syntax: TAB caexpr>


Example: TAB ( 23 )

Positions the text cursor at a specified position on the output line during
execution of a PRINT statement. The example moves the cursor to
column 23. [5.2.4.5]

216 Appendix A: Summary of Applesoft Statements and Functions


-
TAN
Syntax: T A H caexpr>
Example: TAH C 2 )
Yields the tangent of the argument, which must be expressed in radians.
The example yields -2.18503987. [2.4.1.7]

-
TEXT
Syntax: TEXT
Example: TE X T

Converts the display to 24 lines of text, with the cursor positioned at the
beginning of the bottom line. [5.2.4]

TRACE
Syntax: TRACE
Example: TRACE
Causes the line number of each statement to be displayed on the screen as
it is executed. [7.3.1]

-
USR

Syntax: usR c aexpr>


Example: USR C3)
Executes a machine-language subroutine supplied by the user, passing it a
specified argument. The subroutine is entered via a JMP Gump) instruction
stored at addresses $0A through $0C hexadecimal. The example passes the
argument value 3. [7.1.4]

Appendix A: Summary of Applesoft Statements and Functions 217


-
VAL

Syntax: V A L c sexpr>
Example: VAL C " - 3 . 7E4")

Yields the numeric value represented by the string supplied as an


argument. The example yields -37000. [4.2.5.2]

-
VLIN

Syntax: V L I H aexpr , aexpr A T aexpr


Example: VL I H 1 0 , 2 0 A T 3 0
Draws a vertical line in low-resolution graphics, using the current
low-resolution display color. The example draws a line down column 30
from row 10 to row 20. [6. 1.5]

-
VTAB

Syntax: VTAB aexpr


Example: VTAB 1 5
Positions the cursor to a specified row of the text display. The example
moves the cursor to row 15. [5.2.4. 7]

-
WAIT

Syntax: W A I T aexpr , aexpr [ , aexpr]


Examples: WA I T 4 9 3 4 7 , 1 5
WA I T 4934 7 , 1 5 , 1 2
Suspends program execution until a specified bit pattern appears at a
specified memory location. Used to wait for a status signal from a peripheral
device. The second and (optional) third arguments are masks: the second
specifies which bits of the designated location are of interest, the third
specifies the values to be tested for in those bits. The first example
suspends execution until a 1 bit appears in any of the four low-order bit
positions of location 49347; the second waits for a 1 bit in position 0 or 1 or a
0 bit in position 2 or 3. [7.1.5]

218 Appendix A: Summary of Applesoft Statements and Functions


XDRAW

Syntax: X D � A w aexpr [AT aexpr , aexpr]


Examples: XDRAW 4 AT S B , 1 e e
XDRAW 4
Draws a shape from the shape table currently in memory at a specified
point on the high-resolution graphics screen. Each point in the shape is
plotted using the complement of the color currently displayed at that point.
Typically used to erase a shape already drawn. The first example erases
shape number 4, beginning in column 50, row 100, using the current scale
and rotation settings; the second example erases shape 4 at the last point
plotted by HPLOT, DRAW, or XDRAW. [6.3.2.2]

Appendix A: Summary of Applesoft Statements and Functions 219


Appendix B Syntax Definitions

221
This appendix describes the syntax definitions given in Appendix A. The
following symbols are used in the syntax definitions:
means "is defined as"
separates alternative definitions (alternative definitions for the same
term may also be given separately)
[] enclose elements that can be omitted
{ } enclose elements that can be repeated one or more times
aexpr (arithmetic expression)
real I integer I avar I fcall
unop aexpr
aexpr alop aexpr
sexpr relop sexpr
(aexpr)
Parentheses cannot be nested more than 36 levels deep.
alop (arithmetic or logical operator)
aop l relop I lop
aop (arithmetic operator)
+ 1-1*1/I
avar (arithmetic variable)
realvar I intvar
character
letter I digit I spchar I quote I space
digit
0111213141516171819
expr (expression)
aexpr I sexpr
fcall (function call)
name ( expr [ {, expr} ] )
integer
[ + I - ] {digit}
Integers must be between -32767 and +32767 to be valid.

222 Appendix B: Syntax Definitions


intvar (integer variable)
namex [subscript]
letter
uppercase I lowercase
line
linenum [ {statement:} ] statement I RETURN I
linenum (line number)
digit [ {digit} ]
Line numbers must be in the range O to 63999.
literal
[ {character} ]
lop (logical operator)
AND I OR
Notice that NOT is not included here.
lowercase
a l b I c I d I e I f l g l h I i lj I k I
llmlnlolplqIrisltlulvl
wlxlylz
name
uppercase [ {uppercase I digit} ]
A name can be of any length. When distinguishing one name from another,
Applesoft ignores any characters after the first two. However, even the
ignored portion of a name must not contain a special character or any of
Applesoft's reserved words.
quote
II

real
[+ I -] {digit} [ . {digit} ] [ E [+ I -] [ digit [digit] ] ]
[+ I -] [ {digit} ] . [ {digit} ] [ E [+ I -] [ digit [digit] ] ]
The letter E in a real number stands for "times 10 raised t.o the power after
the E." Valid reals must be between -1E38 and + 1E38.

Appendix B: Syntax Definitions 223


Applesoft recognizes the following as reals and evaluates them as 0:
. +. -. .E +.E -.E
.E+ .E- +.E+ +.E- -.E+ -.E-
In addition, the following are recognized as reals and evaluated as O when
used as numeric responses to INPUT or as numeric elements of DATA:
! SPACE ! + - E +E -E
E+ E- +E+ +E- -E+ -E-
The GET statement evaluates all of the single-character reals listed as 0.
realvar (real variable)
name [subscript]
relop (relational operator)
= l < l > l <= l = < l >= l = > l < > I > <
schar (string character)
letter I digit I spchar I space
Notice that the quote character ( is not included here.
11)

sexpr (string expression)


string I svar
sexpr sop sexpr
(sexpr)
Parentheses cannot be nested more than 36 levels deep.
sop (string operator)
+
space
! SPACE !
spchar (special character)
+ l-1*1/1 1= 1 < 1 > 1(1)1 , 1 . 1 : 1 ; 1
A

% 1 $ 1 #�? 1 & 1 ' 1 @ 1 ! 1 [ 1 ] 1 { 1 } 1 \ I


1 : 1_1 1 I
Control characters (characters typed while holding down the I CONTROL I
key) and the null character are also considered special characters. Notice
that the quote character (") and I SPACE I are not included here.

224 Appendix B: Syntax Definitions


statement
See Appendix A for syntactic definitions of all Applesoft statements.
string
"[{schar}]"
"[{schar}]
The second form of string can appear only at the end of a line.
subscript
( aexpr [ {, aexpr} ] )
The maximum number of dimensions (aexpr's) is 89, although in practice
this is limited by the extent of memory available.
svar (string variable)
name$ [subscript]
unop (unary operator)
+ 1 - I NOT
uppercase
AIBICIDIEIFIGIHIIIJIKI
LIMINIOIPIQIRISITIUIVI
WIXIYIZ
var (variable)
avar l svar

Appendix B: Syntax Definitions 225


Appendix C ASCII Character Codes


,o

227
This appendix contains a chart of the ASCII (American Standard Code for
Information Interchange) character codes. The first 32 codes represent
control characters; to type these characters from the Apple computer
keyboard, press I CONTROL I and hold it down while pressing the designated
character. (Some of these characters also have single-key representations,
as noted.) The abbreviations given for these codes in the column labeled
Char represent standard control functions originally intended for use on
teletypes; the meanings of these abbreviations are given in the Meaning
column. Functions marked with a dagger (t) are implemented on the
Apple iI; the others are listed purely for historical interest.
I Note: Older model Apples (II, II Plus) don't have some of the keys listed
in the Type column. To access these characters, use the CHR$ function.
Dec = decimal ASCII code
Hex = hexadecimal ASCII code
Char = ASCII character name
Type = what you type from the Apple computer keyboard

228 Appendix C: ASCII Character Codes


Dec Hex Char Type Meaning
0 00 NUL � null character t
1 01 SOH ! CONTROL HA) start of heading
2 02 STX � start of text
3 03 ETX � end of text
4 04 EOT � end of
transmission
5 05 ENQ I CONTROL H]] inquiry
6 06 ACK I CONTROL fill acknowledge
7 07 BEL � bell t
8 08 BS � or E] b�9kspace t
9 09 HT I CONTROL rill horizontal tab
10 0A LF I CONTROL KI) or IT] line feed t
11 OB VT I CONTROL HK] or [Il vertical tab
12 QC FF I CONTROL KI) form feed
13 OD CR � or I RETURN I carriage return t
14 OE so � shift out
15 OF SI � shift in
16 10 DLE ! CONTROL [E) data link escape
17 11 DCl � device control I
18 12 DC2 � device control 2
19 13 DC3 ! CONTROL H � device control 3
20 14 DC4 I fJ
CONTROL H device control 4
21 15 NAK � or E] negative
acknowledge
22 16 SYN ! CONTROL f{y] synchronous idle
23 17 ETB � end of
transmission
block
24 18 CAN I CONTROL Hi] cancel t
25 19 EM � end of medium
26 lA SUB ! CONTROL I@ substitute
27 1B ESC I CONTROL l{O or I ESC I escape
28 lC FS I CONTROL H \] file separator
29 1D GS I CONTROL HJ] group separator
30 1E RS I CONTROL H � record separator
31 lF us I CONTROL fl-] unit separator

Appendix C: ASCII Character Codes 229


The following characters can be typed directly from the keyboards of most
Apples. If you are using a model II or II Plus, use the CHR$ function to
generate the "missing" characters:
Dec Hex Char Dec Hex Char Dec Hex Char
32 20 ! SPACE ! 64 40 @ 96 60
33 21 ! 65 41 A 97 61 a
34 22 " 66 42 B 98 62 b
35 23 # 67 43 C 99 63 C
36 24 $ 68 44 D 100 64 d
37 25 % 69 45 E 101 65 e
38 26 & 70 46 F 102 66 f
39 27 71 47 G 103 67 g
40 28 ( 72 48 H 104 68 h
41 29 ) 73 49 105 69
42 2A • 74 4A J 106 6A j
43 2B + 75 4B K 107 6B k
44 2C 76 4C L 108 6C
45 2D 77 4D M 109 6D m
46 2E 78 4E N 110 6E n
47 2F I 79 4F 0 111 6F o
48 30 0 80 50 p 112 70 p
49 31 1 81 51 Q 113 71 q
50 32 2 82 52 R 114 72 r
51 33 3 83 53 s 115 73 s
52 34 4 84 54 T 116 74 t
53 35 5 85 55 u 117 75 u
54 36 6 86 56 V 118 76 V
55 37 7 87 57 w 119 77 w
56 38 8 88 58 X 120 78 X
57 39 9 89 59 y 121 79
58 3A 90 5A z 122 7A z
59 3B 91 5B [ 123 7B
60 3C < 92 5C \ 124 7C
61 3D 93 5D l 125 7D }
62 3E > 94 5E 126 7E
A

63 3F ? 95 5F 127 7F I DELETE I

230 Appendix C: ASCII Character Codes


Appendix D Reserved Words

231
Table D-1 lists Applesoft's reserved words. In most cases these character
sequences cannot be used as, or embedded in, variable names.
Applesoft converts all its keywords to one-byte codes, called tokens, to
save memory. Refer to Section H.4 for a list of tokens. All other characters
in a program occupy one byte each of program storage.
The ampersand character (&) is reserved for Applesoft's internal use and
for user-supplied machine-language routines. When executed as an
instruction, it causes a JSR to address $03F5 hexadecimal.
XPLOT is a reserved word that does not correspond to a current Applesoft
statement.
Some reserved words are recognized by Applesoft only in certain contexts:
□ COWR, HCOLOR, ROT, SCALE, and SPEED are interpreted as reserved
words only if the next nonspace character is an equal sign ( = ). This is of
little benefit in the case of COLOR and HCOLOR, as the embedded
reserved word OR prevents their use as variable names anyway.
□ HIMEM and LOMEM are interpreted as reserved words only if the next
nonspace character is a colon (:).
□ IN and PR are interpreted as reserved words only if the next nonspace
character is a number sign ( #).
□ SCRN, SPC, and TAB are interpreted as reserved words only if the next
nonspace character is a left parenthesis, (.
□ ATN is interpreted as a reserved word only if there is no space between
the T and the N. If a space occurs between the T and the N, the reserved
word AT is interpreted instead of ATN.
□ TO is interpreted as a reserved word unless it is preceded by an A and
there is a space between the T and the 0. In that case, the reserved word
AT is interpreted instead of TO.
Even if you don't embed reserved words in your variable names, they can
sometimes pop up unexpectedly and cause problems. For example, the
statement
1ee F O R A • L O F T O R L E F T TO 1 5
is interpreted as
1ee F O R A • LOF TO R L E F T TO 1 5
and causes a syntax error. To force the correct interpretation, use
parentheses:
1ee F O R A • ( L O F T ) OR C L E F T ) TO 1 5

232 Appendix D: Reserved Words


Table D-1. Applesoft Reserved Words

$ GET NEW SAVE


GOSUB NEXT SCALE=
ABS GOTO NORMAL SCRN(
AND GR NOT SGN
ASC NOTRACE SHLOAD
AT HCOLOR= SIN
ATN HGR ON SPC(
HGR2 ONERR SPEED=
CALL HIMEM: OR SQR
CHR$ HLIN STEP
CLEAR HOME PDL STOP
COLOR= HPLOT PEEK STORE
CONT HTAB PLOT STR$
cos POKE
IF POP TAB(
DATA IN# POS TAN
DEF INPUT PRINT TEXT
DEL INT PR# THEN
DIM INVERSE TO
DRAW READ TRACE
LEFT$ RECALL
END LEN REM USR
EXP LET RESTORE
LIST RESUME VAL
FLASH LOAD RETURN VLIN
FN LOG RIGHT$ VTAB
FOR LOMEM: RND
FRE ROT= WAIT
MID$ RUN
XPLOT
XDRAW

Appendix D: Reserved Words 233


Appendix E Error Messages

e


235
This appendix lists Applesoft's error messages and their causes. When an
error occurs in immediate execution, Applesoft sounds a beep and displays
a message of the form
?XX ERROR
where x x is the name of the particular error.
In deferred execution (during the course of a running program), the
message takes the form
? X X ERROR I H VY
where v v is the line number of the statement in which the error occurred,
the Applesoft prompt character ( ] ) and the cursor are displayed, and control
of the system is retumed t,o the user. Variable values and the text of the
program remain intact, but internal control information is erased and the
program cannot be continued with the CONT command (refer t,o
Section 1.3.3). An error in a deferred-execution statement is not detected
until the statement is executed.
The error handling described can be overridden by an error-handling
routine in the program itself, established with the ONERR GOTO statement
(refer t,o Section 3.5.1). Error codes for use in such an error-handling routine
are shown in square brackets following the error names. When an error
occurs, the code listed is soored at location 222 decimal; it can be retrieved
from that location with the PEEK function (refer t,o Section 7.1.1). Errors for
which no code is given cannot occur in deferred execution.
Errors associated with the disk operating system also register at
location 222; see the disk operating system manual for further information.
Debugging suggestions given under the individual error messages are not
intended t,o be exhaustive or comprehensive; the causes of program bugs
are as numberless as the sands of the sea and stars of the sky.

236 Appendix E: Error Messages


E . 1 Error Messages b y Number
See Section E.2 for an explanation of any error message listed below.
0 NEXT WITHOUT FOR
16 SYNTAX ERROR
22 RETURN WITHOUT GOSUB
42 OUT OF DATA
53 ILLEGAL QUANTITY
69 OVERFLOW
77 OUT OF MEMORY
90 UNDEF'D STATEMENT
107 BAD SUBSCRIPT
120 REDIM'D ARRAY
133 DIVISION BY ZERO
163 TYPE MISMATCH
176 STRING TOO LONG
191 FORMULA TOO COMPLEX
224 UNDEF'D FUNCTION
CAN'T CONTINUE
ILLEGAL DIRECT

E.2 Alphabetical List of Error Messages


See Section E.1 for a list of error messages by number.

BAD SUBSCRIPT [ 1 07]

A reference was made to an array element that is outside the dimensions of


the array. This error can occur if the wrong number of dimensions are used
in an array reference: for instance,
LET A C 1 , 1 , 1 > • Z

when A has been defined by


DIM AC2 , 2>

E.2 Alphabetical List of Error Messages 237


CAN'T CONTINUE
An att.empt was made to continue a program with the CONT command
when no program exists in memory, or after an error, or after a line has
been changed, deleted from, or added to the program.

DIVISION BY ZERO [1 33]


An attempt was made to divide by O; division by O is mathematically
undefined. Often occurs when a variable is used in an arithmetic expression
before being given a value (all numeric variables initially have the value 0).
To debug, examine the divisor of the expression where the error occurred to
see why it unexpectedly has a O value. Look particularly for variables that
have inadvertently been used without having been given a nonzero value.

FORMULA TOO COMPLEX [191]

More than two statements of the form


I F "22" T H E N
were executed (where "ZZ" is any quoted string). The Applesoft IF... THEN
statement wasn't intended to be used with strings, and the results of such
statements are not meaningful. The wisest policy is to avoid this type of
construction altogether.

ILLEGAL DIRECT
An attempt was made to use one of the following statements in immediate
execution:
□ DEF FN
□ GET
□ INPUT
□ ONERR GOTO
□ READ
□ RESUME

238 Appendix E: Error Messages


ILLEGAL QUANTITY [53]

The argument supplied to a statement or function was out of the allowed


range. This error can be caused by
□ a negative array subscript (for example, LET A (-1) = 0)
□ LOG with a negative or O argument
□ SQR with a negative argument
□ A B with A negative and B not an integer
A

□ use of LEFT$, MID$, RIGHT$, WAIT, PEEK, POKE, CALL, TAB, SPC,
ON...GOTO, ON...GOSUB, or any of the graphics statements or functions
with an improper argument.

NEXT WITHOUT FOR [O]


The variable named in a NEXT statement did not agree with the variable in
the corresponding FOR statement, or a nameless NEXT was executed when
no FOR was in effect. The most common causes of this error are forgetting a
FOR or NEXT statement, typing the wrong variable in the NEXT statement,
crossing loops, or accidentally branching into or out of the body of a FOR
loop.

OUT OF DATA [42]


A READ statement was executed after all DATA statements in the program
had already been read. A READ statement may have been executed more
times than intended (for example, in an infinite loop), or one or more DATA
statements may have been inadvertently omitted. Sometimes caused by
accidentally leaving out a RESTORE statement.

E.2 Alphabetical List of Error Messages 239


OUT OF MEMORY [77)

Any of the following can cause this error:


□ program too large
□ too many variables
□ FOR loops nested more than 10 levels deep
□ subroutine calls nested more than 24 levels deep
□ parentheses nested more than 36 levels deep
□ too complicated an expression
□ attempt to set LOMEM: too high
□ attempt to set LOMEM: lower than present value
□ attempt to set HIMEM: too low.

OVERFLOW [69)
The result of an arithmetic calculation was too large to be represented in
Applesoft's internal number format.

REDIM'D ARRAY [ 1 20)


An attempt was made to define the same array twice in the same or
different DIM statements. This error often occurs if an array has been
referred to in a statement such as
LET A C I > • 3
before being defined in a DIM statement. At first reference, the array is
automatically defined with an assumed dimension of 10; if such a statement
is followed later in the program by
DIM A ( 1 88)

the R E D I M ' D A R R A Y error results. Another common cause of the error is a


program that loops back to a line before the DIM statement, consequently
executing it a second time.
If you must define the same array twice in the same program, use CLEAR
before redefining it. Remember that CLEAR initializes all variables (refer to
Section 1.1.1). Before using CLEAR, save all essential data to disk (or to
RAM) and close any open files.

240 Appendix E: Error Messages


Locating an Array Definition: This error message can prove useful if
you wish to discover on what program line an array was defined. Just
insert a DIM statement for the array in the first line, run the program, and
the program halts with a R E D 1 M • D A R R A v error when the original DIM
statement is executed.

RETURN WITHOUT GOSUB [22]

A RETURN statement was encountered without a corresponding GOSUB


having been executed. This error often occurs when control accidentally
branches into a subroutine via a GOTO statement, or "falls into" a
subroutine because there is no END or GOTO statement at the end of the
program segment preceding the subroutine.

STRING TOO LONG [ 1 76]

An attempt was made by use of the concatenation operator ( +) to create a


string more than 255 characters long. This error tends to occur when a
string variable is used more than once without being cleared (that is,
without being reset to the null string).

SYNTAX ERROR ( 1 6]

A statement or expression doesn't conform to Applesoft's syntax rules.


There are a myriad of possible causes for this error, such as a missing
parenthesis, illegal character, or incorrect punctuation. Often results from a
simple typing error.

TYPE MISMATCH ( 1 63]


The left side of an assignment statement was a numeric variable and the
right side was a string, or vice versa; or a function that expected a string
argument was given a numeric one or vice versa. Often caused by
inadvertently leaving out the dollar sign ($) in a string variable or function
name.

E.2 Alphabetical List of Error Messages 241


UNDEF'D FUNCTION [224]

A reference was made to a function that had never been defined. Can occur
when you type something like F H L c x > when you meant to type
r H I c x > ; that is, a simple case of mistaken identifier.

UNDEF'D STATEMENT [90]

An attempt was made to transfer control, via GOTO, GOSUB, or IF ... THEN,
to a nonexistent line number. Common causes include accidentally deleting
a line, changing a line number without changing references from other lines
accordingly, and simple typing errors.

242 Appendix E: Error Messages


Appendix F Peeks, Pokes, and Calls







243
This appendix discusses some of the many special features of the Apple II
that you can use in your Applesoft programs by means of PEEK, POKE, or
CALL statements (see Sections 7.1.1, 7.1.2, and 7.1.3, respectively). Notice
that some of them duplicate the effects of other Applesoft features.
Many of these special addresses are soft switches-specific locations in
memory that produce some special effect whenever the contents are read or
written-any reference to them, whether a read (that is, a PEEK) or a write
(a POKE), invokes the feature associated with the address. For instance, the
sample given here for switching from text to graphics without clearing the
graphics screen is
P O K E - 1 63 0 4 , 0
but you can get the same effect by executing
X • P E E K C - 1 63 0 4 )
or by using POKE to address -16304 with a value other than 0. This does not
apply in cases where you must use POKE to store a specific value into the
special address, such as a margin setting or a cursor location.
For More Information: For more information on special features
accessible with PEEK, POKE, and CALL, see your Apple's reference
manual.

F. 1 Screen Text
The special locations described in this section are used for controlling the
display of text on the screen:
o setting the boundaries of the text window within which characters are
displayed and scrolled
o clearing all text from all or part of the screen
o scrolling text within the text window
o controlling the position of the cursor.
Setting the text window does not clear the remainder of the screen (for
which you can use HOME) and does not move the cursor into the new text
window (use HOME again, or HTAB and VTAB-see Section 5.2.4).

244 Appendix F: Peeks, Pokes, and Calls


F. 1 . 1 Setting the Text Window

This program lets you experiment with text windows:


1 il HOME
2 il P R I NT I I + - - - - - - - - - - - - - - - \ + II

3 il I NP U T I I I L E F T : I I ; L
4 il I NP UT I I I W I DTH : II ; w
S il I N P U T I I I TOP : II ; T
S il I N P U T II I BOTTOM : II ; B
7 il POKE 33 , W
S il P OK E 3 2 , L
S il POKE 34 , T
1 B il POKE 35 , B
1 1 " GOTO 1 B

POKE 32 L
Sets the left edge of the text window to the value specified by expression L.
This value should be between 0 and 39 (or 0 and 79 if you're using
80 columns), where 0 represents the leftmost column of the screen.
The change doesn't become visible until the cursor attempts to return to the
left edge of the window.
•Warning The width of the window is not changed by this statement: this means
that the right edge is moved by the same amount you move the left edge.
To protect your program and Applesoft, first reduce the window width
appropriately; then change the left edge.

POKE 33 W
Sets the width of the text window (number of characters per line) to the
value specified by expression W. This value should be between 1 and 40
(or 1 and 80 if you're using 80 columns).

F. 1 Screen Text 245


AWarning Make sure the right edge of the text window doesn't extend past the right
edge of the display screen. The window width shouldn't be set greater
than 40 (or 80) minus the current left edge of the window. For sample, if
you've set the left edge of the window to 10, don't set the window width
greater than 30 (or 70 if you're using 80 columns). Setting the window too
wide causes display text to be written outside the usual memory area
reserved for it, destroying parts of your program or vital system
information.
Do not set the window width to 0! The statement
POKE 33 , Ill

causes the system to crash.


If W is less than 33, the TAB function (see Section 5.2. 4.5) in a PRINT
statement may cause characters to be displayed outside the text window.

POKE 34 T
Sets the top edge of the text window to the value specified by expression T.
This value should be between 0 and 23, where 0 represents the top line of
the screen.
AWarning I Do not set the top edge of the window (T) lower than the bottom edge.

POKE 35 B
Sets the bottom edge of the text window to the value specified by
expression B. This value should be between 0 and 23, where 23 represents
the bottom line of the screen.
By the Way: No matter what you do to the left margin, width, top, and
bottom of the text window, you can quickly restore it to the full screen
with the TEXT statement.
AWarning Make sure the bottom of the text window doesn't extend past the bottom
of the display screen. Setting the window bottom beyond line 23 causes
display text to be written outside the usual memory area reserved for it,
destroying parts of your program or vital system information.
Do not set the bottom edge of the window (B) higher than the top edge.

246 Appendix F: Peeks, Pokes, and Calls


F. 1 .2 Text in Windows
These five CALLS are used to clear portions of the text window, and to
move the cursor and scroll text.

CALL -936
Clears all text within the text window and moves the cursor to the top-left
corner of the window. The effect is the same as that of the HOME statement
or of press� I Esc I [ru from the keyboard.

CALL -958
Clears all characters inside the text window from the current cursor
position to the bottom-right corner. Characters above and to the left of the
cursor are not affected. The effect is the same as that of pressing I Es c 1 1 I:]
from the keyboard.

CALL -868
Clears all characters inside the text window from the current cursor
position to the end of the line. The effect is the same as that of pressing
I ESC I (I) from the keyboard.

CALL -922
Issues a line feed character, causing the cursor to move down one line
without changing its horizontal position. If the cursor is on the bottom line
of the text window, the contents of the window are scrolled up one line. The
effect is the same as that of pressing I CONTROL HI] from the keyboard.

CALL -9 1 2
Scrolls all text within the text window up one line. The old top line is lost;
the old second line becomes the top line; the bottom line becomes blank.
Text outside the text window is not affected.

F.1 Screen Text 247


F. 1 .3 The Cursor in Windows
These PEEKs and POKEs move the cursor within the text window.

PEEK (36)
Yields the current horizontal position of the cursor, a number between 0
and 39 (0 and 79, if you're using 80 columns). The cursor position is given
relative to the left edge of the text window, not the left edge of the screen.
The effect is the same as that of the POS function (see Section 5.2.4).

POKE 36, CH
Moves the cursor to the horizontal position specified by expression CH,
which is interpreted relative to the left edge of the text window, not the left
edge of the screen. The value of this expression should be between O and
the current width of the window, with O representing the leftmost column
of the window. The effect is the same as that of the HTAB statement (see
Section 5.2.4.6), but is not limited to 40 columns.
Like HTAB, this statement can move the cursor beyond the right edge of the
text window, but only long enough to display one character.
80-Column Users: You can use this POKE statement to position the
cursor in columns 40 to 79 of the screen, which are inaccessible with
HTAB.
•Warning Don't move the cursor past the right edge of the display screen! The
cursor position shouldn't be set greater than 40 (or 80) minus the current
left edge of the window. For example, if you've set the left edge of the
window to 10, don't set the cursor position greater than 30 (or 70 with
80 columns). Moving the cursor too far to the right may cause display text
to be written outside the usual memory area reserved for it, destroying
parts of your program or vital system information.

PEEK (37)
Yields the current vertical position of the cursor, a number between 0
and 23. The cursor position is given relative to the top edge of the screen,
not the top edge of the text window. A value of O represents the top line of
the screen, 23 the bottom line.

248 Appendix F: Peeks, Pokes, and Calls


POKE 37, CV
Moves the cursor to the vertical position specified by expression CV, which
is interpreted relative to the top of the screen, not the top of the text
window. The value of this expression should be between O and 23, with 0
representing the topmost line of the screen. The effect is similar to that of
the VTAB statement (see Section 5.2.4.7), except that
□ screen lines are numbered from O to 23, not from 1 to 24 as with VTAB
□ the specified cursor position is not limited to 24 lines.
Like VTAB, this statement can move the cursor beyond the bottom edge of
the text window, but all subsequent text sent to the display screen then
appears on that same line.
•Warning Don't move the cursor past the bottom edge of the display screen! Setting
the cursor position beyond line 23 causes display text to be written
outside the usual memory area reserved for it, destroying parts of your
program or vital system information.

F.2 Keyboard
The following special locations are used for reading input directly from the
keyboard.

PEEK (·1 6384)


Reads the last character typed from the keyboard. If the high-order bit of
this location is 1 (PEEK yields a result > 127), then a new character has
been typed since the last POKE to address -16368; subtracting 128 from the
value received gives the ASCII code for the character typed. If the
high-order bit is O (PEEK yields a result < = 127), then no new character
has been typed since the last POKE to -16368.

POKE - 1 6368, 0
Clears the high-order bit of location -16384 to prepare for reading another
keyboard character. This should be done immediately after reading the
keyboard via PEEK (-16384).

F.2 Keyboard 249


F .3 Graphics

Four areas are reserved in the Apple H's memory for displaying text and
graphics on the screen:
□ Low-resolution page 1 is located at addresses $400 to $7FF hexadecimal
(1024 to 2047 decimal). Information stored in this area can be interpreted
and displayed on the screen in the form of either text or low-resolution
graphics. This is the usual area of memory used for both these purposes,
and is the area used by Applesoft's TEXT and GR statements.
□ Low-resolution page 2, at addresses $800 to $BFF hexadecimal (2048 to
3071 decimal), can be used as an alternate area for either text or
low-resolution graphics. Since this is the same area as the beginning of
Applesoft's normal program storage space (see Section H.l), using it for
text or graphics is tricky and is not recommended.
□ High-resolution page 1, at addresses $2000 to $3FFF hexadecimal
(8192 to 16383 decimal), is the usual area for high-resolution graphics,
and is accessible via Applesoft's HGR statement.
□ High-resolution page 2, at addresses $4000 to $5FFF hexadecimal
(16384 to 24575 decimal), serves as an alternate area for high-resolution
graphics, and is accessible via Applesoft's HGR2 statement.
To use the different text and graphics areas, you can use Applesoft's built-in
text and graphics facilities or you can use PEEK and POKE to manipulate
soft switch: a location in memory that the soft switches that control the display of text and graphics. There are
produces some special effect whenever its four such soft switches, each consisting of a pair of special locations in the
contents are read or written Apple II's memory. Any PEEK or POKE to one of the locations in the pair
sets the switch one way; a PEEK or POKE to the other location in the pair
sets the switch the other way.
In the following list, the addresses shown in parentheses are those of the
special locations that control the various settings of the switches. Each
address is given first in hexadecimal (preceded by a dollar sign, $) and then
in the equivalent decimal form.
The four soft switches controlling the display choose between
□ text ($C051, -16303) and graphics ($C050, -16304)
□ high ($C057, -16297) and low resolution ($C056, -16298)
□ page 1 ($C054, -16300) and page 2 ($C055, -16299)
□ full-screen graphics ($C052, -16302) and mixed text and graphics
($C053, -16301)

250 Appendix F: Peeks, Pokes, and Calls


For Further Information: For further information on these and other
soft switches in the Apple II's memory, see your Apple's reference
manual.

F .3.1 Switching Graphics Screens

These POKEs let you switch from one text or graphics mode to another.

POKE -1 6304, 0
Switches the display from full-screen text to graphics without clearing the
graphics screen. Depending on the settings of the other soft switches, the
resulting display may be high- or low-resolution graphics, taken from page 1
or 2, and full-screen graphics or mixed text and graphics.
Similar Applesoft Statements: The GR statement switches to mixed
text and low-resolution graphics from page 1 and clears the graphics
screen to black. The HGR statement switches to mixed text and
high-resolution graphics from page 1 and clears the graphics screen to
black. The HGR2 statement switches to full-screen high-resolution
graphics from page 2 and clears the entire screen to black.

POKE -1 6303, 0
Switches the display from any fonn of graphics to full-screen text without
resetting the text window. Depending on the setting of the applicable soft
switch, the text displayed may be taken from low-resolution page 1 or
page 2.
The TEXT statement also switches to text display, but in addition selects
page 1, resets the text window to the full screen, and positions the cursor in
the bottom-left corner of the screen (column 1, row 24).

POKE - 1 6302, 0
Switches the display from mixed text and graphics to full-screen graphics.
Depending on the settings of the other soft switches, the resulting display
may be either low- or high-resolution graphics and may be taken from either
page 1 or page 2. If full-screen text is currently being displayed, there is no
visible effect.

F.3 Graphics 251


POKE - 1 6301 , 0
Switches the display from full-screen graphics to mixed text and graphics,
with four lines of text at the bottom of the screen. Depending on the settings
of the other soft switches, the upper portion of the screen may show low- or
high-resolution graphics, taken from either page 1 or page 2. The text
displayed in the bottom four lines is taken from the same page number as
the graphics in the upper part of the screen. If full-screen text is currently
being displayed, there is no visible effect.

POKE -1 6300, 0
Switches the display from page 2 to page 1, without clearing the screen or
moving the cursor. Depending on the settings of the other soft switches, the
resulting display may be text or low-resolution graphics taken from
low-resolution page.1, or high-resolution graphics taken from
high-resolution page 1; if graphics, it may be either full-screen graphics or
mixed with four lines of text from low-resolution page 1.
Always execute this POKE statement before switching to Integer BASIC if
you've been using page 2 in Applesoft; otherwise you'll be left still looking
at text Oow-resolution) page 2 while Integer BASIC is writing its screen
output to page 1.

POKE - 1 6299, 0
Switches the display from page 1 to page 2, without clearing the screen or
moving the cursor. Depending on the settings of the other soft switches, the
resulting display may be text or low-resolution graphics taken from
low-resolution page 2, or high-resolution graphics taken from
high-resolution page 2; if graphics, it may be either full-screen graphics or
mixed with four lines of text from low-resolution page 2.

252 Appendix F: Peeks, Pokes, and Calls


POKE - 1 6298, 0
Switches from high- to low-resolution graphics, without clearing the screen.
Depending on the settings of the other soft switches, the resulting display
may be taken from low-resolution page 1 or page 2, and may be either
full-screen low-resolution graphics or mixed with four lines of text from the
same low-resolution page. If full-screen text is currently being displayed,
there is no visible effect.
Always execute this POKE statement before switching to Integer BASIC if
you've been using high-resolution graphics in Applesoft; otherwise Integer
BASIC's GR statement incorrectly displays the high- instead of the
low-resolution page.

POKE -1 6297, 0
Switches from low- ·to high-resolution graphics, without clearing the screen.
Depending on the settings of the other soft switches, the resulting display
may be taken from high-resolution page 1 or page 2, and may be either
full-screen high-resolution graphics or mixed with four lines of text from the
corresponding low-resolution page. If full-screen text is currently being
displayed, there is no visible effect.

F.3.2 Clearing Graphics Screens


These CALLs clear graphics pages in various ways.

CALL - 1 998
Clears low-resolution page 1 to black if displaying low-resolution graphics,
or to black-on-white at-signs (@) if displaying text. If displaying
high-resolution graphics, or text or low-resolution graphics from page 2,
there is no visible effect.

CALL - 1 994
Clears the upper 40 rows of low-resolution page 1 to black if displaying
low-resolution graphics, or the upper 20 lines to black-on-white at-signs (@)
if displaying text. If displaying high-resolution graphics, or text or
low-resolution graphics from page 2, there is no visible effect.

F.3 Graphics 253


CALL -3086
Clears the current high-resolution page t,o black. (Applesoft remembers
which page you used last, regardless of the switch settings.)

CALL -3082
Clears the current high-resolution page t,o the color most recently used in an
HPLOT statement. (Applesoft remembers which page you used last,
regardless of the switch settings.)

F.4 Miscellaneous Input and Output

This section describes the special locations in the Apple II's memory for
controlling a variety of input and output devices:
□ reading the butrons on the hand controls
□ controlling the annunciaror outputs and the utility strobe
□ producing sounds through the built-in speaker.

F .4. 1 Hand Controls and Strobe


Three PEEKs read the status of the hand control butrons. Another PEEK
triggers the utility strobe.

PEEK (-1 6287)


Reads the butt.on on hand control O; yields a result > 127 if the butt.on is
being pressed, < = 127 if it is not. The @] key on the Apple Ile and
Apple Ile keyboards is equivalent t,o this butt.on and can be read in the same
way.

PEEK (-1 6286)


Reads the butt.on on hand control I; yields a result > 127 if the butt.on is
being pressed, < = 127 if it is not. The [!) key on the Apple Ile and
Apple Ile keyboards is equivalent t,o this butt.on and can be read in the same
way.

254 Appendix F: Peeks, Pokes, and Calls


PEEK (-1 6285)
Reads the button on hand control 2; yields a result > 127 if the button is
being pressed, < = 127 if it is not.
Note: Although there are provisions for connecting four hand controls
(numbered O to 3) to the computer, there is no way to read the button on
hand control 3.

PEEK (-1 6320)


Triggers the utility strobe (hand control connector, pin 5). This does not
apply to the Apple Ile.
The utility strobe should always be controlled with PEEK, not with POKE.
Using POKE triggers the strobe twice instead of once. See your Apple's
reference manual for further information.

F.4.2 Annunciators
These eight POKEs control the annunciator output on hand control
connectors.
Notfor Ile Users: The Apple lie doesn't have easily-accessible
annunciators. Apple lie users can safely dispense with reading the next
eight entries, but note that the locations discussed, POKE locations -16295
through -16290, are used by the system. They are generally not free
locations.
What's an Annunciator? The annunciators are four pins of the hand
control connector that can each be set to either of two states (on or off) in
the Apple II, Apple II Plus, and Apple lie. The utility strobe is another pin
of the connector that is normally at +5 volts but can be triggered to drop
to 0 volts for one-half microsecond. These features are typically used to
control devices such as lamps and relays connected to the computer
through the hand control connector. See your Apple's reference manual
for further information.

POKE -1 6295, 0
Turns on annunciator output 0 (hand control connector, pin 15).

F.4 Miscellaneous Input and Output 255


POKE -1 6296, 0
Tums off annunciator output O (hand control connector, pin 15).

POKE -1 6293, 0
Tums on annunciator output 1 (hand control connector, pin 14).

POKE -1 6294, 0
Tums off annunciator output 1 (hand control connector, pin 14).

POKE - 1 629 1 , 0
Tums on annunciator output 2 (hand control connector, pin 13).

POKE - 1 6292, 0
Tums off annunciator output 2 (hand control connector, pin 13).

POKE -1 6289, 0
Tums on annunciator output 3 (hand control connector, pin 12).

POKE -1 6290, 0
Tums off annunciator output 3 (hand control connector, pin 12).

F.4.3 Loudspeaker
These PEEKs produce audible clicks.

PEEK (-1 6336)


Produces a single click from the built-in speaker; can be used in various
combinations and frequencies to produce musical tones and other sounds.
The speaker should always be controlled with PEEK, not with POKE. Using
POKE produces two clicks instead of one. See your Apple's reference
manual for further information.

256 Appendix F: Peeks, Pokes, and Calls


PEEK (-1 6352)
Produces a single click on a cassette recording or on an audio amplifier
connected to the cassette output jack via the amplifier's auxiliary input
jack; can be used in various combinations and frequencies to produce
musical tones and other sounds. See Appendix M for further information on
using a cassette recorder. (This does not apply to the Apple Ile.)
Cassette output should always be controlled with PEEK, not with POKE.
Using POKE produces two clicks instead of one. See your Apple's reference
manual for further information.

F .5 Error Handling

This section describes the special locations associated with Applesoft's


error-handling mechanism. They can be used by user-supplied
error-handling routines established with the ONERR GOTO statement. See
Section 3.5 and Appendix E for further information.

PEEK (21 6)
Yields a result > 127 if an error-handling routine has been established with
the ONERR GOTO statement, < = 127 if normal error handling is in effect.

POKE 2 1 6 0
Restores Applesoft's normal error-handling mechanism; cancels the effect
of a previous ONERR GOTO statement.

PEEK (222)
After an error-handling routine has been called, yields the error code
identifying the type of error detected. See Appendix E and Table 3-1
(Section 3.5.1) for further information on error codes.
Errors associated with the disk operating system also register at
location 222; see the disk operating system manual for further information.

PEEK (2 1 9) * 256 + PEEK (21 8)


After an error-handling routine has been called, this expression yields the
line number of the statement in which the error was detected.

F.5 Error Handling 257


CALL -3288
Clears from Applesoft's internal control stack information placed there
when an error-handling routine was called. Should be used before exiting
from any error-handling routine with a GOTO instead of a RESUME
statement.

CALL 549 1 5
Empties the internal control stack of all control information, without
affecting the contents of any variables.

258 Appendix F: Peeks, Pokes, and Calls


Appendix G Hints for Program Efficiency

..

259
The information in this appendix can help you write programs that run
faster or use less memory space.
□ Section G.l, "Saving Space," gives tips you can follow if you need to
conserve memory space.
□ Section G.2, "Saving Time," suggests ways to speed up program
execution.

G . 1 Saving Space
Serious programmers often keep two versions of their programs: one
expanded and heavily documented with REM statements, the other
"crunched" to use the minimum memory space. There are a number of
utility programs on the market that will make Applesoft programs more
compact. They work by automatically removing REM statements,
combining several statements onto a single program line, and eliminating
optional semicolons in PRINT lists. Here are some tips for programmers who
prefer to do the work themselves:
□ Use multiple statements per line. There is a small amount of overhead
(five bytes) associated with each line in the program. Two of these bytes
contain the line number. This means that no matter how many digits you
have in your line number (minimum line number is 0, maximum
is 63999), it takes the same number of bytes (two). Putting as many
statements as possible on each line cuts down on the number of bytes
used by your program. (A single line can include up to 239 characters.)
When combining statements into fewer lines, remember that when the
condition in an IF...THEN statement is false, execution continues with
the next line and not necessarily with the next statement.
If you're counting bytes, remember to add in one byte for each colon used
to separate statements.
The Disadvantages: Combining many statements on one line makes
editing and other changes much more difficult. It also makes a program
more difficult to read and understand, not only for others but also for you
yourself when you return to the program later on. Use this technique only
in programs with serious space limitations.

260 Appendix G: Hints for Program Efficiency


Delete all REM statements. Each REM statement uses at least one byte (for
the keyword REM itself), plus one byte for each character in the text of the
remark. For instance, the statement
R E M TH I S I S A R E M A R K
occupies 18 bytes of memory. In the program line
148 X • X + V : R E M UPDATE S U M
the REM uses 12 bytes of memory, plus one for the colon separating it from
the preceding statement.
Take care not to delete REM lines that are referred to by other lines. For
example, if your program includes the lines
2 C BB B GOTO 3 8 8

388 R E M TH I S I S THE H E X T R O UT I H E
and you delete line 300, the program halts with an U H D E F • D STATE M E H T
error.
The Di,sadvantages: Like programs with many statements on each line,
those without detailed REM statements are difficult to read and
understand, not only for others but also for you yourself when you return
to the program later on. You should consider eliminating REM statements
only when faced with a serious shortage of memory space.
o Use integer instead of real arrays wherever possible (see Section H.2).
o Use variables instead of constants. Suppose you use the constant 3.14159
ten times in your program. If you insert a statement
P I • 3 . 1 4 1 59
and then use the variable PI instead of the constant 3.14159 each time it
is needed, you save 40 bytes. This also results in a speed improvement.
o Applesoft programs need not end with an END statement, so you can
save a little space by omitting it.
o Reuse the same variables. If you use a variable T to hold a temporary
result in one part of the program and you need a temporary variable later
in your program, use T again. Or if you're accepting a one-character input
from the user in two different places in the program, use the same
variable both times.

G.l Saving Space 261


□ Use subroutines and functions when the same action must be performed
at different places in the program, to avoid having to write the identical
code more than once.
□ Use the zero elements of arrays-such as A(O) or B(O,X)-since space is
allocated for them anyway.
□ Semicolons are optional before and after TAB calls; leaving them out
saves one byte per occurrence.
□ Semicolons between items in a PRINT list are optional as long as the
separate items are unambiguous. For instance, in line 50 of the following
example all items are displayed separately (although concatenated),
since the dollar signs at the ends of the string variable names make it
clear they are three separate variables:
18 L ET A $ • " W E L L , I I
2 11 L E T B S • " M A R S H A , II
3 11 L E T C S - II I T L O O K S L I K E II

◄ II L E T C • 1 11
S Ii P R I NT A $ B $ C $ " F R E D I s II
C II
HOURS
L A TE ! "
This program displays
W E L L , M A R S H A , I T L O O K S L I K E F R E D I S 1 11 H O U R S LATE !
But in this example several of the variables are run together and
interpreted as a single name:
1 11 LET A • 5
2 11 L E T B • 1 11
3 11 LET C% • 1 5
◄ II L E T D • 1 11
S Ii P R I NT A B e x D
Applesoft interprets line 50 as saying "display the value of integer
variable ABC%, followed by the value of real variable D," and displays
11 1 11
Since variable ABC% hasn't been assigned a value, its value is 0.
□ If a quoted string is the last item in the last statement of a line, the
closing quotation mark can be omitted, saving one byte:
1 11 P R I NT "TH I S I S T H E W A Y THE W O � L D
E N Di ,
2 11 P R I NT " N O T W I TH A BANG BUT A W H I MP E R

262 Appendix G : Hints for Program Efficiency


A Caution: This last technique should be used with caution. Bad things
can happen if the omitted quotation mark comes somewhere other than
at the end of a line:
11 P R I NT "TH I S W O N ' T W O R K : P R I NT "VE R Y
WELL
This line displays
TH I S W O N ' T W O R K : P R I NT I
The final O is the value of the undefined variable VERYWELL.

G.2 Saving Time

Utility programs called compilers are now available that convert Applesoft
programs to a form in which they run far faster than normally. However, a
compiled program can take as much as 50 percent more space than a
noncompiled one. The following hints should improve the execution speed
of your Applesoft programs. Notice that some of these same hints were
given in Section G.1 to save memory space. This means that in many cases
you can both shorten and speed up your programs at the same time.
□ This hint is probably ten times more important than any other in the list:
use real variables wherever possible instead ofinteger variables or
constants. It takes more time to convert an integer to its real-number
representation than to fetch the value of a real variable. This technique
is especially important within subroutines, loops, and other program
segments that are executed repeatedly.
□ Space for variables is allocated in the variable table in the order in which
they are encountered during the execution of the program. A line such as
5 A • I : B • A : C • B
places A first in the variable table, B second, and C third (assuming this
line is the first executed in the program). When these variables are
referred to later in the program, Applesoft has to search only one entry in
the variable table to find A, two entries to find B, and three entries to
find C. Try to arrange for those variables that your program refers to
most often to be located as early as possible in the variable table.

G.2 Saving Time 263


o Omit the index variable in NEXT statements. The statement
NEXT
is somewhat faster than
N E XT I
because no check needs to be made to see whether the variable named in
the NEXT statement agrees with the index variable named in the
corresponding FOR statement.
□ When Applesoft encounters a backward reference from a later line of the
program to an earlier one, such as
9 81! GOTO 1 1Hl
it scans the entire program from the beginning until it finds the desired
line number (100, in this example). So you can speed things up by
placing frequently-referenced lines as early in the program as possible.

264 Appendix G: Hints for Program Efficiency


Appendix H Implementation Details

265
This appendix contains information on various details of Applesoft's
internal operation.
□ Section H.1, "Apple II Memory Map," summarizes the use of memory in
the Apple II and identifies areas of memory reserved for system use.
□ Section H.2, "Applesoft Memory Allocation," describes the way Applesoft
allocates memory for program and variable storage.
□ Section H.3, "Zero Page Use," details Applesoft's use of special locations
in page zero of the Apple II's memory.
□ Section H.4, "Keyword Tokens," lists the internal codes Applesoft uses to
represent keywords occurring in a program.

266 Appendix H: Implementation Details


H.1 Apple II Memory Map
Table H-1 summarizes memory use in the Apple IL Addresses preceded by a
dollar sign ($) are in hexad�irnal; they are followed on the next line by
their decimal equivalents.

Table H-1. Apple II Memory Use

Memory
Range
From To Used For
$0000 $01FF System workspace; not advisable to use
0 511
$0200 $02FF Keyboard character buffer
51 2 767
$0300 $03CF Available for short machine-language programs
768 975
$03D0 $03FF Used by DOS and ProDOS
976 1023
$0400 $07FF Low-resolution graphics and text display, page 1
1024 2047
$0800 0BFF Low-resolution graphics and text display, page 2
2048 3071
$0800 $0XXX Applesoft program and variable space, where
XXX is the setting of HIMEM:
2048 XXX
$2000 $3FFF High-resolution graphics display, page 1
8192 16383
$4000 $5FFF High-resolution graphics display, page 2
16384 24575
$9600 $BFFF DOS
38400 49151
$COOO $CFFF Hardware 1/0 addresses
49152 53247
$D000 $F7FF Applesoft
53248 63487
$F800 $FFFF Apple II system Monitor
63488 65535

H.l Apple II Memory Map 267


H.2 Applesoft Memory Allocation
Figure H-1 shows how Applesoft allocates the memory space between the
start of program storage (normally $800 hexadecimal, 2048 decimal) and
the end of variable storage (determined by the setting of HIMEM: ). The
boundaries between areas may vary; the left column gives pointer
addresses at which the current settings of the boundaries can be found.

Figure H-1. Applesoft Memory Map

st,art of program
$0067 - $0068
103 - 104 --. - normally
$0800 (2048)

PROGRAM
end of program
$00AF - $00B0
175 - 176
st,art of variables
$0069 - $006A (LOMEM:)
105 - 106 SIMPLE
VARIABLES

st,art of arrays
$006B - $006C
-
107 - 108

-
ARRAYS
end of variables
$006D - $006E
109 - 110

FREE SPACE

st,art of strings
$006F - $0070
1 1 1 - 112
STRINGS
end of strings (HIMEM:)
$0073 - $0074
1 15 - 116

268 Appendix H: Implementation Details


Pointer addresses are given in hexadecimal first, followed by their decimal
equivalents. All pointers are stored with the low-order byte first. Thus; for
example, the address of the beginning of string space can be calculated with
the Applesoft expression
P E E K ( 1 1 2 > * 256 + PEEK C 1 1 1 )
Table H-2 shows how space is allocated for individual variables and arrays.
Simple real, integer, or string variables use seven bytes each. Real variables
use two bytes for the variable name and five for the value (one exponent,
four mantissa, most significant first). Integer variables use two bytes for the
".ariable name, two for the value, and have zeros in the remaining three
bytes. String variables use two bytes for the variable name, one for the
length of the string, two for a pointer to the contents of the string in
memory, and have zeros in the remaining two bytes.
Real arrays use a minimum of twelve bytes: two bytes for the array name,
two for the size of the array in bytes, one for the number of dimensions, two
for each dimension, and five for each element of the array. Integer array
variables use only two bytes for each element. String array variables use
three bytes for each element: one for the length of the string and two for a
pointer to it.s contents. Multidimensional arrays are stored with the first
subscript varying fastest.
String variables and arrays contain pointers (addresses) to the contents of
the strings themselves, which are stored in order of creation from
HIMEM: down, using one byte of memory for each character in the string.
The pointer stored with the variable gives the address of the first character
in the string.
When a new function is defined by a DEF FN statement, six bytes are used
to store the pointer to the definition.
Reserved words occurring in a program are converted into one-byte tokens
(see Section H.4. All other characters in a program occupy one byte of
program storage each.
As a program is executed, space is allocated on the internal control stack as
follows:
□ Each active FOR/NEXT loop uses 16 bytes.
□ Each active subroutine (one that has been called and has not yet
returned) uses 6 bytes.
□ Each pair of parentheses encountered in an expression uses 4 bytes.
□ Each temporary result calculated in an expression uses 12 bytes.

H.2 Applesoft Memory Allocation 269


Table H-2. Variable and Array Maps

Simple Variables

Real Integer String Pointers


NAME NAME NAME
(pos) 1st byte (neg) 1st byte (pos) 1st byte
(pos) 2nd byte (neg) 2nd byte (neg) 2nd byte
exponent: 1 byte high byte length: 1 byte
mantissa: m.s. byte t low byte address: low byte
mantissa 0 address: high byte
mantissa 0 0
mantissa: Ls. byte :j: 0 0

Array Variables

Real Integer String Pointers


NAME NAME NAME
(pos) 1st byte (heg) 1st byte (pos) 1st byte
(pos) 2nd byte (neg) 2nd byte (neg) 2nd byte
OFFSET pointer to next OFFSET pointer to next OFFSET pointer to next
variable: add to address variable: add to address variable: add to address
of this variable name of this variable name of this variable name
low byte low byte low byte
high byte high byte high byte
NO. OF DIMENSIONS NO. OF DIMENSIONS NO. OF DIMENSIONS
1 byte 1 byte 1 byte
SIZE Nth DIMENSION SIZE Nth DIMENSION SIZE Nth DIMENSION
high byte high byte high byte
low byte low byte low byte
SIZE 1st DIMENSION SIZE 1st DIMENSION SIZE 1st DIMENSION
high byte high byte high byte
low byte low byte low byte
REAL (0,0... 0) INTEGER% (0,0...0) STRING$ (0,0...0)
exponent: 1 byte high byte length: 1 byte
mantissa: m.s.byte low byte address: low byte
mantissa address: high byte
mantissa
mantissa: Ls.byte

270 Appendix H: Implementation Details


Table H-2-Continued. Variable and Array Maps
Real Integer String Pointers
REAL (N,N ...N) INTEGER% (N,N ... N) STRING$ (N,N ... N)
exponent: 1 byte high byte length: 1 byte
mantissa: m.s.byte low byte address: low byte
mantissa address: high byte
mantissa
mantissa: l.s.byte
t rn.s. = most significant
:j: Ls. = least significant

H.3 Zero Page Use


Table H-3 shows the locations that Applesoft uses in page zero of memory
(locations $0000 through $00FF hexadecimal). Addresses are given first in
hexadecimal, then in decimal. All pointers (memory addresses) are stored
in the usual 6502 style, low-order byte first. To find the value of a pointer,
use the Applesoft expression
P E E K C S E C MDADDR > * 2 5 6 + P E E K C F I R STADDR >
where FIRSTADDR and SECNDADDR are the addresses of the two bytes of
the pointer itself.

Table H-3. Applesoft Zero Page Use


Locations Used For
$0000 - $0005 Jump instructions to continue in Applesoft
0-5
$000A - $0000 Jump instruction for USR function (see Section 7.1.4)
10 - 12
$000D - $0017 General purpose counters/flags for Applesoft
13 - 23
$0020 - $004F Reserved for system Monitor program
32 - 79
$0050 - $0061 General purpose pointers for Applesoft
80 - 97

H.3 Zero Page Use 271


Table H-3-Continued. Applesoft Zero Page Use

Locations Used For


$0062 - $0066 Result of last multiplication or division
98 - 102
$0067 - $0068 Pointer to beginning of program; normally set to $0801
103 - 104
$0069 - $006A Pointer to start of simple variable space; also points to the
105 - 106 end of the program plus 1 or 2, unless changed with the
LOMEM: statement
$006B - $006C Pointer to start of array space
107 - 108
$006D - $006E Pointer to end of array space
109 - 110
$006F - $0070 Pointer to start of string start; strings are stored from here
111 - 112 to value of HIMEM:
$0071 - $0072 General pointer
113 - 114
$0073 - $007 4 Highest location in memory available to Applesoft
115 - 116 plus l;on initial entry to Applesoft, set to the highest RAM
memory location available
$0075 - $0076 Line number of line currently being executed
117 - 118
$0077 - $0078 "Old line number" at which execution was interrupted by
119 - 120 END, STOP, or �
$0079 - $007A "Old text pointer"; location in memory of statement to be
121 - 122 executed next
$007B - $007C Line number of DATA statement containing next item for
123 - 124 READ
$0070 - $007E Absolute memory location of next item for READ
125 - 126
$007F - $0080 Pointer to current source of INPUT; set to $0201 during an
127 - 128 INPUT statement; during a READ statement is set to the
DATA item being read

272 Appendix H: Implementation Details


Table H-3-Continued. Applesoft Zero Page Use

Locations Used For


$0081 - $0082 Name of last-used variable
129 - 130
$0083 - $0084 Pointer to value of last-used variable
131 - 132
$0085 - $009C General usage
133 - 156
$009D - $00A3 Main floating-point accumulator
157 - 163
$00A4 General use in floating-point arithmetic
164
$00A5 - $00AB Secondary floating-point accumulator
165 - 171
$00AC - $00AE General usage flags/pointers
172 - 174
$00AF - $00B0 Pointer to end of program (not changed by LOMEN:)
175 - 176
$00B1 - $00C8 Character input routine; Applesoft calls here every time it
177 - 200 wants another character
$00B8 - $00B9 Pointer to last character obtained through character input
184 - 185 routine
$00C9 - $00CD Random number
201 - 205
$00DO - $00D5 High-resolution graphics scratch pointers
208 - 213
$00D8 - $00DF ONERR pointers/scratch
216 - 223
$00E0 - $00E2 High-resolution graphics horizontal and vertical
224 - 226 coordinates

H.3 Zero Page Use 273


Table H-3-Continued. Applesoft Zero Page Use

Locations Used For


$00E4 High-resolution graphics color code
228
$00E5 - $00E7 General use for high-resolution graphics
229 - 231
$00E6 Current high-resolution page being drawn on (decimal 32 if
230 page 1; decimal 64 if page 2)
$00E8 - $00E9 Pointer to beginning of shape table
232 - 233
$00FO - $00F3 General-use flags
240 - 243
$00F4 - $00F8 ONERR pointers
244 - 248

H.4 Keyword Tokens


Applesoft converts all its keywords to one-byte codes, called tokens, to save
memory space. Table H-4 is a list of the tokens representing the various
keywords.

Table H-4. Applesoft Keyword Tokens

Hex Dec Keyword Hex Dec Keyword


$80 128 END $8D 141 PLOT
$81 129 FOR $8E 142 HLIN
$82 130 NEXT $BF 143 VLIN
$83 131 DATA $90 144 HGR2
$84 132 INPUT $91 145 HGR
$85 133 DEL $92 146 HCOLOR=
$86 134 DIM $93 147 HPLOT
$87 135 READ $94 148 DRAW
$88 136 GR $95 149 XDRAW
$89 137 TEXT $96 150 HTAB
$8A 138 PR# $97 151 HOME
$8B 139 IN# $98 152 ROT=
$8C 140 CALL $99 153 SCALE=

274 Appendix H: Implementation Details


Table H-4-Continued. Applesoft Keyword Tokens
Hex Dec Keyword Hex Dec Keyword
$9A 154 SHLOAD $C3 195 SPC
$9B 155 TRACE $C4 196 THEN
$9C 156 NOTRACE $C5 197 AT
$9D 157 NORMAL $C6 198 NOT
$9E 158 INVERSE $C7 199 STEP
$9F 159 FLASH $CB 200 +
$AO 160 COLOR= $C9 201
$Al 161 POP $CA 202 •
$A2 162 VTAB $CB 203 {
$A3 163 HIMEM: $CC 2tl4
$A4 164 LOMEM: $CD 205 AND
$A5 165 ONERR $CE 206 OR
$A6 166 RESUME $CF 207 >
$A7 167 RECALL $DO 208
$A8 168 STORE $DI 209 <
$A9 169 SPEED= $D2 210 SGN
$AA 170 LET $D3 211 INT
$AB 171 GOTO $D4 212 ABS
$AC 172 RUN $D5 213 USR
$AD 173 IF $D6 214 FRE
$AE 174 RESTORE $D7 215 SCRN
$AF 175 & $08 216 PDL
$BO 176 GOSUB $D9 217 POS
$Bl 177 RETURN $DA 218 SQR
$B2 178 REM $DB 219 RND
$B3 179 STOP $DC 220 LOG
$B4 180 ON $DD 221 EXP
$B5 181 WAIT $DE 222 cos
$B6 182 LOAD $EF 223 SIN
$B7 183 SAVE $E0 224 TAN
$BB 184 DEF $El 225 ATN
$B9 185 POKE $E2 226 PEEK
$BA 186 PRINT $E3 227 LEN
$BB 187 CONT $E4 228 STR$
$BC 188 LIST $E5 229 VAL
$BD 189 CLEAR $E6 230 ASC
$BE 190 GET $E7 231 CHR$
$BF 191 NEW $ES 232 LEFT$
$CO 192 TAB $E9 233 RIGHT$
$Cl 193 TO $EA 234 MID$
$C2 194 FN

H.4 Keyword Tokens 275


Appendix I Display Formats for Numbers


277
This appendix describes the fonnats in which Applesoft displays or prints
numeric values. Numbers may not always be fonnatted in the way you
might expect; this is particularly true for numbers more than nine digits
long or for exceptionally small numbers.
Numeric values in Applesoft must be in the range -1*10 38 to 1•10 38. Any
A A

number whose absolute value is less than approximately 3*10 -39 is


A

converted to 0. True integer values to be assigned to integer variables (such


as A%) must be in the range -32767 to +32767.
A number typed from the keyboard or a numeric constant used in an
Applesoft program can have as many as 38 digits. However, only 9 digits are
significant, and the last digit is rounded off. An Applesoft statement that
you type as
PR I NT 1 . 2345678765432 1

displays
1 . 23456788

on the screen.
Integers are always converted to real fonn before being used in arithmetic
calculations, and the results are converted back to integer fonn when
assigned to an integer variable. Conversion from real to integer fonn is by
truncation to the next lower integer, not by rounding.
Applesoft displays and prints numbers according to the following rules:
o If the number is negative, it is preceded by a minus sign (-); if it is O or
positive, no sign is used.
□ If the number is an integer with an absolute value from O to 999 999 999,
it is fonnatted as an integer.
□ If the number is not an integer and its absolute value is between .01 and
999 999 999.2, it is fonnatted with a decimal point in the usual way.
o In all other cases, the number is fonnatted in scientific notation.

278 Appendix I: Display Formats for Numbers


Table 1-1 shows examples of the formats used for displaying and printing
numbers.

Table J.J. Number Formats

Number Output Fonnat


+1 1
-1 -1
6523 6523
-23.460 -23.46
45.72 • 10 5 4572000
1 • 10 � 20 1E+20
-12.34567896 • 10 10 -l.2345679E+ 1 1
1000000000 1E+09
999999999 999999999

The format Applesoft uses for scientific notation is shown in Figure 1-1.

Figure I-1. Format for Scientific Notation


sign exponent symbol

I
SX .
I
X X X X X X X X E SDD

each x is a digit

sign of exponent
digits of exponent

Appendix I: Display Formats for Numbers 279


A sign is shown only if the number is negative. There is always exactly one
nonzero digit before the decimal point and up to eight digits after it, with
trailing zeros suppressed. There are never any leading zeros; the digit before
the decimal point is always nonzero. If there is only one digit to print after
all trailing zeros are suppressed, no decimal point is shown. The letter E (for
exponent) is always followed by a sign and a two-digit exponent. The value
of a number represented in this form is the number before the E times 10
raised to the power after the E.
For example,
P R I NT 3 5 * 3 4 5 A 14 yields 1.18450085E+37
P R I NT - 3 . 1 4 1 5 9 * 5 6 7A 5 yields l.84104669E+ 14
P R I NT 1 / 999 yields 1.00lOOlE-03
P R I NT -3 / 999 yields -3.003003E-03

280 Appendix I: Display Formats for Numbers


Appendix J On-Screen Editing and Cursor Control

281
The figures and tables on the following pages summarize Applesoft's
facilities for on-screen editing and cursor control. These features are
discussed briefly in Section 1.4, "Editing What You Type," and at greater
length in your Apple's owner's manual and theApplesoft Tutorial.
80-Column Users: If your model has 80-column display capabilities,
additional escape-mode features are available. If you have an Apple Ile
80-Column Text Card, see the manual that came with it. If you are an
Apple Ile owner, you can find the information in your owner's manual.

Figure J-1. Single Cursor Moves

Figure J-2. Long-Range Cursor Moves


Note: Does not apply to original Apple II.

282 Appendix J: On-Screen Editing and Cursor Control


Table J-1. ASCII Equivalents of Arrow Keys
Note: Table applies to Apple Ile and Apple Ile only.

Key ASCII Code Keyboard Equivalent

G 8 �
El 21 �
III 11 �
ill 10 i CONTROL I-QJ

Table J-2. Escape-Mode Functions


Note: Table applies to Apple Ile and Apple Ile only.

Key Function

[II Moves cursor right one position; leaves escape mode


[[) Moves cursor left one position; leaves escape mode
[ID Moves cursor down one line; leaves escape mode
[[) Moves cursor up one line; leaves escape mode
[D Moves cursor up one line; remains in escape mode
QJ Moves cursor left one position; remains in escape mode
!Kl Moves cursor right one position; remains in escape mode
[0 Moves cursor down one line; remains in escape mode
G Moves cursor left one position; remains in escape mode
El Moves cursor right one position; remains in escape mode
III Moves cursor up one line; remains in escape mode
ill Moves cursor down one line; remains in escape mode
[[I Clears from cursor to end of line; leaves escape mode
II) Clears from cursor to end of screen; leaves escape mode
00 Clears entire screen; moves cursor to top-left comer;
leaves escape mode
I CONTROL H (I Enables display of control characters
� Disables display of control characters

Appendix J: On-Screen Editing and Cursor Control 283


Appendix K 40 /80-Column Display Differences

•O

285
The following table summarizes the differences in the Apple Ile's behavior
with and without the Apple I le 80-Column Text Card installed. Notice that
even 40-column display behaves somewhat differently with the 80-Column
Text Card installed and active than without it. See the BO-Column Text
Card Manual for further information.

Table K-1. 40/80-Column Display Differences

Escape Mode Inverse Inverse Home Flash Comma HTA.B


Tabbing
Card Checkerboard Uppercase Clears text Uppercase Available Available
Inactive: cursor characters window characters
40-Column only to black: only
Display characters
displayed in
inverse
Plus-sign Upper- and Clears text Not available Available Available
Card Active:
40-Column cursor; lowercase window •••
Display additional to white; DO NOT USE
escape-mode characters
features displayed
available in black
Card Active: Plus-sign Upper- and Clears text Not available Not available Not available
SO-Column cursor; lowercase window ••• for second for second
Display additional to white; DO NOT USE 40 columns 40 columns;
escape-mode characters use
features displayed POKE 36, XX
available in black

286 Appendix K: 40/80-Column Display Differences


Appendix L Comparison With Integer BASIC

287
This appendix summarizes the differences between Applesoft BASIC and
Apple's earlier Integer BASIC language. Section L.3 gives some hints on
converting programs written in Integer or other versions of BASIC to
Applesoft.
Applesoft BASIC can be used with two Apple disk operating systems:
DOS 3.3 and ProDOS. ProDOS does not support Integar BASIC. If you must
use Integer BASIC, you must use DOS 3.3. If you're using ProDOS only, you
can disregard this appendix.
IfInteger BASIC is loaded into your computer's memory, you can
switch from Applesoft to Integer BASIC by typing the command
I HT
To switch from Integer BASIC to Applesoft, type
FP
FP stands for floating-point, the name for the internal format used by
languages like Applesoft to represent real numbers.

288 Appendix L: Comparison With Integer BASIC


L. 1 Differences Between Features

Table L-1 lists Applesoft statements and functions that are not available in
Integer BASIC.

Table L-1. Applesoft Features Not Available in Integer BASIC

ATN INT SCALE=


INVERSE SHWAD
CHR$ SIN
cos LEFT$ SPC
LOG SPEED=
DATA LOMEM: SQR
DEF FN STOP
DRAW MID$ STORE
STR$
EXP NORMAL
TAN
FLASH ON ... GOSUB
FN ON ... GOTO USR
FRE ONERR GOTO
VAL
GET POS
WAIT
HCOWR= READ
HGR RECALL XDRAW
HGR2 RESTORE
HIMEM: RESUME
HOME RIGHT$
HPWT ROT=
Table L-2 lists Integer BASIC statements and functions that are not
available in Applesoft.

Table L-2. Integer BASIC Features Not Available in Applesoft

AUTO
DSP
MAN
MOD

L.l Differences Between Features 289


Table L-3 lists Applesoft features that are expressed or accomplished
differently in Integer BASIC.

Table L-3. Applesoft Features Expressed Differently in Integer BASIC

Applesoft Integer BASIC


CLEAR CLR
CONT CON
HTAB TAB
ON X GOTO 100, 1 10, 120 GOTO 100 + lO * X
ON X GOSUB 1000, 1 100, 1200 GOSUB 1000 + 100 • X
HOME CALL -936
INVERSE POKE 50, 127
NORMAL POKE 50, 255
FLASH POKE 50, 63
X% (integer variable) X
< > or > < #

L.2 Other Differences


As the name implies, the only numbers Integer BASIC can deal with are
integers (whole numbers). Real variables and constants (numbers with
decimal points or exponents) are available in Applesoft but not in Integer
BASIC.
In Integer BASIC, the correctness of a statement's syntax is checked when
the statement is typed (when you press I RETURN D. In Applesoft, such
checking is not done until the statement is executed.
Integer BASIC permits the line number in a GOTO or GOSUB statement to
be specified by an arithmetic variable or expression; in Applesoft they may
be specified only by an actual line number. In Applesoft, only the first two
characters in a variable name are significant (for example, GOOD and
GOUGE are recognized as the same variable). In Integer BASIC, all
characters in a variable name are significant.
String operations are clifferently defined in the two languages. In Integer
BASIC, both strings and arrays must be defined in a DIM statement; in
Applesoft, only arrays must be so defined.
Applesoft arrays can be multidimensional; Integer BASIC arrays are limited
to one dimension. There are no string arrays in Integer BASIC.

290 Appendix L: Comparison With Integer BASIC


Applesoft automatically sets all array elements to O or the null string on
executing RUN or CLEAR. In Integer BASIC, your program must explicitly
set all array elements to their initial values.
In Integer BASIC, if the condition specified in an IF ... THEN statement is
false, only the THEN portion of that statement is skipped. In Applesoft, all
statements following the keyword THEN on the remainder of the same
program line are skipped; program execution proceeds with the next
numbered line.
In Applesoft, the TRACE statement displays the line number of each
individual statement executed; in Integer BASIC, the line number is
displayed just once for each program line.
In Applesoft, PEEK, POKE, and CALL can use the true range of memory
addresses (0 to 65535). In Integer BASIC, locations with addresses greater
than 32767 must be referred to by their corresponding negative values
(location 32768 is called -32767-1; 32769 is called -32767; 32770 is called
-32766; and so on).
If control reaches the last line of an Integer BASIC program without an END
statement having been executed, an error message is displayed; in
Applesoft, the END statement at the end of a program is optional.
In Integer BASIC, every NEXT statement must include a variable name; in
Applesoft, the variable name is optional.
In the Integer BASIC INPUT statement, the string representing the optional
prompting message is followed by a comma, not a semicolon as in Applesoft.
If the first variable in the INPUT list is an arithmetic (integer) variable, a
question mark (?) is displayed whether the optional prompting string is
present or not; if the first variable in the list is a string variable, no question
mark is displayed, again whether the prompting string is present or not. In
Applesoft, the question mark is displayed only if no prompting string is
specified.

L.3 Converting BASIC Programs to Applesoft


Although different versions of BASIC are generally similar, there are some
incompatibilities that you should know about if you're planning to convert
programs to Applesoft from Integer or other versions of BASIC. Here are
some things to watch for:

L.3 Converting BASIC Programs to Applesoft 291


□ Some versions of BASIC use square brackets [ ] to denote array
subscripts; Applesoft uses parentheses ( ).
□ Many versions of BASIC require that you define the lengths of all strings
in DIM statements before you use them. In converting a program to
Applesoft, remove all such DIM statements; use DIM only to define
arrays. In some of these other versions of BASIC, a statement of the form
DIM A$ C I , J>

defines a string array of J elements, each of length I. Convert DIM


statements of this type to
DIM A$CJ)
□ Some versions of BASIC use a comma (,) or an ampersand (&) for string
concatenation; Applesoft uses a plus sign ( + ).
□ Applesoft uses the string functions LEFT$, MID$, and RIGHT$ to extract
substrings. Other versions of BASIC (such as Integer BASIC) use the
expression
A$ C I >

to refer to character number I of string A$, and


A$ C I , J>

to designate the substring of A$ from character number I to character


number J. These expressions occurring on the right side of an
assignment statement ca� be converted to Applesoft as follows:
Convert A s c 1 >
to M I D $ C A $ , I , 1 )
Convert A U 1 , J >
to M I D $ C A $ , I , J - I + 1 )
When these expressions occur on the left side of an assignment
statement, convert them as follows:
Convert A U 1 > • u
to A $ • LEFT$ C A $ , I - 1 > + X S + M I DS C A S ,
I + 1>

Convert A s c 1 , J> • u
to A S • LEFTS C A $ , I - 1 > + X S + M I D$ C A $ ,
J + 1)

292 Appendix L: Comparison With Integer BASIC


□ Some versions of BASIC allow "multiple assignment" statements of the
form
LET 8 • C • B
This statement would set both variables B and C to 0.
In Applesoft, such a statement has an entirely different effect: all equal
signs after the first are interpreted as logical comparison operators. Thus
the statement above sets variable B to 1 (meaning true) if C equals 0, to 0
(meaning false) if it doesn't.
The easiest way to convert such a multiple assignment statement into
Applesoft is to rewrite it as

or
8 • B : C • B
□ Some versions of BASIC use a slash (/) instead of a colon (:) to separate
multiple statements on the same line. In converting to Applesoft, change
each such slash to a colon.
□ Programs that use the MAT (matrix arithmetic) functions available in
some versions of BASIC must be rewritten using FOR/NEXT loops to
perform the corresponding matrix operations.

L.3 Converting BASIC Programs to Applesoft 293


Appendix M If You Have a Cassette Recorder

295
This appendix discusses Applesoft's facilities for storing programs and
information on tape cassettes. For any of these features to work, all of the
following conditions must be present:
□ There must be a cassette tape recorder properly connected to the
computer (Apple II, Apple II Plus, or Apple Ile only).
□ The tape recorder must be turned on.
□ There must be a tape cassette properly mounted in the recorder.
□ The recorder must be set to RECORD or PLAY, depending on the
statement being executed.
None of the Applesoft tape operations checks for these conditions; if any
condition doesn't hold, the system may hang indefinitely. Only
I CONTROL H RESET I can interrupt a tape operation.
Occasionally a tape recorder does not work properly when both input and
output cables are plugged in at the same time. This problem originates from
a ground loop in the tape recorder itself, which prevents making a good
recording. The easiest solution is to unplug the output cable (usually labeled
MONITOR on the tape recorder) when recording. Such a ground loop causes
no trouble when reading a tape.

M. 1 The SAVE Command


SAVE
The SAVE command writes the Applesoft program currently in memory
onto a tape cassette. No prompting message or signal of any kind is given;
the tape recorder must already be turned on and set to RECORD at the time
the SAVE command is executed. Beeps signal the start and end of the
recording. If your system is equipped with a disk drive and you have the
disk operating system loaded and running, a SAVE command with a name
following the keyword SAVE writes the current program onto a disk under
that file name. Refer to Section 1.2.5 and your disk operating system
manual for more information.

296 Appendix M: If You Have a Cassette Recorder


M.2 The LOAD Command
LOAD
The LOAD command reads an Applesoft program into memory from a tape
cassette. No prompting message or signal of any kind is given; the tape
recorder must already be turned on and set to PLAY at the time the LOAD
command is executed. A beep signals when the beginning of information is
detected on the tape; a second beep is sounded when the program has been
successfully loaded.
If your system is equipped with a disk drive and you have the disk
operating system loaded and running, a LOAD command with a name
following the keyword LOAD reads a program from a disk under that file
name. Refer to Section 1.2.6 and your disk operating system manual for
more information.

M.3 The STORE Statement

STORE MX
The STORE statement writes the contents of an integer or real array onto a
tape cassette. The name of the array (MX in the example above) follows the
keyword STORE, without a subscript. No prompting message or signal of
any kind is given; the tape recorder must already be turned on and set to
RECORD at the time the STORE statement is executed. Beeps signal the
start and end of the recording.
String arrays cannot be written with the STORE statement.

M.4 The RECALL Statement


RECALL MX
The RECALL statement reads information into an integer or real array from
a tape cassette. The name of the array (MX in the example) follows the
keyword RECALL, without a subscript. The designated array must have
been previously defined in a DIM statement in the program issuing the
RECALL.

M.4 The RECALL Statement 297


No prompting message or signal of any kind is given; the tape recorder must
already be turned on and set to PLAY at the time the RECALL statement is
executed. A beep signals when the beginning of information is detected on
the tape; a second beep is sounded when the information has been
successfully transferred.
String arrays cannot be read with the RECALL statement.
The name of the array read with RECALL need not be the same name used
in the STORE statement that wrote the information onto the tape. However,
the dimensions of the array being read should be the same as those of the
array originally written. For example, if the tape was written by the
statement
STORE A
where array A had been defined by
DIM A CS , 5 , 5)

it can be read back with the statement


RECALL B
where array B is defined by
DIM B CS, 5, 5)

If the dimensions of the two arrays differ, RECALL may scramble the
information read into array B, or the program may halt with the message
? OUT O F M E M O R Y E R R O R .

M.5 The SHLOAD Statement


SHLOAD
The SHLOAD (for shape load) statement reads a shape table into memory
from a tape cassette. The shape table is loaded just below the current
setting of HIMEM: (see Section 7.2.1, "The HIMEM: Statement") and
HIMEM: is reset to just below the shape table to protect it.
No prompting message or signal of any kind is given; the tape recorder must
already be turned on and set to PLAY at the time the SHWAD command is
executed. A beep signals when the beginning of information is detected on
the tape; a second beep is sounded when the shape table has been
successfully loaded.
Section 6.3 contains extensive information on shape tables.

298 Appendix M: If You Have a Cassette Recorder


Appendix N Complete Listing of the Postage Rates Program






299
The following is a complete listing of the postage rates program developed
in Chapter 8. A copy of this program is included on the ProDOS BASIC
Programming Examples disk.
1 B R E M P O STAGE R A T E S Name of program.
20 Colon leaves line empty.
3 0 R E M D E T E R M I M E S P O STAGE F E E S
What program does.
4 0 R E M F D R E X P R E S S , 1 ST C L A S S ,
5 0 R E M A M D P R I O R I TY MA I L Empty line inserted by embedding
I CONTROL Hl] (line feed) at end of
REM statement in line 50.
6 0 R E M V3 1 0 1 1 5 / 8 3 Number and date of this version
7 0 R E M BY J O H M S C R I BB L E M O M G E R & S C O T K AM I M S
Programmer's credit line.
1 0 0 R E M M E M U O F P O STAGE C L A S S E S
I CONTROL Hl] here.
1 1 0 HOME Begins with a clear screen.
1 2 0 T I TL E $ • " P O STAGE R A T E S "
1 3 0 P R I MT
1 4 0 HTAB 2 1 - L E M ( T I TL E $ ) / 2
Formula to center title.
150 P R I MT T I TL E $
1 60 VTAB 6
1 70 P R I MT " 1 . E X P R E S S "
1 80 P R I MT " 2 . F I R S T C L A S S "
1 90 P R I MT " 3 . P R I O R I TY "
200 P R I MT
210 P R I MT " 4 . E M D THE P R OGRAM"
The escape hatch.
3 0 0 REM I CONTROL Hl] here,
GET C L A S S OF MA I L I CONTROL HlJ here,
3 1 0 VTAB 1 4
3 2 0 P R I MT " P r e !l !l t h e numb e r o f y o u r c h o i c e : " ;
Semicolon keeps response on same
line,
330 GET cs Only one keypress needed-cuts
down on error possibilities; use of
string variable to get number avoids
type mismatch errors.

300 Appendix N: Complete Listing of the Postage Rates Program


335 REM I CONTROL H]] here.
C H E C K S F O R V A L I D I TY Another I CONTROL rLlJ (last time
this is noted).
3 4 1! I F c s • 11 4 11 T H E H E H D Ends program if user types a 4 .
3 5 1! I F V A L C C $ ) > I! A H D VAL C C $ ) < 4 T H E H 3 8 1!
Skips next two lines if valid choice
typed.
3 6 1! P R I H T C H R $ C 7 > ; C H R U 7 > ; Beeps twice to get attention.
3 7 1! GOTO 3 3 1! Response was invalid; try again.
3 8 1! P R I HT c s Since choice accepted via GET, it
isn't displayed on the screen;
displays it back to user.
3 9 1! c • VAL c c n Needs this value later to determine
what section of program to branch
to for proper processing.
5 1!1! REM
GET W E I GH T O F I TE M
5 1! 5 VTAB 1 6
5 1 1! P R I HT 11 P l e a !l e e n t e r t h e W E I GHT - a n u mb e r p l u !I
a n O f o r C o u n c e !I ) o r a P ( f o r p o u n d !! ) - a n d
p r e !l !I t h e R E T U R H k ey : 1 1 ; Prompting message to tell user what
information to type and how to type
it.
5 2 1! C A L L - 868 Clears to end of line; useful to erase
any errors that might be typed.
5 3 1! I H PUT 1111 ; w s Empty string suppresses question
mark.
5 4 1! w u • R I GHH c w s , 1 > Rightmost letter should be either O
or P; use it later to see if weight is
consistent with postal regulations.
5 5 1! w • VAL c w n How many ounces or pounds?
555 REM
W A S E HT E R E D W E I GHT VAL I D ?
5 6 1! I F W A H D C W 1 $ • 11 0 11 O R W 1 $ • 11
P 11 ) T H E H 7 1 0
If a weight was typed, and if last
character was either O for ounces or
P for pounds, then proceeds.
5 7 0 P R I H T C H R $ C 7 > ; C H R U 7 > ; Beeps twice to get attention.
5 8 0 GOTO 5 0 0 Entry was invalid; tries again.

Appendix N: Complete Listing of the Postage Rates Program 301


7 fll8 R E M
C H E C K C O N S I STE N C Y
7 1 8 ON C GOSUB 1 8 8 8 8 , 1 1 8 8 8 , 1 2 8 8 8
Branches to appropriate subroutine
to see if weight typed is within
postal rules or program limitations
for mail class chosen.
728 I F NOT EFLAG THEN 9 1 8 If no inconsistency detected in
subroutine then proceeds with
processing.
7 3 8 GO S U B 6 fll8 f1J 8 R E M K E Y ST A L L
Waits for user to acknowledge
message.
7 4 8 E F LA G • 8 Clears error flag set in subroutine.
758 CLEAR Resets all variables, clears arrays,
etc.
768 GOTO 1 8 8 Restarts program loop.
9 fll8 R E M
F I ND A P P R O P R I ATE CODE F O R P R O C E S S I NG
Everything is valid and consistent;
now program can solve for the
postage rate!
9 1 8 O N C GOSUB 1 8 8 8 , 2 8 8 8 , 3 8 8 8
Branches to proper calculating
routine.
9 2 8 G O S U B 6 1 B fll8 R E M F O RMATTER
Formats result for display.
9 3 8 P R I NT
935 REM
D I S P L A Y R E SU L T S
9 4 8 P R I NT " P O STAGE N E EDED : $ II ; T $
Finally, the postage due!
9 5 8 G O S U B 6 fll8 fll 8 : R E M K E Y ST A L L
Doesn't go on until user is ready.
96 8 C L E A R Prepares for restart...
9 7 8 GOTO 1 fll8 ... and does it.
999 R E M
S U B R O U T I N E S BE G I N H E R E

302 Appendix N : Complete Listing o f the Postage Rates Program


1 11 " " R E M
EXPRESS MA I L CALCULAT I ON
1 8 1 8 W • I NT C W + . 99 ) Weight must be increased to
compensate for fractions; postal
rates read "NOT MORE THAN x
POUNDS."
1 11 2 8 T • R C W ) Rate array filled in express mail
consistency-checking routine
(line 10000).
1 8 3 8 R E T UR N Ends routine.
2 8 8 8 REM
F I RST CLASS CALCULAT I ON
2 8 1 8 T • . 2 8 + I NT C W + . 99 - 1 > * . 1 7
First class rate is 20 cents first
ounce plus 17 cents for each addi
tional ounce or portion thereof
(January 1984 rates).
2 8 2 8 RETURN Ends routine.
3 " " 8 REM
P R I OR I TY MA I L C A L C U L A T I O N
3 8 1 8 W • I NT C W + . 99 ) Compensates for partial ounces or
pounds.
3 8 2 8 I F W > 1 8 THEN 3 1 68 Goes to line 3160 for weights greater
than 10 pounds (ounce weights
converted to pounds in consistency
subroutine starting at line 12000).
3 8 25 REM
P R I O R I TY R A T E S TO 1 8 P O U N D S
3 8 3 8 IF W <• 1 THEN T • 2 . 24
3 8 4 8 I F W > 1 AND W < • 1 . 5 THEN T • 2 . 38
Rates in half-pound increments.
3858 IF W > 1 . 5 AND W <• 2 THEN T • 2 . 54
3868 IF W > 2 AND W <• 2.5 THEN T • 2 . 78
3878 IF W > 2 . 5 AND W <• 3 THEN T • 3.81
3 8 72 IF W > 3 AND W <• 3.5 THEN T • 3 . 25
3 8 78 IF W > 3 . 5 AND W <• 4 THEN T • 3 . 49
3888 IF W > 4 AND W <• 4.5 THEN T • 3 . 73

Appendix N: Complete Listing of the Postage Rates Program 303


3 11J 9 11J I F W > 4 . 5 At-I D w < • 5 T H E H T • 3 . 9 7
3 1 11J f1J I F W > 5 A H D W < • 6 T H E H T • 4 . 4 4
Rates by the pound now!
3 1 1 f1J I F W > 6 AHD W < • 7 THEH T • 4 . 92
3 1 2 11J I F W > 7 A H D W < • 8 T H E H T • 5 . 39
3 1 3 11J I F W > 8 A H D W < • 9 T H E H T • 5 . 87
3 1 4 11J I F W > 9 T H E H T • 6 . 35
3 1 5 11J GOTO 3 2 4 11J Branches to RETURN statement.
3 1 6 11J REM
P R I O R I TY R A T E S F O R O V E R 1 11J P O U HDS
3 1 7 11J T 1 • I HT C W / 5 - 1 ) * 2 . 38 + 3 . 9 7
First 5 pounds cost $3.97; each
added 5 pounds cost $2.38.
3 1 8 11J W 1 • W - I HT C W / 5 ) * 5
How many odd pounds are there
(pounds that are not multiples of 5
and must be charged at a special
rate)?
3 1 9 11J IF W1 • THEN T2 • . 47
3 2 11J f1J I F W 1 • 2 THEN T2 • . 95
3 2 1 11J I F W 1 • 3 THEH T2 • 1 . 42
3 2 2 11J IF W1 • 4 THEH T2 • 1 . 9 11J
323 0 T • T 1 • T2 Adds the 5-pound-multiples rate to
the odd-pounds rate.
3 2 4 11J R E T U R H Ends routine.
1 11J f1J f1J f1J R E M
E X P R E S S MA I L C O H S I STE H C Y C H E C K
1 11J f1J 1 11J DATA 9 . 3 5 , 9 . 3 5 , 9 , 5 5 , 9 . 9 11J , 1 11J . 3 11J , 1 11J . 6 5 ,
1 1 . IIJ IIJ , 1 1 . 4 11J , 1 1 . 7 5 , f1J
Express mail rates; 0 at end is "last
item" flag.
1 f1J f1J 2 11J x • f1J Sets up counter to check how many
rates are read from DATA list.
1 f1J f1J 3 11J x • x + 1 Increments counter.
1 f1J f1J 4 f1J R E A D R c x > Puts price into proper array
element.
1 11J f1J 5 11J I F R C X > • f1J TH E N 1 11J f1J 7 11J
Price of 0 marks end of list.
1 f1J 11J 6 11J GOTO 1 f1J 11J 3 11J Gets next price.
1 f1J f1J 7 f1J x • x - 1 X includes count of "last item" flag
from 10050; subtracts it from count
since it's a "dummy" item.

304 Appendix N: Complete Listing of the Postage Rates Program


1 B B8B I F W 1 $ • "P" THEN 1 B 1 B B
Next line is for ounces only.
u ese w • w / 1 6 Converts ounces to pounds.
1B1BB I F W ( • X THEN 1 B 1 4 B lf weight in pounds is covered by
the rate chart, then goes ahead.
1 B 1 1 B PR I HT
1 B 1 2 B P R I NT C H R $ C 7 > ; C H R $ C 7 > ; "TOO H E A V Y F O R
M Y TABL E S - P L E A S E C A L L T H E P O S T O F F I C E "
Sorry; can't help you.
u 1 3 B E F L AG • 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 B 1 4 B RETURN Ends routine.
1 1 B B B REM
F I R S T C L A S S C O N S I STE N C Y C H E C K
1 1 B 1 B IF W 1 $ • "0" AND W < 1 2 . B 1 THEN 1 1 B6B
OK if not more than 12 ounces.
1 1 B 2 B P R I NT
1 1 B 3 B P R I NT C H R $ C 7 > ; C H R $ C 7 > ; "TOO H E A V Y F O R
F I RST CLASS" Sorry-inconsistent!
1 1 B 4 B P R I NT "TRY P R I O R I TV MA I L "

1 1 B S B EFLAG . 1
Suggests alternative.
Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 1 B6B RETURN Ends routine.
1 2 B B B REM
P R I O R I TY MA I L C O N S I STE N C Y C H E C K
1 2 B 1 B IF WU • "P" THEN 1 2 B9B
If in pounds, then skips down.
1 2B2B I F W > 1 2 THEN 1 2B8B Skips down if weight is between 12
and 16 ounces.
1 2 B 3 B P R I NT
1 2 B 4 B P R I NT C H R $ C 7 ) ; C H R $ C 7 ) ; "TOO L I GHT F O R
P R I O R I TY MA I L - " Too light!
1 2 B S B P R I NT "TRY F I R S T C L A S S "
Suggests alternative.
1 2 B 6 B E F LAG = 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 2 0 1 0 GOTO 1 2 1 s e Branches to end of routine.
1 2Bae w • w / 16 Converts ounces to pounds.
1 2B9B I F W ( • 7B THEN 1 2 1 S B Final check: is item on the charts?

Appendix N: Complete Listing of the Postage Rates Program 305


1 2 1 8 8 P R I NT
1 2 1 1 8 P R I NT C H R $ < 7 > ; C H R S C 7 ) ; " T O O H E A V Y F O R
P R I O R I TY M A I L - " Off the charts
1 2 1 2 8 P R I NT " T R Y O H E O F T H E A I R E XP R E S S C O M P A N I E S "
Too big for the Post Office!
1 2 1 3 8 EFLAG • 1 Sets flag indicating inconsistent
weight/type; will be checked at
line 720.
1 2 1 5 8 R ET U R N Ends routine.
59999 R E M
UT I L I TY R O UT I N E S Routines useful for various tasks but
ancillary to rest of program.
68 8 8 8 REM
K E V ST A L L Routine to interrupt program until
user presses a key.
688 1 8 VTAB 2 4 Moves cursor to screen bottom.
68828 I NV E R S E Sets text to appear black-on-white.
68838 P R I NT " P R E S S A H V K E V T O GO O H • • • " ;
68848 GET A t Waits for keypress.
68858 NORMAL Restores ordinary white-on-black.
68 8 6 8 RETURN Ends routine.
61 888 REM
M O N E Y F O RMATT E R Adds zeros after the decimal point
where needed.
6 1 8 1 8 T S • STR S C T > Turns the calculated postage fee
into a string.
6 1 8 2 8 I F T • I HT C T > T H E H T S • T S + 11 . 8 8 11
If charge is in whole dollars, adds a
decimal point and two zeros.
6 1 8 3 8 I F A S C < R I GH T S C T S , 2 > > • 4 6 T H E H T t • T S + 11 8 11

If second character from the right is


a decimal point (ASCII code 46)
then number has only one digit to
right of decimal-so add a "O" to the
string.
6 1 8 4 8 RETURN Ends the routine.

306 Appendix N: Complete Listing of the Postage Rates Program


Appendix O BASIC and the Mouse

307
It's not hard to write programs that use the mouse pointing device. 'This
appendix is an introduction to what the mouse does and how to control it
from BASIC programs. There are two sample programs at the end of this
appendix.
A.Warning This appendix and the sample programs it contains assume you have a
mouse attached to your computer either through the special mouse port
(Apple Ile) or through port 4 (Apple II, Apple II Plus, Apple Ile). If you are
using a computer with expansion slots and the mouse card is plugged into
some port other than 4, adjust the port designation accordingly.
Also note that the sample code listed throughout this appendix sends
information to the video screen using the command
PR# 0

Some Apple II models capable of displaying 80 columns need a different


command instead, in the form
PR#3

in order to keep the 80,column settings intact and to prevent meaningless


garbage from being strewn randomly across the video screen. Check the
appropriate manual, just to be sure.
Like the keyboard, the mouse is an input device for your computer.
Programs you write and software you buy need special code to enable you
to use the mouse, once it's plugged in. Typically with software written for
the mouse, rolling the mouse along a flat surface moves a pointer or cursor
on the video screen; pressing the button on top of the mouse sends a signal
to the computer, usually (but not necessarily) meaning that the pointer is in
the location you want.

0.1 Using the Mouse in BASIC


This section explains how to tum the mouse on and off so that you can use
it in BASIC. You needn't try the commands out as you read; things will be
clearer if you first read through this entire section to get a feel for what's
going on. MOUSE.MOVE, the program that puts all these commands
together for you, is listed at the end of this section.

308 Appendix 0: BASIC and the Mouse


Here's a list of all the commands you'll need in order to use the mouse from
BASIC:
PR#4 directs the computer to send information to the mouse (if you
are using an Apple with slots and your mouse card is in a port
other than 4, the number after PR# should designate that port)
PR#0 directs the computer to send information to the video screen
(but note the warning about 80-column displays)
IN#4 directs the computer to accept information from the mouse (if
you are using an Apple with slots and your mouse card is in a
port other than 4, the number after IN# should designate that
port)
IN#0 directs the computer to accept information from the keyboard
CHR$ (1) turns the mouse's firmware on and initializes coordinates to 0,0
CHR$ (0) turns off the mouse's firmware, making it invisible to Applesoft
In Applesoft BASIC you use the CHR$ function to execute a DOS or ProDOS
command within a program, specifically CHR$(4). The CHR$ function
converts any valid code number to its corresponsing ASCII character;
CHR$( 4) returns the ASCII character code � You use
� to tell the computer that the next command should be
interpreted as a DOS or ProOOS command.
All DOS and ProDOS commands work only if they are issued immediately
following a CHR$(13)-that i&, if they are not preceded by a semicolon or a
response to a GET statement. One way to insure that this happens is to
precede all disk operating system commands with a blank PRINT
statement. For example:
4 8 P R I NT : P R I NT C H R S C ◄ > ; " P R # ◄ "
See your DOS or ProDOS manual for more details.

0.1 Using the Mouse in BASIC 309


0. 1 . 1 Turning the Mouse On
The order of the following five steps is significant. Follow these steps
whenever you're turning the mouse on in a BASIC program:
1. First, use the PR# command to tell the computer that you want to
communicate with the mouse. Since PR# is an operating system
command, it must be treated as an embedded disk operating system
command:
P R I HT C H R S C 4 > ; " P R l 4 "
2. When you are hooked up to the mouse, turn it on:
P R I HT CHRS C O
3. Then use PR# to tell the computer to send information to the screen
instead of somewhere else. Note that you treat PR# like a DOS or
ProDOS command:
P R I HT C H R S C 4 ) ; " P R # B "
4. Next, direct the computer to accept input from the mouse with IN#,
remembering again to treat it as a disk operating system command:
PR I HT CHRS C 4 > ; " 1 Hl4"
5 . Finally, use an INPUT statement to define variable names for mouse
information. The statement should be in the form
I HP U T X , Y , S
where X is the horizontal location of the mouse, Y is the vertical position
of the mouse, and S is the status of the mouse button. The possible
values of these three variables are as follows:
X = a number in the range O to + 1023
Y = a number in the range O to + 1023
S = a number in the range + 1 to +4 or -1 to -4
If S = ± 1 then the mouse button is still being pressed.
If S = ± 2 then the mouse button has just been pressed.
If S = ± 3 then the mouse button has just been released.
If S = ± 4 then the mouse button has not been pressed.
If S < 0 then a key on the keyboard has been pressed.

310 Appendix 0: BASIC and the Mouse


0.1 .2 Turning the Mouse Off
The st.eps you use to turn the mouse off are similar to those you use to turn
the mouse on.
1. P R I HT C H R $ C 4 > ; " I H I ll directs the comput.er to accept
II

information from the keyboard.


2. P R I HT C H R S c ◄ > ; " P R I ◄ " directs the comput.er to send information
to the mouse (rather than the video screen).
3. P R I HT C H R S c e > turns the mouse firmware off.
4. P R I HT C H R S c ◄ > ; " P R I il " directs the comput.er to resume sending
information to the video screen.
The two BASIC programs that follow show you how to turn the mouse on
and off, and how to use input from the mouse. Study these programs, play
with them, and modify them to suit your own needs.

0.2 MOUSE.MOVE
The program named MOUSE.MOVE demonstrat.es the positions of the
mouse. This program reads and displays the current location of the mouse
and the status of the mouse button (whether it was just pressed, is
currently being pressed, and so on). Type in and run the program, then
move the mouse over your desk top and watch the coordinat.es change.
Press the mouse button and see the status change. Press any key to stop the
program.

0.2. 1 MOUSE.MOVE Program Listing

1" HOME
2 1l P R I NT "Th 1 !I 1 !I a demo n !l t r a t i o n o f t h e
M o u !l e "
3 1l P R I NT C H R $ ( 4 ) ; "P R l 4 " : P R I NT C H R $ ( 1 )
4 1l P R I NT C H R S ( ◄ ) ; "P R I il "
S il P R I NT C H R $ C 4 ) ; " I H 1 4 "
6 1l I NPUT "" ; X , V , S
7 1l VTAB 1 " : P R I NT X ; " II t yn I I t 511 II

Sil I F S > ll THE N GOTO 61l

0.2 MOUSE.MOVE 311


S B P R I HT C H R $ C 4 > ; " I H # B "
1 B B P R I HT C H R $ C 4 ) "P R # 4 " : P R I HT C H R $ C B >
1 1 B P R I HT C H R $ C 4 ) ; "P R # B "
1 2 B P O K E - 1 6368 , B : R E M C l e a r s k ey b o a r d
s t r obe
1 3 B E HD

0.2.2 How MOUSE.MOVE Works

1. Line 10 clears the screen to black.


2. Line 20 prints a message.
3. Line 30 turns on the mouse.
4. Line 40 redirects the computer to send information to the video screen.
5. Line 50 tells the computer to accept input from the mouse.
6. Line 60 uses an empty string as a prompt to suppress the question
mark, then reads the mouse position and status of the mouse button.
7. Line 70 prints the mouse position and status of the mouse button.
8. Line 80 goes to line 60 if no key has been pressed.
9. Line 90 tells the computer to accept input from the keyboard.
10. Lines 100 and 1 10 tum off the mouse.
11. Line 120 resets the keyboard strobe so that the next time a key is
pressed BASIC can check for it (see Appendix F, Section F.2 for
details).
12. Line 130 ends the program.

0.3 MOUSE.DRAW
This program is an expanded version of MOUSE.MOVE. With this program,
you can cause the mouse to draw pictures on the low-resolution graphics
screen. Pressing the mouse button clears the screen and lets you produce a
new picture.

312 Appendix 0: BASIC and the Mouse


0.3. 1 MOUSE.DRAW Program Listing

18 R E M U !5 e !5 m o u !l e to d r aw l ow - r e !l o l u t i o n
g r a p h i c !I
188 G O S U B 1 B B B : R E M Tu r n o n t h e mou !5 e
118 P R I NT C H R $ C 4 ) ; " I N # 4 "
1 28 I NP U T '"' ; X , Y , S : R E M R e a d mou !5 e
p o !5 i t i o n
1 38 I F S • 1 THEN 1 8 8 : REM C l ear the
!S c r e e n
148 I F S < e THEN 3 8 8 : REM Time t o qu i t ?
1 58 R E M S c a l e t he p o !5 i t i o n
1 68 X • I NT e x 1 2 5 . 5 7 5 >
178 y - I NT C Y / 2 5 . 5 7 5 >
188 PLOT X , Y
198 GOTO 1 2 8
388 REM Chec k i f t i me t o qu i t
318 P O K E - 1 6368 , B : R E M C l e a r k eybo a r d
!l t o be
328 P R I NT CHRt C 4 ) ; " I N # B "
338 VTAB 2 2 : P R I NT "P r e !5 !5 R E T U R N t o c o n t
o r E S C t o qu i t "
348 VTAB 2 2 : HTAB 39 : G E T A $ : P R I NT
358 I F A $ • C H R $ C 1 3 ) T H E N H O M E : GOTO 1 1 8
368 I F A $ < > CHR$ C 27 ) THEN 348
378 R E M C l ea r !S c r e e n a n d t u r n o f f m o u !l e
388 TEXT : HOME
398 P R I NT C H R $ C 4 > ; " P R # 4 " : P R I NT C H R t C B )
488 P R I NT C H R $ C 4 ) ; " P R # B "
418 END
1 BBB R E M C l e a r !S c r e e n a n d i n i t a l i z e m o u !l e
18 18 H O M E : GR
1 828 COLOR• 15
1 838 P R I NT C H R $ C 4 > ; "P R ' 4 " : P R I NT C H R $ C 1 >
1 848 P R I NT C H R $ C 4 > ; "P R # B "
1 858 RETURN

0.3 MOUSE.DRAW 313


0.3.2 How MOUSE.DRAW Works

1. Line 10 reminds you what the program does.


2. Line 100 goes to the subroutine at line 1000 to turn on the mouse and
the low-resolution graphics page.
3. Line 1 10 tells the computer to accept input from the mouse.
4. Line 120 uses an empty string to suppress the question mark, then
reads the mouse position and status of the mouse button.
5. If the mouse button is pressed, line 130 sends program to line 100 to
begin again.
6. If a key is pressed, line 140 sends program to line 300 to check for an
end.
7. Line 150 reminds you what the next two lines do.
8. Lines 160 and 170 convert the mouse position to low-resolution
graphics coordinates.
9. Line 180 plots a point on the low-resolution screen.
10. Line 190 goes back to line 120 and does it all again.
11. Line 300 reminds you what the next group of statements does.
12. Line 310 resets the keyboard strobe so that the next time a key is
pressed BASIC can check for it (see Appendix F, Section F.2 for
details).
13. Line 320 tells the computer to accept input from the keyboard.
14. Line 330 prints a line of instructions on the screen.
15. Line 340 gets a character from the keyboard.
16. If you press I RETURN I, line 350 returns to the main program for more
graphics; otherwise program goes to the next line.
17. If you didn't press I Esc � line 360 sends the program back to line 340 to
get another character.
18. Line 370 reminds you of what happens next.
19. Line 380 sets the screen to text and clears it.
20. Lines 390 and 400 turn off the mouse.
21. Line 410 ends the program.
22. Line 1000 reminds you what this subroutine does.
23. Line 1010 clears the screen and turns on the low-resolution graphics
screen.
24. Line 1020 sets the graphics color to white.
25. Lines 1030 and 1040 turn on the mouse.
26. Line 1050 returns to the main program.

314 Appendix 0: BASIC and the Mouse


An Idea: You might write a program that uses the mouse to move a
pointer on the screen. Then, when the pointer reaches a certain area on
the screen and the user presses the mouse's button, the program could
open up a new text window that displays a menu or other information.
Refer to Appendix F for details on windows.

0.3 MOUSE.ORAW 315


Glossary

acronym: A word formed from the application program: A program assembler: A language translator
initial letters of a name or phrase, that puts the resources and that converts a program written in
such as laser, from light capabilities of the computer to use assembly language into an
amplification by stimulated for some specific purpose or task, equivalent program in machine
emission of radiation. such as word processing, data-base language.
address: A number used to identify management, graphics, or assembly language: A low-level
something, such as a location in the telecommunications. Compare programming language in which
computer's memory. system program. individual machine-language
algorithm: A step-by-step application software: The instructions are written in a
procedure for solving a problem or component of a computer system symbolic form more easily
accomplishing a task. consisting of application programs. understood by a human programmer
argument: The value on which a than is machine language itself.
AND: A logical operator that function operates. BASIC: Beginner's All-purpose
produces a true result if both of its Symbolic Instruction Code; a
operands are true, a false result if arithmetic operator: An operator, high-level programming language
either or both of its operands are such as +, that combines numeric designed to be easy to leam and use.
false; compare OR, NOT. values to produce a numeric result; Two versions of BASIC are available
Apple II: A personal computer in compare relational operator, from Apple Computer for use with
the Apple II family, manufactured logical operator. the Apple II: Applesoft (built into
and sold by Apple Computer; array: A collection of variables the Apple II in firmware) and
generic name for all computers in referred to by the same name and Integer BASIC (provided on the OOS
the series. distinguished by means of 3.3 SYSTEM MASTER disk).
Applesoft: An extended version of numerical subscripts. . binary: The representation of
the BASIC programming language ASCII: American Standard Code numbers in terms of powers of 2,
used with the Apple II family of for Infonnation Interchange; a code using the two digits O and 1.
computers and capable of in which the numbers from O to 127 Commonly used in computers, since
processing numbers in floating-point stand for text characters, used for the values O and 1 can easily be
form. An interpreter for creating representing text inside a computer represented in physical form in a
and executing programs in and for transmitting text between variety of ways, such as the
Applesoft is built into the Apple II computers or between a computer presence or absence of current,
system in firmware. Compare and a peripheral device. positive or negative voltage, or a
Integer BASIC. white or black dot on the display
screen.

Glossary 317
binary file: A file containing "raw" boot disk: See startup disk. catalog: A list of all files stored on
information not expressed in text bootstrap: See boot. a disk; sometimes called a directory.
form; compare text file. cathode-ray tube: An electronic
binary operator: An operator that branch: To send program execution device, such as a television picture
combines two operands to produce a to a line or statement other than the tube, that produces images on a
result; for example, + is a binary next in sequence. screen coated with phosphors that
arithmetic operator, < is a binary buffer: An area of the computer's emit light when struck by a focused
relational operator, and OR is a memory reserved for a specific beam of electrons.
binary logical operator. Compare purpose, such as to hold graphical central processing unit: See
unary operator. information to be displayed on the processor.
bit: A binary digit (0 or 1); the screen or text characters being read
smallest possible unit of from some peripheral device. Often character: A letter, digit,
information, consisting of a simple used as an intermediary "holding punctuation mark, or other written
two-way choice, such as yes or no, area" for transferring information symbol used in printing or
on or off, positive or negative, between devices operating at displaying information in a form
something or nothing. different speeds, such as the readable by humans.
computer's processor and a printer character code: A number used to
bit bucket: The final resting place or disk drive. Information can be represent a text character for
of all information; see write-only stored in the buffer by one device processing by a computer system.
memory. and then read out by the other at a
body: The statements or different speed. code: (1) A number or symbol used
instructions malting up some bug: An error in a program that to represent some piece of
construct in a program, such as a causes it not to work as intended. information in a compact or easily
loop or a subroutine. processed form. (2) The statements
byte: A unit of information or instructions making up a
boot: To start up a computer by consisting of a fixed number of bits; program.
loading a program into memory on the Apple II, one byte consists of command: A communication from
from an external storage medium eight bits and can hold any value the user to a computer system
such as a disk. Often accomplished from O to 255. (usually typed from the keyboard)
by first loading a small program call: To request the execution of a directing it to perform some
whose purpose is to read the larger subroutine or function. immediate action.
program into memory. The program
is said to "pull itself in by its own card: See peripheral card. compiler: A language translator
bootstraps"; hence the term that converts a program written in a
bootstrapping or booting.

318 Glossary
high-level programming language control character: A character current output device: The
into an equivalent program in some that controls or modifies the way destination, such as the display
lower-level language (such as information is printed or displayed. screen or a printer, to which an
machine language) for later Control characters have ASCII Applesoft program is currently
execution. Compare interpreter. codes between O and 31 and are sending its output.
typed from the Apple II keyboard by
component: A part; in particular, a cursor: A marker or symbol
holding down the I CONTROL I key displayed on the screen that marks
part of a computer system. while typing some other character.
For example, the character where the user's next action will
computer: An electronic device for take effect or where the next
performing predefined � (ASCII code 13)
means "return to the beginning of character typed from the keyboard
(programmed) computations at high will appear.
speed and with great accuracy. the line" and is equivalent to the
I RETURN I key. data: Information; especially
computer system: A computer information used or operated on by
and its associated hardware, controller card: A peripheral card
that connects a device such as a a program.
firmware, and software.
printer or disk drive to the Apple II, debug: To locate and correct an
concatenate: Literally, "to chain and controls the operation of the error or the cause of a problem or
together"; to combine two or more device. malfunction in a computer system.
strings into a single, longer string Typically used to refer to
containing all the characters in the control variable: See index
variable. software-related problems; compare
original strings. troubleshoot.
conditional branch: A branch CPU: Central processing unit; see
that depends on the truth of a processor. decimal: The common form of
condition or the value of an number representation used in
crash: To cease operating everyday life, in which numbers are
expression; compare unexpectedly, possibly damaging or expressed in terms of powers of 10,
unconditional branch. destroying information in the using the ten digits O to 9.
constant: A symbol in a program process.
default: A value, action, or setting
representing a fixed, unchanging CRT: See cathode-ray tube. that is automatically used by a
value; compare variable. computer system when no other
current input device: The source,
control: The order in which the such as the keyboard or a modem, explicit information has been given.
statements of a program are from which an Applesoft program is For example, if a command to run a
executed. currently receiving its input. program from a disk does not
identify which disk drive to use, the
disk operating system automatically
uses the same drive that was used
in the last operation.

Glossary 319
deferred execution: The saving of dimension: The maximum size of display color: The color currently
an Applesoft program line for one of the subscripts of an array. being used to draw high- or
execution at a later time as part of a directory: A list of all files stored low-resolution graphics on the
complete program; occurs when the on a disk; sometimes called a display screen.
line is typed with a line number. catalog. display device: A device that
Compare immediate execution. exhibits information visually, such
delimiter: A character that is used disk: An information storage as a television receiver or video
medium consisting of a flat, circular monitor.
for punctuation to mark the magnetic surface on which
beginning or end of a sequence of information can be recorded in the display screen: The glass or
characters, and that therefore is not form of small magnetized spots, plastic panel on the front of a
considered part of the sequence similarly to the way sounds are display device, on which images are
itself. For example, Applesoft uses recorded on tape. displayed.
the double quotation mark ( ") as a
delimiter for string constants: the disk drive: A peripheral device edit: To change or modify; for
string "DOG" consists of the three that writes and reads information example, to insert, remove, replace,
characters D, 0, and G, and does not on the surface of a magnetic disk. or move text in a document.
include the quotation marks. In Disk II drive: A model of disk element: A member of a set or
written English, the space character drive made and sold by Apple collection; specifically, one of the
is used as a delimiter between Computer for use with the Apple II individual variables making up an
words. family of computers; uses array.
device: (1) A physical apparatus for 5-1/4-inch flexible ("floppy") disks. embedded: Contained within. For
performing a particular task or disk operating system: A example, the string "HUMPTY
achieving a particular purpose. (2) software system for the Apple II DUMPTY" is said to contain an
In particular, a hardware that enables the computer to control embedded space.
component of a computer system. and communicate with one or more
digit: (1) One of the characters O to Disk II drives. ending value: The value against
9, used to express numbers in which the index variable is tested
decimal form. (2) One of the disk-resident: Stored or held after each pass through a loop, to
characters used to express numbers permanently on a disk. determine when to stop repeating
in some other form, such as O and 1 display: (1) Information exhibited the loop.
in binary or O to 9 and A to F in visually, especially on the screen of error code: A number or other
hexadecimal. a display device. (2) To exhibit symbol representing a type of error.
information visually. (3) A display
device.

320 Glossary
error message: A message file: A collection of infonnation flag: A variable whose contents
displayed or printed to notify the stored as a named unit on a (usually 1 or 0, standing for true or
user of an error or problem in the peripheral storage medium such as false) indicate whether some
execution of a program. a disk. condition holds or whether some
file name: The name under which event has occurred, used to control
escape mode: A state of the Apple
the program's actions at some later
II family of computers, entered by a file is stored on a disk.
time.
pressing the I ESC I key, in which
firmware: Those components of a
certain keys on the keyboard take computer system consisting of floating-point: A method of
on special meanings for positioning programs stored permanently in representing numbers inside the
the cursor and controlling the read-only memory. Such programs computer in which the decimal
display of text on the screen. (for example, the Applesoft point (more correctly, the binary
interpreter and the Apple II Monitor point) is permitted to "float" to
escape sequence: A sequence of
program) are built into the computer different positions within the
keystrokes beginning with the I ESC I
at the factory; they can be executed number. Some of the bits within the
key, used for positioning the cursor
at any time but cannot be modified number itself are used to keep track
and controlling the display of text
or erased from main memory. of the point's position.
on the screen.
Compare hardware, software. Floating-point numbers of a given
execute: To perform or carry out a length cover a wider range than
specified action or sequence of fixed-point: A method of fixed-point numbers of the same
actions, such as those described by representing numbers inside the length, but with less precision.
a program. computer in which the decimal Compare fixed-point.
point (more correctly, the binary
expansion slot: A connector inside point) is considered to occur at a format: (1) The form in which
the Apple II, II Plus, and Ile fixed position within the number. infonnation is organized or
computers in which a peripheral Typically, the point is considered to presented. (2) To specify or control
card can be installed; sometimes lie at the right end of the number, so the format of infonnation. (3) To
called peripheral slot or port. that the number is interpreted as an prepare a blank disk to receive
integer. Fixed-point numbers of a information by dividing its surface
expression: A formula in a
given length cover a narrower range into tracks and sectors; also
program describing a calculation to
than floating-point numbers of the initialize.
be perfonned.
same length, but with greater function: A preprogrammed
FIFO: First in, first out. precision. Compare floating-point. calculation that can be carried out
on request from any point in a
program.

Glossary 321
GAME 1/0 connector: A special hardware: Those components of a high-order byte: The more
16-pin connector inside the Apple II, computer system consisting of significant half of a memory address
II Plus, and Ile computers, originally physical (electronic or mechanical) or other two-byte quantity. In the
designed for connecting hand devices. Compare software, Apple II's 6502 microprocessor, the
controls to the computer, but also firmware. low-order byte of an address is
used for connecting some other hertz: The unit of frequency of usually stored first and the
peripheral devices. Compare hand vibration or oscillation, also called high-order byte second.
control connector. cycles per second; named for the high-resolution graphics: The
graphics: (1) Information physicist Heinrich Hertz and display of graphics on the Apple II's
presented in the form of pictures or abbreviated Hz. The current display screen as a six-color array of
images. (2) The display of pictures provided by a standard power outlet points, 280 columns wide and 192
or images on a computer's display alternates at a rate of 60 hertz; that rows high.
screen. Compare text. is, it changes polarity 60 times each
second. The Apple II's 6502 Hz: See hertz.
hand control: An optional
peripheral device that can be microprocessor, for example, immediate execution: The
connected to the Apple II's hand operates at a clock frequency of 1 execution of an Applesoft program
control connector and has a rotating million hertz, or 1 megahertz (MHz). line as soon as it is typed; occurs
dial and a pushbutton; typically hexadecimal: The representation when the line is typed without a
used to control game-playing of numbers in terms of powers of 16, line number. Compare deferred
programs, but can be used in more using the sixteen digits 0 to 9 and A execution.
serious applications as well. to F. Hexadecimal numbers are implement: To realize or bring
hand control connector: A 9-pin easier for humans to read and about; for example, a language
connector on the Apple- II's back understand than binary numbers, translator implements a particular
panel, used for connecting hand but can be converted easily and language.
controls to the computer. Compare directly to binary form: each index: (1) A number used to
GAME 1/0 connector. hexadecimal digit corresponds to a identify a member of a list or table
sequence of four binary digits, or by its sequential position. (2) A list
hang: For a program or system to bits.
"spin its wheels" indefinitely, or table whose entries are identified
performing no useful work. high-level language: A by sequential position.
programming language that is index variable: A variable whose
hardcopy: Information printed on relatively easy for humans to
paper for human use. understand. A single statement in a value changes on each pass through
high-level language typically a loop; often called control variable
corresponds to several instructions or loop variable.
of machine language.

322 Glossary
infinite loop: A section of a executing programs in Integer K: Two to the tenth power, or 1024
program that repeats the same BASIC is included on the DOS 3.3 (from the Greek root kilo, meaning
sequence of actions indefinitely. SYSTEM MASTER disk, and is one thousand); for example, 64K
automatically loaded into the equals 64 times 1024, or 65,536.
information: Facts, concepts, or computer's memory when the
instructions represented in an computer is started up with that keyboard: The set of keys built
organized form. into the Apple II computer, similar
disk. Compare Applesoft. to a typewriter keyboard, for typing
initialize: (1) To set to an initial interactive: Operating by means of information to the computer.
state or value in preparation for a dialog between the computer
some computation. (2) To prepare a system and a human user. keystroke: The act of pressing a
blank disk to receive information by single key or a combination of keys
dividing its surface into tracks and interface: The devices, niles, or (such as � on the
sectors; also format. conventions by which one Apple II keyboard.
component of a system keyword: A special word or
input: (1) Information transferred communicates with another.
into a computer from some external sequence of characters that
source, such as the keyboard, a disk interpreter: A language translator identifies a particular type of
drive, or a modem. (2) The act or that reads a program written in a statement or command, such as
process of transferring such particular programming language RUN or PRINT.
information. and immediately carries out the kilobyte: A unit of information
actions that the program describes. consisting of lK (1024) bytes, or 8K
instruction: A unit of a Compare compiler.
machine-language or (8192) bits; see K.
assembly-language program inverse video: The display of text language: See programming
corresponding to a single action for on the computer's display screen in language.
the computer's processor to the form of black dots on a white (or
perform. other single phosphor color) language translator: A system
background, instead of the usual program that reads a program
integer: A whole number, with no white dots on a black background. written in a particular programming
fractional part; represented inside language and either executes it
the computer in fixed-point form. 1/0: Input/output; the transfer of
information into and out of a directly or converts it into some
Compare real number. other language (such as machine
computer. See input, output. language) for later execution. See
Integer BASIC: A version of the
BASIC programming language used 1/0 device: Input/output device; a interpreter, compiler,
with the Apple II family of device that transfers information assembler.
computers; older than Applesoft and into or out of a computer. See input,
capable of processing numbers in output, peripheral device.
integer (fixed-point) form only. An
interpreter for creating and

Glossary 323
LIFO: Last in, first out. low-order byte: The less memory: A hardware component
significant half of a memory address of a computer system that can store
line: See program line. or other two-byte quantity. In the information for later retrieval; see
line number: A number identifying Apple H's 6502 microprocessor, the main memory, random-access
a program line in an Applesoft low-order byte of an address is memory, read-only memory,
program. usually stored first and the read-write memory, write-only
high-order byte second. memory.
load: To transfer information from
a peripheral storage medium (such low-resolution graphics: The memory location: A unit of main
as a disk) into main memory for use; display of graphics on the Apple II's memory that is identified by an
for example, to transfer a program display screen as a sixteen-color address and can hold a single item
into memory for execution. array of blocks, 40 columns wide of information of a fixed size; in the
I
location: See memory location. and 48 rows high. Apple II, a memory location holds
machine language: The form in one byte, or eight bits, of
logical operator: An operator, which instructions to a computer information.
such as AND, that combines logical
values to produce a logical result; are stored in memory for direct memory-resident: (1) Stored
compare arithmetic operator, execution by the computer's permanently in main memory, as
relational operator. processor. Each model of computer firmware. (2) Held continually in
processor (such as the 6502 main memory even while not in use,
loop: A section of a program that is microprocessor used in the Apple II) as the disk operating system.
executed repeatedly until some has its own form of machine
condition is met, such as an index language. menu: A list of choices presented
variable reaching a specified ending by a program, usually on the display
value. main memory: The memory screen, from which the user can
component of a computer system select.
loop variable: See index that is built into the computer itself
variable. and whose contents are directly MHz: Megahertz; one million hertz.
accessible to the processor. See hertz.
low-level language: A
programming language that is mask: A pattern of bits for use in microcomputer: A computer, such
relatively close to the form that the bit-level logical operations. as the Apple II, whose processor is a
computer's processor can execute microprocessor.
directly. Low-level languages microprocessor: A computer
available for the Apple II include processor contained in a single
6502 machine language and 6502 integrated circuit, such as the 6502
assembly language. microprocessor used in the Apple II.

324 Glossary
mode: A state of a computer or operand: A value to which an page: (1) A screenful of information
system that determines its behavior. operator is applied. on a video display, consisting on the
modem: Modulator/demodulator; a operating system: A software Apple II of 24 lines of 40 or 80
peripheral device that enables the system that organizes the characters each. (2) An area of main
computer to transmit and receive computer's resources ai:ld memory containing text or graphical
information over a telephone line. capabilities and makes them information being displayed on the
available to the user or to screen.
monitor: See video monitor. application programs running on the pass: A single execution of a loop.
Monitor program: A system computer.
program built into the Apple II in peek: To read information directly
firmware, used for directly operator: A symbol or sequence of from a location in the computer's
inspecting or changing the contents characters, such as + or AND, memory.
of main memory and for operating specifying an operation to be
performed on one or more values peripheral: At or outside the
the computer at the boundaries of the computer itself,
machine-language level. ( the operands) to produce a result;
see arithmetic operator, either physically (as a peripheral
nested loop: A loop contained relational operator, logical device) or in a logical sense (as a
within the body of another loop and operator, unary operator, peripheral card).
executed repeatedly during each binary operator. peripheral card: A removable
pass through the containing loop. OR: A logical operator that printed-circuit board that plugs into
nested subroutine call: A call to a produces a true result if either or one of the Apple II, II Plus, or Ile's
subroutine from within the body of both of its operands are true, a false expansion slots and expands or
another subroutine. result if both of its operands are modifies the computer's capabilities
f alse; compare AND, NOT. by connecting a peripheral device or
nibble: A unit of information equal performing some subsidiary or
to half a byte, four bits, or fifty output: (1) Information transferred peripheral function.
cents; can hold any value from O to from a computer to some external
15. Sometimes spelled nybble. destination, such as the display peripheral device: A device, such
as a video monitor, disk drive,
NOT: A unary logical operator that screen, a disk drive, a printer, or a printer, or modem, used in
produces a true result if its operand modem. (2) The act or process of conjunction with a computer. Often
is false, a false result if its operand transferring such information.
(but not necessarily) physically
is true; compare AND, OR. separate from the computer and
null string: A string containing no connected to it by wires, cables, or
characters. some other form of interface,
typically by means of a peripheral
card.

Glossary 325
peripheral slot: See expansion printed-circuit board: A programmer: The human author ·
slot. hardware component of a computer . of a program; one who writes
plotting vector: A code or other electronic device, programs.
representing a single step in consisting of a flat, rectangular
piece of rigid material, commonly programming: The activity of
drawing a shape on the fiberglass, to which integrated writing programs.
high-resolution graphics screen, circuits and other electronic
specifying whether to plot a point at programming language: A set of
components are connected. rules or conventions for writing
the current screen position and in
what direction to move (up, down, printer: A peripheral device that programs.
left, or right) before processing the writes information on paper in a prompt: To remind or signal the
next vector. See shape defmition, form easily readable by humans or user that some action is expected,
shape table. literate monkeys. typically by displaying a distinctive
point of call: The point in a processor: The hardware symbol, a reminder message, or a
program from which a subroutine or component of a computer that menu of choices on the display
function is called. performs the actual computation by screen.
directly executing instructions prompt character: (1) A text
pointer: An item of information represented in machine language
consisting of the memory address of character displayed on the screen to
some other item. For example, and stored in main memory. prompt the user for some action.
Applesoft maintains internal program: (1) A set of instructions Often also identifies the program or
pointers to (among other things) the describing actions for a computer to component of the system that is
most recently stored variable, the perform in order to accomplish some doing the prompting; for example,
most recently typed program line, task, conforming to the rules and the prompt character J is used by
and the most recently read DATA conventions of a particular the Applesoft BASIC interpreter, >
item. programming language. In by Integer BASIC, and • by the
Applesoft, a sequence of program system Monitor program. Also called
poke: To store information directly prompting character. (2) Someone
in a location in the computer's lines, each with a different line
number. (2) To write a program. who is always on time.
memory.
program line: The basic unit of an prompt message: A message
pop: To remove the top entry from displayed on the screen to prompt
a stack. Applesoft program, consisting of one
or more statements separated by the user for some action. Also called
precedence: The order in which colons (:). prompting message.
operators are applied in evaluating push: To add an entry to the top of
an expression. a stack.

326 Glossary
queue: A list in which entries are read-only memory: Memory reserved word: A word or
added at one end and removed at whose contents can be read but not sequence of characters reserved by
the other, causing entries to be written; used for storing firmware. a programming language for some
removed in FIFO (first-in-first-out) Information is written into read-only special use, and therefore
order; compare stack. memory once, during manufacture; unavailable as a variable name in a
it then remains there permanently, program.
RAM: See random-access even when the computer's power is
memory. turned off, and can never be erased resident: See memory-resident,
random-access memory: Memory or changed. Compare read-write disk-resident.
in which the contents of individual memory, random-access return address: The point in a
locations can be referred to in an memory, write-only memory. program to which control returns on
arbitrary or random order. This completion of a subroutine or
read-write memory: Memory
term is often used incorrectly to whose contents can be both read function.
refer to read-write memory, but and written; often misleadingly
strictly speaking both read-only and ROM: See read-only memory.
called random-access memory, or
read-write memory can be accessed RAM. The information contained in routine: A part of a program that
in random order. This misuse of the read-write memory is erased when accomplishes some task subordinate
term random-access is an attempt to the computer's power is turned off, to the overall task of the program.
confuse new users, creating a rite of and is permanently lost unless it
passage and an excellent market for run: (1) To execute a program. (2)
has been saved on a more To load a program into main
glossaries of computer terms. permanent storage medium, such as memory from a peripheral storage
Compare read-only memory, a disk. Compare read-only
read-write memory, write-only medium, such as a disk, and
memory, random-access execute it.
memory. memory, write-only memory.
read: To transfer information into save: To transfer information from
real number: A number that may main memory to a peripheral
the computer's memory from � include a fractional part; storage medium for later use.
source external to the computer represented inside the computer in
(such as a disk drive or modem) or floating-point form. Compare scientific notation: A method of
into the computer's processor from a integer. expressing numbers in terms of
source external to the processor powers of 10, useful for expressing
(such as the keyboard or main relational operator: An operator, numbers that may vary over a wide
memory). such as > , that compares numeric range, from very small to very large.
values to produce a logical result; For example, the number of atoms
compare arithmetic operator, in a gram of hydrogen is
relational operator. approximately 6.02E23, meaning

Glossary 327
6.02 times 10 to the 23rd power. simple variable: A variable that is statement: A unit of a program in a
(The letter E stands for exponent.) not an element of an array. high-level language specifying an
The number is easier to understand soft switch: A means of changing action for the computer to perfonn,
in this fonn than in the fonn some feature of the Apple II from typically corresponding to several
602000000000000000000000. within a program; specifically, a instructions of machine language.
screen: See display screen. location in memory that produces step value: The amount by which
some special effect whenever its the index variable changes on each
scroll: To change the contents of contents are read or written. pass through a loop.
all or part of the display screen by
shifting infonnation out at one end software: Those components of a stepwise refmement: A technique
(most often the top) to make room computer system consisting of of program development in which
for new infonnation appearing at programs that determine or control broad sections of the program are
the other end (most often the the behavior of the computer. laid out first, then elaborated step
bottom), producing an effect like Compare hardware, firmware. by step until a complete program is
that of moving a scroll of paper past space character: A text character obtained.
a fixed viewing window. See whose printed representation is a string: An item of infonnation
viewport, window. blank space, typed from the consisting of a sequence of text
seed: A value used to begin a keyboard by pressing the I�s-P- -E�i
AC characters.
repeatable sequence of random bar.
numbers. strobe: (1) An event, such as a
stack: A list in which entries are change in a signal, that triggers
shape definition: A coded added or removed at one end only some action. (2) A signal whose
description of a shape to be drawn (the top of the stack), causing them change is used to trigger some
on the high-resolution graphics to be removed in LIFO action.
screen, consisting of one or more (last-in-first-out) order; compare
plotting vectors. See shape table, queue. subroutine: A part of a program
plotting vector. that can be executed on request
starting value: The value assigned from any point in the program, and
shape table: A collection of one or to the index variable on the first that returns control to the point of
more shape definitions, together pass through a loop. the request on completion.
with their indices.
startup disk: A disk containing subscript: An index number used
shape table index: A list giving software recorded in the proper to identify a particular element of
the memory addresses of the shapes fonn to be loaded into the Apple H's an array.
in a shape table. memory in order to set the system
into operation. Sometimes called a
boot disk; see boot.

328 Glossary
substring: A string that is part of truncate: To shorten by discarding video: (1) A medium for
another string. a part; specifically, to convert a real transmitting information in the form
syntax: The rules governing the number to the next lower integer. of images to be displayed on the
structure of statements or unary operator: An operator that screen of a cathode-ray tube. (2)
instructions in a programming applies to a single operand; for Information organized or
language. example, the minus sign (-) in a transmitted in video form. (3) An
negative number such as -6 is a early space pioneer.
system: A coordinated collection of unary arithmetic operator. Compare video monitor: A display device
interrelated and interacting parts binary operator.
organized to perform some function capable of receiving video signals by
or achieve some purpose. unconditional branch: A branch direct connection only, and that
that does not depend on the truth of cannot receive broadcast signals
system program: A program that any condition; compare such as commercial television. Can
makes the resources and conditional branch. be connected directly to the Apple II
capabilities of the computer computer as a display device.
available for general purposes, such user: The person operating or viewport: All or part of the display
as an operating system or a controlling a computer system. screen, used by an application
language translator. Compare user interface: The rules and program to display a portion of the
application program. conventions by which a computer information (such as a document,
system software: The component system communicates with the picture, or worksheet) that the
of a computer system consisting of person operating it. program is working on. Compare
system programs. value: An item of information that window.
text: (1) Information presented in can be stored in a variable, such as a window: (1) The portion of a
the form of characters readable by number or a string. collection of information (such as a
humans. (2) The display of variable: (1) A location in the document, picture, or worksheet)
characters on the Apple H's display computer's memory where a value that is visible in a viewport on the
screen. Compare graphics. can be stored. (2) The symbol used display screen; compare viewport.
text ftle: A file containing in a program to represent such a (2) A viewport. (3) A flat,
information expressed in text form; location; compare constant. rectangular panel, usually made of
compare binary me. silica, used in many archaic
structures as a human-to-nature
text window: An area on the Apple interface.
H's display screen within which text
is displayed and scrolled.

Glossary 329
wraparound: The automatic write-only memory: A form of Farnsfarfle's critics have denounced
continuation of text from the end of computer memory into which his project as a six-million-dollar
one line to the beginning of the next, information can be stored but never, boondoggle, but his defenders point
as on the display screen or a printer. ever retrieved, developed under out that this excess information
write: To transfer information from government contract in 1975 by would have cost more than 250
the computer to a destination Professor Hornberg T. Farnsfarfle. billion dollars to store in
external to the computer (such as a Farnsfarfle's original prototype, conventional media. Compare
disk drive, printer, or modem) or approximately one inch on each read-only memory, read-write
side, has so far been used to store memory, random-access
from the computer's processor to a more than 100 trillion words of memory.
destination external to the processor surplus federal information.
(such as main memory).

330 Glossary
Index

Cast of Characters alphabetizing strings 76 Apple Ile


altering memory 210, 244 , (comma) and 105
& (ampersand) 232 American Standard Code for enhanced 3
• (asterisk) 29 Information Interchange (ASCII) escape mode and 19
\ (backslash) 3, 16 228-230 FLASH and 116
A (caret) 29 ASC and 84, 196 HTAB and 113
: (colon) 4, 93 CHR$ and 83, 197 PR# and 102
, (comma) 93, 104, 105 comparing strings with 75-76 RECALL and 212
$ (dollar sign) in string variable names ampersand 232 SAVE and 12, 214
26 AND 32-35 SHLOAD and 156, 215
[I] (Down-Arrow key) l7-18 animation 154 upper/lowercase and 3, 18
= (equal sign) 232 annunciator outputs 119, 255-256 Applesoft Tutorial xxvi
= (equal to) 31-35 Apple Backpack: Humanized arc tangent, calculating 38, 196
1 Esc 1 (Escape key) 18 Programming in BASIC xxvii See also tangent
> (greater than) 31-35 Apple keys (@] and [!)) 100, 254 argument 35
> = (greater than or equal to) 31-35 Apple II arithmetic, integer 23
El (Left-Arrow key) 17-18 , (comma) and 105 arithmetic
< (less than) 31-35 escape mode and 19 functions 35-42
< = (less than or equal to) 31-35 HTAB and 1 13 built in 35-39
- (minus sign) 29 memory map 267 operators 29-30
< > (not equal to) 31-35 RECALL and 212 arrays 26, 70-74
+ (plus sign) 29 SAVE and 12, 214 cassette tape and 297-298
? (question mark) 106 SHLOAD and 156, 215 defining 199
G (Right-Arrow key) 17-18 speaker and 118 dimensioning 72
] (right bracket) 2 upper/lowercase and 3, 18 memory allocation and 269-271
; (semicolon) 104, 110, 112 Apple II Plus multidimensional 72-74
/ (slash) 29 , (comma) and 105 RECALL and 212
[!] (Up-Arrow key) 17-18 escape mode and 19 storing on cassette tape 216
HTAB and 113 arrow keys 17-18, 283
A RECALL and 212 ASC function 84, 196
SAVE and 12, 214 ASCII
ABS function 36, 196 SHLOAD and 156, 215 See American Standard Code for
absolute value, calculating 36, 196 upper/lowercase and 3, 18 Information Interchange
adding lines 4 Apple Ile (ASCII)
address(es) FLASH and 116 assigning values 27-28
memory 162-165 PR# and 102 assignment statements 27-28, 196
return 58, 59, 60 upper/lowercase and 3, 18 * (asterisk), for multiplication 29

Index 331
ATN function 38, 196 integers 36-37 COLOR= statement 123-124, 197
as reserved word 232 length of strings 76-77 as reserved word 232
audio output 118, 256-257 logarithm 39, 207 color(s)
auto-repeat 17 sine 37, 215 in high-resolution graphics 133-134,
square root 37, 215 202
B string length 206 in low-resolution graphics 123-124,
tangent 38, 217 129, 202, 214
\ (backslash) 3, 16 CALL statement 164-165, 197 setting with COLOR= 197
backspace (G) 17 CAN'T CONTINUE message 238 monochrome display and 124, 133
BAD SUBSCRIPT message 237 canceling reading 129
BASIC lines with � 16 , (comma) 105
Applesoft BASIC and 2 A (caret), for exponentiation 29 INPUT and 93
Converting programs to Applesoft cassette tape 296-298 PRINT and 104
BASIC 291-293 arrays and 297-298 canceling TRACE with 173
See also Integer BASIC I CONTROL H RESET I and 296 resetting
BASIC Programming With ProDOS LOAD and 13 HIMEM: with 169
xxvi loading from 297, 298 LOMEM: with 170
bell loading shape tables from 215, 298 comma tabbing, differences between
using � to sound 118 reading from 100, 297-298 40- and 80-colurnn display and
bit masking 167, 218 RECALL and 212 286
blank lines 105 SAVE and 12 commands
eliminating 104 storing . BSAVE 149
blocks, _plotting 125-126 arrays on 216 CLEAR 8, 197
branching 44-49 shape tables on 156-157 CONT 15, 197
condition.al 46-49, 59-60, 204, 209 writing to 119, 296, 297 DEL 5-6, 198
to lines 46-47 changing lines 6 LIST 9-10, 206
to subroutines 59-60 characters, inputting single 94-95 LOAD 12-13, 100, 207, 297
unconditional 44-45, 201 CHR$ function 83, 197 NEW 7-8, 208
to variables 45 CLEAR command 8, 197 NOTRACE 174, 208
BSAVE command 149 clearing RUN 10-11, 213
graphics pages 253-254 SAVE 11-12, 296
C memory 7-8, 208 TRACE 173, 217
screen 19, 203 comments
calculating text window 109, 247 See REM statement
absolute value 36, 196 variables (unused) 171-172 comparing strings 75-76 compilers 263
arc tangent 38, 196 : (colon) concatenating strings 77-79
cosine 37, 198 INPUT and 93 LEN and 78
exponents 38, 199 to separate statements 4 PRINT and 104

332 Index
condensing programs 260-264 D E
conditional branching 46-49, 59-60,
204, 209 DATA statement 96-98, 198 editing programs 16-20
constants, string 7 4-84 control characters and 98 80-column display, differences from
CONT command 15, 197 debugging 172-174, 257-258 40-column display 286
control characters NOTRACE and 174, 208 80-Column Text Card
DATA and 98 TRACE and 173, 217 , (comma) and 105
INPUT and 91 DEF FN statement 40-42, 198 FLASH and 116
control stack 8, 60, 65 deferred execution 2, 4 HTAB and 113
memory allocation and · 269-271 defining PR# and 102
arrays 199 elements, array 26, 70

stopping functions 40-42 END statement 67, 199
infinite loops with 45, 53 DEL command 5-6, 198 enhanced Apple Ile, upper/lowercase
programs with 13, 14 deleting lines 5-6, 198 and 3
� using to sound bell 118 DIM statement 72, 199 = (equal sign), with reserved words
I CONTROL KI], REM statements and dimensioning arrays 72 232
185 disk operating system = (equal to) 31-35
I CONTROL H RESET I See DOS, ProDOS error code 62-63
cassette tape and 296 display error handling 62-66
CONT and 15 differences between 40- and soft switches and 257-258
stopping programs with 14-15 80�column 286 error messages 236-242
� interrupting screen monochrome 124, 133 BAD SUBSCRIPT 237
output with 13 DIVISION BY ZERO message 238 CAN'T CONTINUE 238
�. canceling lines with 16 $ (dollar sign) in string variable names DIVISION BY ZERO 238
converting 26 FORMULA TOO COMPLEX 238
programs to Applesoft BASIC DOS ILLEGAL DIRECT 238
291-293 IN# and 87, 102 ILLEGAL QUANTITY 239
strings 81-84, 216 PR# and 87, 102 NEXT WITHOUT FOR 239
coordinates [D (Down-Arrow key) 17-18 OUT OF DATA 239
in high-resolution graphics 134-136 DRAW statement 152-153, 199 OUT OF MEMORY 240
in low-resolution graphics 125-126 animation with 154 OVERFLOW 240
COS function 37, 198 See also XDRAW REDIM'D ARRAY 240-241
cosine, calculating 37, 198 RETURN WITHOUT GOSUB 241
cursor STRING TOO LONG 241
moving 17-20, 104-105, 247-249, SYNTAX ERROR 241
282-283 TYPE MISMATCH 241
position of 248 UNDEF'D FUNCTION 242
POS �d 114 UNDEF'D STATEMENT 242
in windo\vs 248-249

Index 333
I esc I (Escape key) 18 free memory 171-172, 201 G
escape mode 18-20, 282-283 functions
differences betw:een 40- and ABS 36, 196 game paddle
80-column display and 286 arithmetic 35-42 See hand controls
executing ASC 84, 196 GET statement 94-95, 201
machine-language subroutines with ATN 38, 196, 232 � and 14
CALL 164-166, 197 CHR$ 83, 197 GOSUB statement 55-60, 201
programs 10-1 1, 213 cos 37, 198 GOTO statement 44-46, 201
subroutines with GOSUB 201 defining 40-42 GR statement 122-123, 202
execution EXP 38, 199 graphics
deferred 2, 4 FRE 171-172, 201 display, switching from text to 109
immediate 2, 3 INT 36-37, 205 full screen 123, 134
interrupting 167-168, 192-193, 218 LEFT $ 79, 206 HGR and 130
resuming 15, 197, 212 LEN 76-77, 78, 206 high resolution 130-138, 202, 203
stopping 199, 216 LOG 39, 207 low resolution 122-129, 197, 202,
tracing 173-174, 208, 217 memory allocation and 269-271 210, 214, 218
EXP function 38, 199 MID$ 80, 207 mixing with text 126, 134, 136-137
exponents, calculating 38, 199 naming 41 modes, switching between 251-253
expressions 28-35 PDL 99-100, 209 pages 130-132, 137-138, 202, 250-254
EXTRA IGNORED message 89, 95 PEEK 162-163, 210 in text mode (MouseText) 158-159
POS 114, 211 > (greater than) 31-35
F RIGHT $ 81, 213 > = (greater than or equal to) 31-35
RND 39-40, 213
FLASH statement 115-116, 200 SCRN 129, 214, 232 H
differences between 40- and SGN 36, 214
80-column display and 286 SlN 37, 215 hand controls 99-100, 254-255
FN 200 SPC 109-110, 215, 232 annunciator outputs and 1 19
FOR statement 52-53, 200 SQR 37, 215 PDL and 99-100, 209
.formatting STR$ 82, 216 utility strobe and 119
numbers 106-108, 278-280 string conversion 81-84 HCOLOR= statement 133-134, 202
output 103-106 substring 79-81 as reserved word 232
text 108-1 17 TAB 111-112, 216 HGR statement 130-131, 202
FORMULA TOO COMPLEX message TAN 38, 217 HGR2 statement 131-132, 202
238 trigonometric 37-38 high memory 168-169, 203
40-column display, differences from user defined 198, 200 high-resolution graphics 130-138, 202
80-column display 286 USR 165-166, 217 color in 133-134
fractions 30 VAL 82-83, 218 coordinates in 134-136
FRE function 171-172, 201 pages 137-138, 202
plotting
lines in 135-136
points in 134, 203

334 Index
high-resolution page 2, GR and 123 inputting line numbers 3, 4
HIMEM: statement 168-169, 203 data from within programs 96-98 lines
as reserved word 232 single characters 94-95 adding 4
HLIN statement 127, 203 INT function 36-37, 205 blank 105
HOME statement 109 1 203 integer(s) 205 eliminating 104
horizontal lines, in low-resolution arithmetic 23 branching to 46-47
graphics 127, 203 calculating 36-37 canceling with � 16
HPLOT statement 134-136, 203 Integer BASIC, differences from changing 6_
HTAB statement 1 12-1 13, 204 Applesoft BASIC 288-293 deleting 5-6, 198
differences between 40- and See also BASIC horizontal 127, 203
SO-column display and 286 interrupting plotting in high-resolution graphics
See also TAB, VTAB execution 167-168, 192-193, 218 135-136
programs 13-15, 14-15 program 2, 3
I screen output 13 vertical 128, 218
INVERSE statement 115-1 16, 205 LIST command 9-10, 206
IF ... THEN statement 47-49, 204 differences between 40- and listing programs 9-10, 206
ILLEGAL DIRECT message 238 SO-column display and 286 LOAD command 12-13, 100, 207, 297
ILLEGAL QUANTITY message 239 inverse tangent loading
immediate execution 2, 3 See arc tangent from cassette tape 297, 298
IN# statement 86-87, 205 programs 12-13, 207
DOS and 87, 102 J, K shape tables 146-150
ProDOS and 87, 102 from cassette tape 215, 298
as reserved word 232 keyboard LOG function 39, 207
index, shape table 144-145 input from 201, 249 logarithm, calculating 39, 207
index variable 50 keyboard introduction disk xxvi logical operators 32-35
infinite loops, stopping 45, 53 keyword tokens 274-275 LOMEM: statement 170, 207
input 86-100 as reserved word 232
accepting 88-94 L loops 50-55
cassette tape 100 infinite, stopping 45, 53
designating source of 86-87, 205 G (Left-Arrow key) 17 -18 nesting 54-55
keyboard 201, 249 LEFT$ function 79, 206 loudspeaker
numeric 91-94 LEN function 76°77, 206 See speaker
string 90-91 concatenating strings and 78 low memory 170, 207
INPUT statement 88-94, 205 length of strings, calculating 76-77 low-resolution graphics 122-129, 202
: (colon) and 93 < (less than) 31-35 colors in 214
, (comma) and 93 < = (less than or equal to) 31-35 setting with COLOR= 197
control characters and 91 LET statement 27-28 coordinates in 125-126
multiple 89 See also assignment statements plotting in 210
vertical lines in 218

Index 335
lowercase 3, 18 menus, designing 184 numeric
INVERSE and 115 MID$ function 80, 207 input 91-94
strings and 74 - (minus sign), for subtraction 29 values 106-108
monochrome display, colors and 124, variables, RUN and 11
133
M mouse 308-315 0
using 308-311
machine-language subroutines, MOUSE.ORAW program 312-314 ON...GOSUB statement 59-60, 209
executing with CALL 164-166, 197 MOUSE.MOVE program 311-312 ON ... GOTO statement 46-47, 209
manuals MouseText 158-159 IF ... THEN and 48
Apple Backpack: Humanized multidimensional arrays 72-74 ONERR GOTO statement 62-64, 209
Programming in BASIC xxvii multiple 6 key (@]) 100, 254
Applesoft Tutorial xxvi INPUT statements 89 operating system
BASIC Programming With statements 4-5 See DOS, ProDOS
ProDOS xxvi operators
keyboard introduction disk xxvi N arithmetic 29-30
owner's manual xxvi logical 32-35
map, memory (Apple II) 267 naming functions 41 precedence of 33-35
masking 167, 218 nesting relational 30-35, 75-76
memory loops 54-55 OR 32-35
addresses 162-165 subroutines 57 OUT OF DATA message 239
allocation of 268-271 NEW command 7-8, 208 OUT OF MEMORY message 240
altering 163-165, 210, 244 NEXT statement 53-54, 55, 208 output(s) 101-119
clearing 7-8, 208 NEXT WITHOUT FOR message 239 annunciator 119, 255-256
examining 162-163, 210 NORMAL statement 116, 208 audio 118, 256-257
free 171-172, 201 NOT 32-35 cassette tape 119
high 168-169, 203 < > (not equal to) 31-35 formatting 103-106
low 170, 207 NOTRACE command 174, 208 specifying destination of 101-103,
managing 149, 157, 168-172 null string 75 211
map (Apple II) 267 numbers speed of 117, 215
page2, high resolution, GR and 123 formatting 106-108, 278-280 OVERFLOW message 240
page zer0 271-27 4 line 3, 4 owner's manual xxvi
pages, graphics 130-132, 202, random 39-40, 213
250-254 real 23-24, 23-24 p
protecting 203 rounding 37
saving 260-264 paddles
See hand controls
page 2, high resolution, GR and 123

336 Index
page zero 271-27 4 debugging 172-174, 208, 217, 257-258 reading
pages, graphics 130-132, 202, 250-254 editing 16-20 from cassette tape 297-298
clearing 253-254 executing 10-11, 213 colors 129
protecting 137-138 execution, stopping 67, 199, 216 hand-control buttons 100
parentheses, precedence and 35 with � 13, 14 real
PDL function 99-100, 209 with I CONTROL H RESET I 14-15 numbers 23
PEEK function 162-163, 210 flow, controlling 44-49 variables 23-24
planning programs 176-183 inputting data from within 96-98 RECALL statement 100, 212, 297-298
PLOT statement 125-126, 210 interrupting 13-15, 14-15 REDIM'D ARRAY message 240-241
plotting line 2, 3 REENTER message 90
lines, in high-resolution graphics listing 9-10, 206 relational operators 30-35
135-136 loading 12-13, 207 comparing strings with 75-76
in low-resolution graphics 210 MOUSE.DRAW 312-314 REM statement 6, 184, 185, 212
points, in high-resolution graphics MOUSE.MOVE 31 1-312 I CONTROL H1) and 185
134-136, 203 planning 176-183 reserved words 232-233
vectors in shape tables 139-140 postage rates 176-193, 300-306 memory allocation and 269-271
+ (plus sign), for addition 29 resuming 13-15 See also tokens
points, plotting in high-resolution saving 11, 214 reset vector 15
grpahics 134-136, 203 specifications of 176-180 resetting
POKE statement 163-164, 210 prompt character (I) 2 variables 8, 197, 208
POP statement 58-59, 60-62, 65, 210 prompting for input 88-89 RESTORE statement 98-99, 212
POS function 114, 211 protecting RESUME statement 65, 212
postage rates program 176-193, high-resolution graphics 137-138 resuming
300-306 memory 203 execution 15, 197, 212
PR# statement 101-103, 211 shape tables 149 normal error handling 65-66
DOS and 87, 102 PUSH 58-59 programs 13-15
ProOOS and 87, 102 return address 58, 59, 60
as reserved word 232 Q RETURN statement 55-60, 212
precedence of operators 33-35 RETURN WITHOUT GOSUB message
PRINT statement 103-106, 211 ? (question mark), instead of PRINT 241
? (question mark) instead of 106 106 reversed text
spaces in 109-110 See FLASH, INVERSE
ProDOS R G (Right-Arrow key) 17-18
IN# and 87, 102 ] (right bracket), as prompt character
PR# and 87, 102 random numbers 39-40, 213
READ statement 96-98, 211 2
program(s) 2 RIGHT$ function 81, 213
condensing 260-264 RND function 39-40, 213
converting to Applesoft BASIC ROT= statement 155-156, 213
291-293 as reserved word 232

Index 337
rotating shapes 155-156, 213 shapes END 67, 199
rounding numbers 37 drawing 152-154, 199 FLASH 115-116, 200, 286
RUN command 10-11, 213 erasing 153, 219 FOR 52, 200
rotating 155-156, 213 GET 14, 94-95, 201
s scale of 154-155, 214
SHLOAD statement 100, 156-157, 215,
GOSUB 55-60, 201
GOTO 44-46, 201
SAVE command 11-12, 296 298 GR 122-123, 202
saving sign, determining 36, 214 HCOLOR= 133-134, 202, 232
memory 260-264 SIN function 37, 215 HOR 130-131, 202
programs 11, 214 sine, calculating 37, 215 HGR2 131-132, 202
shape tables 149-150 / (slash), for division 29 HIMEM: 168-169, 203, 232
scale of shapes 154-155, 214 soft switches 244, 250-251 HLIN 127, 203
SCALE= statement 154-155, 214 a key (rn) 100, 254 HOME 109, 203
as reserved word 232 error handling and 257-258 HPLOT 134-136, 203
scientific notation 107-108 sound See speaker 118, 256-257 HTAB 112-113, 204, 286
screen spaces 215 IF ... THEN 47-49, 204
clearing 19, 203 with PRINT 109-110 IN# 86-87, 102, 205
display 286 SPC function 109-110, 215 INPUT 88-94, 205
output, interrupting 13 as reserved word 232 INVERSE 1 15-1 16, 205, 286
text 244 ; (semicolon) and 110 LET 27-28
SCRN function 129, 214 speaker 118, 256-257 LOMEM: 170, 207, 232
as reserved word 232 specifications of programs 176-180 multiple 4-5
scrolling text 247 specifying output destination 101-103, NEXT 53-54, 55, 208
; (semicolon) 211 NORMAL 1 16, 208
PRINT and 104 SPEED= statement 117, 215 ON ... GOSUB 59-60, 209
SPC and 110 as reserved word 232 ON ... GOTO 46-47, 48, 209
TAB and 112 SQR function 37, 215 ONERR GOTO 62-64, 209
SGN function 36, 214 square root, calculating 37, 215 PLOT 125-126, 210
shape tables 138-157 stack See control stack 8, 60, 65 POKE 163-164, 210
creating 138-150 statement( s) 2 POP 58-59, 60-62, 65, 210
index of 144-145 assignment 27-28, 196 PR# 87, 101-103, 211
loading 146-149, 149-150 CALL 164-165, 197 PRINT 103-106, 109-1 10, 211
from cassette tape 215, 298 COLOR= 123-124, 197, 232 READ 96-98, 211
plotting vectors in 139-140 DATA 96-98, 198 RECALL 100, 212, 297-298
protecting 149 DEF FN 40-42, 198 REM 6, 184, 185, 212
saving 149-150 DIM 72, 199 repeated
storing on cassette tape 156-157 DRAW 152-153, 154, 199 RESTORE 98-99, 212
using 151-157 RESUME 65, 212

338 Index
RETURN 55-60, 212 variables 23-24, 25-26, 75 text
ROT= 155-156, 213, 232 RUN and 11 formatting 108-117
SCALE= 154-155, 214, 232 See also substrings HLIN in 127
SHLOAD 100, 156-157, 215, 298 STRING TOO LONG message 241 mixing with graphics 126, 134,
SPEED= 1 17, 215, 232 strobe, utility 119, 255 136-137
STOP 67, 216 · subroutines 55-62 reversed
STORE 216, 297 branching to 59-60 See FLASH, INVERSE
TEXT 109, 123, 217 ending 212 screen 244
VLIN 128, 218 executing with GOSUB 201 scrolling 247
VTAB 113-114, 218 machine language, executing with VLIN in 128
WAIT 166-168, 218 CALL 164-166, 197 text card, 80 column
XDRAW 153-154, 219 nesting 57 FLASH and 116
step value 52 user defined 165-166, 217 HTAB and 113
STOP statement 67, 216 subscripts, array 26, 70 text display, switching from graphics
stopping substring(s) to 109
infinite loops 45, 53 functions 79-81 text mode, graphics in (MouseText)
program execution 67, 199, 216 See also strings 158-159
with � 13, 14 switches, soft 244, 250-251, 257-258 TEXT statement 109, 217
with I CONTROL H RESET I 14-15 switching high-resolution page 2 and 123
STORE statement 216, 297 between graphics modes 251-253 text window 19, 109-110, 163-164, 203
storing from graphics to text display 109 clearing 109, 247
arrays on cassette tape 216 syntax definitions 222-225 HTAB and 112
shape tables on cassette tape SYNTAX ERROR message 241 setting 245-246
156-157 system THEN statement
STR$ function 82, 216 utilities 162-168 See IF...THEN
string(s) 7 4-84 TO, as reserved word 232
alphabetizing 76 T tokens 274-275
calculating length of 206 See also reserved words
comparing 75-76 TAB function 111-112, 216 TRACE command 173, 217
concatenating 77-79 as reserved word 232 tracing execution 173-174, 208, 217
PRINT and 104 ; (semicolon) and 112 trigonometric functions 37-38
constants 74-84 See also HTAB, VTAB TYPE MISMATCH message 241
converting 81-84, 216 TAN function 38, 217
dividing
input 90-91
tangent, calculating 38, 217
See also arc tangent
u
lowercase and 7 4 tape cassette unconditional branching 44-45, 201
null 75 See cassette tape UNDEF'D FUNCTION message 242
numeric value of 218 UNDEF'D STATEMENT message 242
IT) (Up-Arrow key) 17-18

Index 339
uppercase 3, 18 vector(s) words, reserved 232-233, 269-271
user-defined plotting, in shape tables 139-140 writing
functions 198, 200 reset 15 to cassette tape 296, 297
subroutines 165-166, 217 vertical lines, in low-resolution
USR function 165-166, 217 graphics 128, 218 X
utilities, system 162-168 VLIN statement 128, 218
utility strobe 119, 255 VTAB statement 113-114, 218 XDRAW statement 153-154, 219
See also HTAB, TAB animation with 154
V See also DRAW
VAL function 82-83, 218
w XPLOT 232
value(s) WAIT statement 166-168, 218 Y, Z
assigning 27-28 window(s)
variable(s) 22-26 cursor in 248-249 zero page 271-274
array 26, 70-74 text 19, 109-110, 163-164, 203
branching to 45 clearing 109, 247 •
clearing unused 171-172 HTAB and 112
index 50 setting 245-246
memory allocation and 269-271
numeric 11
real 23-24
resetting 8, 197, 208
string 11, 23-24, 25-26, 75

340 Index

You might also like