********* Welcome to Project 64! The goal of Project 64 is to preserve Commodore 64 related documents in electronic text format that might otherwise cease to exist with the rapid advancement of computer technology and declining interest in 8- bit computers on the part of the general population. If you would like to help by converting C64 related hardcopy documents to electronic texts please contact the manager of Project 64, Cris Berneburg, at <74171.2136@compuserve.com>. Extensive efforts were made to preserve the contents of the original document. However, certain portions, such as diagrams, program listings, and indexes may have been either altered or sacrificed due to the limitations of plain vanilla text. Diagrams may have been eliminated where ASCII-art was not feasible. Program listings may be missing display codes where substitutions were not possible. Tables of contents and indexes may have been changed from page number references to section number references. Please accept our apologies for these limitations, alterations, and possible omissions. The author(s) of the original document and members of Project 64 make no representations about the accuracy or suitability of this material for any purpose. This etext is provided "as-is". Please refer to the warantee of the original document, if any, that may included in this etext. No other warantees, express or implied, are made to you as to the etext or any medium it may be on. Neither the author(s) nor the members of Project 64 will assume liability for damages either from the direct or indirect use of this etext or from the distribution of or modification to this etext. ********* The Project 64 etext of the Commodore 64 Programmer's Reference Guide, first edition. Converted to etext by Ville Muikkula. Some errors in the original document were corrected in this etext. C64PRG10.TXT, June 1996, etext #46 ********* ~ I would like to thank the following persons for their valuable help: Jouko Valta for the memory maps on pages 310-334. Marko Makela for the combined table of memory maps on pages 264-266. Cris Berneburg for proof reading. Kimmo Hamalainen for proof reading. There was a lot of work, but finally, after five weeks of correcting OCR-errors and formatting the text to readable format, it is ready. I hope that this massive project shows to the C= community that it is in a fact possible for one man to convert a 500 page book to ASCII text. One just have to be dedicated, believe that it can be done and have the PATIENCE for it... and lots of free time. So, who's going to etext Inside Commodore DOS? If you find errors in the text, please report them so that they can be fixed. There should not be many, though... There are some pictures missing on pages 132,157,162-163,195,364-365, 377-378,380-381,404,406-407,416-417,421,459,476-477 and 481. Also the schematics of C-64 are not available. I apologize for the possible inconvenience this might cause. Ville Muikkula or . ********* Note: To extract the ascii text basic programs all at once from this etext use "tok64" by Cris Berneburg <74171.2136@compuserve.com>. ********* Windows 95 MS-DOS Edit is the ideal program for reading this etext. Just check that ANSI.SYS is loaded in CONFIG.SYS and issue the command: mode con lines=50 Now a whole page fits nicely on the screen and you can use Page Up/Page Down keys to flip pages. Just be sure that the ~ characters are always on the last line of the screen. ********* ~ COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE Published by Commodore Business Machines, Inc. and Howard W. Sams & Co., Inc. i ~ FIRST EDITION FOURTH PRINTING-1983 Copyright (C) 1982 by Commodore Business Machines, Inc. All rights reserved. This manual is copyrighted and contains proprietary information. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photo- copying, recording, or otherwise, without the prior written permission of COMMODORE BUSINESS MACHINES, Inc. ii ~ TABLE OF CONTENTS INTRODUCTION ....................................................... ix o What's Included? .............................................. x o How to Use This Reference Guide ............................... xi o Commodore 64 Applications Guide ............................... xii o Commodore Information Network ................................. xvii 1. BASIC PROGRAMMING RULES ......................................... 1 o Introduction .................................................. 2 o Screen Display Codes (BASIC Character Set) .................... 2 The Operating System (OS) ................................... 2 o Programming Numbers and Variables ............................. 4 Integer, Floating-Point and String Constants ................ 4 Integer, Floating-Point and String Variables ................ 7 Integer, Floating-Point and String Arrays ................... 8 o Expressions and Operators ..................................... 9 Arithmetic Expressions ...................................... 10 Arithmetic Operations ....................................... 10 Relational Operators ........................................ 12 Logical Operators ........................................... 13 Hierarchy of Operations ..................................... 15 String Operations ........................................... 16 String Expressions .......................................... 17 o Programming Techniques ........................................ 18 Data Conversions ............................................ 18 Using the INPUT Statement ................................... 18 Using the GET Statement ..................................... 22 How to Crunch BASIC Programs ................................ 24 2. BASIC LANGUAGE VOCABULARY ....................................... 29 o Introduction .................................................. 30 o BASIC Keywords, Abbreviations, and Function Types ............. 31 o Description of BASIC Keywords (Alphabetical) .................. 35 o The Commodore 64 Keyboard and Features ........................ 93 o Screen Editor ................................................. 94 iii ~ 3. PROGRAMMING GRAPHICS ON THE COMMODORE 64 .................................................... 99 o Graphics Overview ............................................. 100 Character Display Modes ..................................... 100 Bit Map Modes ............................................... 100 Sprites ..................................................... 100 o Graphics locations ............................................ 101 Video Bank Selection ........................................ 101 Screen Memory ............................................... 102 Color Memory ................................................ 103 Character Memory ............................................ 103 o Standard Character Mode ....................................... 107 Character Definitions ....................................... 107 o Programmable Characters ....................................... 108 o Multi-Color Mode Graphics ..................................... 115 Multi-Color Mode Bit ........................................ 115 o Extended Background Color Mode ................................ 120 o Bit Mapped Graphics ........................................... 121 Standard High-Resolution Bit Map Mode ....................... 122 How It Works ................................................ 122 o Multi-Color Bit Map Mode ...................................... 127 o Smooth Scrolling .............................................. 128 o Sprites ....................................................... 131 Defining a Sprite ........................................... 131 Sprite Pointers ............................................. 133 Turning Sprites On .......................................... 134 Turning Sprites Off ......................................... 135 Colors ...................................................... 135 Multi-Color Mode ............................................ 135 Setting a Sprite to Multi-Color Mode ........................ 136 Expanded Sprites ............................................ 136 Sprite Positioning .......................................... 137 Sprite Positioning Summary .................................. 143 Sprite Display Priorities ................................... 144 Collision Detects ........................................... 144 o Other Graphics Features ....................................... 150 Screen Blanking ............................................. 150 Raster Register ............................................. 150 Interrupt Status Register ................................... 151 Suggested Screen and Character Color Combinations ........... 152 iv ~ o Programming Sprites-Another Look .............................. 153 Making Sprites in BASIC-A Short Program ..................... 153 Crunching Your Sprite Programs .............................. 156 Positioning Sprites on the Screen ........................... 157 Sprite Priorities ........................................... 161 Drawing a Sprite ............................................ 162 Creating a Sprite ... Step by Step .......................... 163 Moving Your Sprite on the Screen ............................ 165 Vertical Scrolling .......................................... 166 The Dancing Mouse-A Sprite Program Example .................. 166 Easy Spritemaking Chart ..................................... 176 Spritemaking Notes .......................................... 177 4. PROGRAMMING SOUND AND MUSIC ON YOUR COMMODORE 64 ............................................ 183 o Introduction .................................................. 184 Volume Control .............................................. 186 Frequencies of Sound Waves .................................. 186 o Using Multiple Voices ......................................... 187 Controlling Multiple Voices ................................. 191 o Changing Waveforms ............................................ 192 Understanding Waveforms ..................................... 194 o The Envelope Generator ........................................ 196 o Filtering ..................................................... 199 o Advanced Techniques ........................................... 202 o Synchronization and Ring Modulation ........................... 207 5. BASIC TO MACHINE LANGUAGE ....................................... 209 o What is Machine Language? ..................................... 210 What Does Machine Code Look Like? ........................... 211 Simple Memory Map of the Commodore 64 ....................... 212 The Registers Inside the 6510 Microprocessor ................ 213 o How Do You Write Machine Language Programs? ................... 214 64MON ....................................................... 215 o Hexadecimal Notation .......................................... 215 Your First Machine Language Instruction ..................... 218 Writing Your First Program .................................. 220 o Addressing Modes .............................................. 221 Zero Page ................................................... 221 The Stack ................................................... 222 v ~ o Indexing ...................................................... 223 Indirect Indexed ............................................ 223 Indexed Indirect ............................................ 224 Branches and Testing ........................................ 226 o Subroutines ................................................... 228 o Useful Tips for the Beginner .................................. 229 o Approaching a Large Task ...................................... 230 o MCS6510 Microprocessor Instruction Set- Alphabetic Sequence ........................................... 232 Instruction Addressing Modes and Related Execution Times ................................... 254 o Memory Management on the Commodore 64 ......................... 260 o The KERNAL .................................................... 268 o KERNAL Power-Up Activities .................................... 269 How to Use the KERNAL ....................................... 270 User Callable KERNAL Routines ............................... 272 Error Codes ................................................. 306 o Using Machine Language From BASIC ............................. 307 Where to Put Machine Language Routines ...................... 309 How to Enter Machine language ............................... 309 o Commodore 64 Memory Map ....................................... 310 Commodore 64 Input/Output Assignments ....................... 320 6. INPUT/OUTPUT GUIDE .............................................. 335 o Introduction .................................................. 336 o Output to the TV .............................................. 336 o Output to Other Devices ....................................... 337 Output to Printer ........................................... 338 Output to Modem ............................................. 339 Working With Cassette Tape .................................. 340 Data Storage on Floppy Diskettes ............................ 342 o The Game Ports ................................................ 343 Paddles ..................................................... 346 Light Pen ................................................... 348 o RS-232 Interface Description .................................. 348 General Outline .............................................. 348 Opening an RS-232 Channel .................................... 349 Getting Data From an RS-232 Channel .......................... 352 Sending Data to an RS-232 Channel ............................ 353 Closing an RS-232 Data Channel ............................... 354 Sample BASIC Programs ........................................ 356 vi ~ Receiver/Transmitter Buffer Base Location Pointers ........... 357 Zero-Page Memory Locations and Usage for RS-232 System Interface ................................ 358 Nonzero-Page Memory Locations and Usage for RS-232 System Interface ................................ 358 o The User Port ................................................. 359 Port Pin Description ........................................ 359 o The Serial Bus ................................................ 362 Serial Bus Pinouts .......................................... 363 o The Expansion Port ............................................ 366 o Z-80 Microprocessor Cartridge ................................. 368 Using Commodore CP/M (R) .................................... 369 Running Commodore CP/M (R) .................................. 369 APPENDICES ......................................................... 373 A. Abbreviations for BASIC Keywords ............................ 374 B. Screen Display Codes ........................................ 376 C. ASCII and CHR$ Codes ........................................ 379 D. Screen and Color Memory Maps ................................ 382 E. Music Note Values ........................................... 384 F. Bibliography ................................................ 388 G. VIC Chip Register Map ....................................... 391 H. Deriving Mathematical Functions ............................. 394 I. Pinouts for Input/Output Devices ............................ 395 J. Converting Standard BASIC Programs to Commodore 64 BASIC ........................................ 398 K. Error Messages .............................................. 400 L. 6510 Microprocessor Chip Specifications ..................... 402 M. 6526 Complex Interface Adapter (CIA) Chip Specifications ....................................... 419 N. 6566/6567 (VIC-II) Chip Specifications ...................... 436 0. 6581 Sound Interface Device (SID) Chip Specifications ....... 457 P. Glossary .................................................... 482 INDEX .............................................................. 483 COMMODORE 64 QUICK REFERENCE CARD .................................. 487 SCHEMATIC DIAGRAM OF THE COMMODORE 64 .............................. 491 vii ~~ INTRODUCTION The COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE has been developed as a working tool and reference source for those of you who want to maximize your use of the built-in capabilities of your COMMODORE 64. This manual contains the information you need for your programs, from the simplest example all the way to the most complex. The PROGRAMMER'S REFERENCE GUIDE is designed so that everyone from the beginning BASIC programmer to the professional experienced in 6502 machine language can get information to develop his or her own creative programs. At the same time this book shows you how clever your COMMODORE 64 really is. This REFERENCE GUIDE is not designed to teach the BASIC programming language or the 6502 machine language. There is, however, an extensive glossary of terms and a "semi-tutorial" approach to many of the sections in the book. If you don't already have a working knowledge of BASIC and how to use it to program, we suggest that you study the COMMODORE 64 USER'S GUIDE that came with your computer. The USER'S GUIDE gives you an easy to read introduction to the BASIC programming language. If you still have difficulty understanding how to use BASIC then turn to the back of this book (or Appendix N in the USER'S GUIDE) and check out the Bibliography. The COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE is just that; a reference. Like most reference books, your ability to apply the information creatively really depends on how much knowledge you have about the subject. In other words if you are a novice programmer you will not be able to use all the facts and figures in this book until you expand your current programming knowledge. ix ~ What you can do with this book is to find a considerable amount of valuable programming reference information written in easy to read, plain English with the programmer's jargon explained. On the other hand the programming professional will find all the information needed to use the capabilities of the COMMODORE 64 effectively. WHAT'S INCLUDED? o Our complete "BASIC dictionary" includes Commodore BASIC language commands, statements and functions listed in alphabetical order. We've created a "quick list" which contains all the words and their abbreviations. This is followed by a section containing a more detailed definition of each word along with sample BASIC programs to illustrate how they work. o If you need an introduction to using machine language with BASIC programs our layman's overview will get you started. o A powerful feature of all Commodore computers is called the KERNAL. It helps insure that the programs you write today can also be used on your Commodore computer of tomorrow. o The Input/Output Programming section gives you the opportunity to use your computer to the limit. It describes how to hook-up and use everything from lightpens and joysticks to disk drives, printers, and telecommunication devices called modems. o You can explore the world of SPRITES, programmable characters, and high resolution graphics for the most detailed and advanced animated pictures in the microcomputer industry. o You can also enter the world of music synthesis and create your own songs and sound effects with the best built-in synthesizer available in any personal computer. o If you're an experienced programmer, the soft load language section gives you information about the COMMODORE 64's ability to run CP/M* and high level languages. This is in addition to BASIC. Think of your COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE as a useful tool to help you and you will enjoy the -hours of programming ahead of you. ----------- * CP/M is a registered trademark of Digital Research, Inc. x INTRODUCTION ~ HOW TO USE THIS REFERENCE GUIDE Throughout this manual certain conventional notations are used to de- scribe the syntax (programming sentence structure) of BASIC commands or statements and to show both the required and optional parts of each BASIC keyword. The rules to use for interpreting statement syntax are as follows: 1. BASIC keywords are shown in capital letters. They must appear where shown in the statement, entered and spelled exactly as shown. 2. Items shown within quotation marks (" ") indicate variable data which you must put in. Both the quotation marks and the data inside the quotes must appear where shown in each statement. 3. Items inside the square brackets ([ ]) indicate an optional state- ment parameter. A parameter is a limitation or additional qualifier for your statements. If you use an optional parameter you must supply the data for that optional parameter. In addition, ellipses (...) show that an optional item can be repeated as many times as a programming line allows. 4. If an item in the square brackets ([ ]) is UNDERLINED, that means that you MUST use those certain characters in the optional para- meters, and they also have to be spelled exactly as shown. 5. Items inside angle brackets (< >) indicate variable data which you provide. While the slash (/) indicates that you must make a choice between two mutually exclusive options. EXAMPLE OF SYNTAX FORMAT: OPEN ,[,
],[":][,]" EXAMPLES OF ACTUAL STATEMENTS: 10 OPEN 2,8,6,"0:STOCK FOLIO,S,W" 20 OPEN 1,1,2,"CHECKBOOK" 30 OPEN 3,4 When you actually apply the syntax conventions in a practical situa- tion, the sequence of parameters in your statements might not be exactly the same as the sequence shown in syntax examples. The examples are not meant to show every possible sequence. They are intended to present all required and optional parameters. INTRODUCTION xi ~ Programming examples in this book are shown with blanks separating words and operators for the sake of readability. Normally though, BASIC doesn't require blanks between words unless leaving them out would give you an ambiguous or incorrect syntax. Shown below are some examples and descriptions of the symbols used for various statement parameters in the following chapters. The list is not meant to show every possibility, but to give you a better understanding as to how syntax examples are presented. SYMBOL EXAMPLE DESCRIPTION 50 A logical file number 4 A hardware device number
15 A serial bus secondary device address number 0 A physical disk drive number "TEST.DATA" The name of a data or program file "ABCDEFG" Literal data supplied by the programmer X145 Any BASIC data variable name or constant AB$ Use of a string type variable required 12345 Use of a numeric type variable required 1000 An actual program line number 1.5E4 An integer or floating-point variable COMMODORE 64 APPLICATIONS GUIDE When you first thought about buying a computer you probably asked yourself, "Now that I can afford to buy a computer, what can I do with it once I get one?" The great thing about your COMMODORE 64 is that you can make it do what YOU want it to do! You can make it calculate and keep track of home and business budget needs. You can use it for word processing. You can make it play arcade-style action games. You can make it sing. You can even create your own animated cartoons, and more. The best part of owning a COMMODORE 64 is that even if it did only one of the things listed below it would be well worth the price you paid for it. But the 64 is a complete computer and it does do EVERYTHING listed and then some! xii INTRODUCTION ~ By the way, in addition to everything here you can pick up a lot of other creative and practical ideas by signing up with a local Commodore Users' Club, subscribing to the COMMODORE and POWER/PLAY magazines, and joining the COMMODORE INFORMATION NETWORK on CompuServe(TM) APPLICATION COMMENTS/REQUIREMENTS ACTION PACKED You can get real Bally Midway arcade games GAMES like Omega Race, Gorf and Wizard of War, as well as "play and learn" games like Math Teacher 1, Home Babysitter and Commodore Artist. ADVERTISING & Hook your COMMODORE 64 to a TV, put it in MERCHANDISING a store window with a flashing, animated, and musical message and you've got a great point of purchase store display. ANIMATION Commodore's Sprite Graphics allow you to create real cartoons with 8 different levels so that shapes can move in front of or behind each other. BABYSITTING The COMMODORE 64 HOME BABYSITTER cartridge can keep your youngest child occupied for hours and teach alphabet/ keyboard recognition at the same time. It also teaches special learning concepts and relationships. BASIC PROGRAMMING Your COMMODORE 64 USER'S GUIDE and the TEACH YOURSELF PROGRAMMING series of books and tapes offer an excellent starting point. BUSINESS The COMMODORE 64 offers the "Easy" series SPREADSHEET of business aids including the most powerful word processor and largest spreadsheet available for any personal computer. COMMUNICATION Enter the fascinating world of computer "net- working." If you hook a VICMODEM to your COMMODORE 64 you can communicate with other computer owners all around the world. INTRODUCTION xiii ~ Not only that, if you join the COMMODORE INFORMATION NETWORK on CompuServe(TM) you can get the latest news and updates on all Commodore products, financial information, shop at home services, you can even play games with the friends you make through the information systems you join. COMPOSING SONGS The COMMODORE 64 is equipped with the most sophisticated built-in music synthesizer available on any computer. It has three com- pletely programmable voices, nine full music octaves, and four controllable waveforms. Look for Commodore Music Cartridges and Commodore Music books to help you create or reproduce all kinds of music and sound effects. CP/M* Commodore offers a CP/M* add-on and access to software through an easy-to-load cartridge. DEXTERITY TRAINING Hand/Eye coordination and manual dexterity are aided by several Commodore games... including "Jupiter lander" and night driving simulation. EDUCATION While working with a computer is an education in itself, The COMMODORE Educational Resource Book contains general information on the educational uses of computers. We also have a variety of learning cartridges designed to teach everything from music to math and art to astronomy. FOREIGN LANGUAGE The COMMODORE 64 programmable character set lets you replace the standard character set with user defined foreign language characters. GRAPHICS AND ART In addition to the Sprite Graphics mentioned above, the COMMODORE 64 offers high-resolution, multi-color graphics plotting, programmable ----------- * CP/M is a Registered trademark of Digital Research, Inc. xiv INTRODUCTION ~ characters, and combinations of all the different graphics and character display modes. INSTRUMENT Your COMMODORE 64 has a serial port, RS-232 port CONTROL and a user port for use with a variety of special industrial applications. An IEEE/488 cartridge is also available as an optional extra. JOURNALS AND The COMMODORE 64 will soon offer an exceptional CREATIVE WRITING wordprocessing system that matches or exceeds the qualities and flexibilities of most "high- priced" wordprocessors available. Of course you can save the information on either a 1541 Disk Drive or a Datassette TM recorder and have it printed out using a VIC-PRINTER or PLOTTER. LIGHTPEN CONTROL Applications requiring the use of a lightpen can be performed by any lightpen that will fit the COMMODORE 64 game port connector. MACHINE CODE Your COMMODORE 64 PROGRAMMER'S REFERENCE GUIDE PROGRAMMING includes a machine language section, as well as a BASIC to machine code interface section. There's even a bibliography available for more in-depth study. PAYROLL & FORMS The COMMODORE 64 can be programmed to handle PRINTOUT a variety of entry-type business applications. Upper/lower case letters combined with C64 "business form" graphics make it easy for you to design forms which can then be printed on your printer. PRINTING The COMMODORE 64 interfaces with a variety of dot matrix and letter quality printers as well as plotters. RECIPES You can store your favorite recipes on your COMMODORE 64 and its disk or cassette storage unit, and end the need for messy recipe cards that often get lost when you need them most. INTRODUCTION xv ~ SIMULATIONS Computer simulations let you conduct dangerous or expensive experiments at minimum risk and cost. SPORTS DATA The Source (TM) and CompuServe (TM) both offer sports information which you can get using your COMMODORE 64 and a VICMODEM. STOCK QUOTES With a VICMODEM and a subscription to any of the appropriate network services, your COMMODORE 64 becomes your own private stock ticker. These are just a few of the many applications for you and your COMMODORE 64. As you can see, for work or play, at home, in school or the office, your COMMODORE 64 gives you a practical solution for just about any need. Commodore wants you to know that our support for users only STARTS with your purchase of a Commodore computer. That's why we've created two publications with Commodore information from around the world, and a "two-way" computer information network with valuable input for users in the U.S. and Canada from coast to coast. In addition, we wholeheartedly encourage and support the growth of Commodore Users' Clubs around the world. They are an excellent source of information for every Commodore computer owner from the beginner to the most advanced. The magazines and network, which are more fully described below, have the most up-to-date information about how to get involved with the Users' Club in your area. Finally, your local Commodore dealer is a useful source of Commodore support and information. POWER/PLAY The Home Computer Magazine When it comes to entertainment, learning at home and practical home applications, POWER/PLAY is THE prime source of information for Com- modore home users. Find out where your nearest user clubs are and what they're doing, learn about software, games, programming techniques, telecommunications, and new products. POWER/PLAY is your personal connection to other Commodore users, outside software and hardware developers, and to Commodore itself. Published quarterly. Only $10.00 for a year of home computing excitement. xvi INTRODUCTION ~ COMMODORE The Microcomputer Magazine Widely read by educators, businessmen and students, as well as home computerists, COMMODORE Magazine is our main vehicle for sharing exclusive information on the more technical use of Commodore systems. Regular departments cover business, science and education, programming tips, "excerpts from a technical notebook," and many other features of interest to anyone who uses or is thinking about purchasing Commodore equipment for business, scientific or educational applications. COMMODORE is the ideal complement to POWER/PLAY. Published bimonthly. Subscription price: $15.00 per year. AND FOR EVEN MORE INFORMATION... ...DIAL UP OUR PAPERLESS USER MAGAZINE COMMODORE INFORMATION NETWORK The magazine of the future is here. To supplement and enhance your subscription to POWER/PLAY and COMMODORE magazines, the COMMODORE INFORMATION NETWORK - our "paperless magazine" - is available now over the telephone using your Commodore computer and modem. Join our computer club, get help with a computing problem, "talk" to other Commodore friends, or get up-to-the-minute information on new products, software and educational resources. Soon you will even be able to save yourself the trouble of typing in the program listings you find in POWER/PLAY or COMMODORE by downloading direct from the Information Network (a new user service planned for early 1983). The best part is that most of the answers are there before you even ask the questions. (How's that for service?) To call our electronic magazine you need only a modem and a sub- scription to CompuServe TM, one of the nation's largest telecommunica- tions networks. (To make it easy for you Commodore includes a FREE year's subscription to CompuServe TM in each VICMODEM package.) Just dial your local number for the CompuServe (TM) data bank and connect your phone to the modem. When the CompuServe (TM) video text appears on your screen type G CBM on your computer keyboard. When the COMMODORE INFORMATION NETWORK'S table of contents, or "menu," appears on your screen choose from one of our sixteen departments, make yourself comfortable, and enjoy the paperless magazine other magazines are writing about. INTRODUCTION xvii ~ For more information, visit your Commodore dealer or contact Com- puserve(TM) customer service at 800-848-8990 (in Ohio, 614-457-8600). COMMODORE INFORMATION NETWORK +-----------------------------------+-----------------------------------+ | Main Menu Description | Commodore Dealers | | Direct Access Codes | Educational Resources | | Special Commands | User Groups | | User Questions | Descriptions | | Public Bulletin Board | Questions and Answers | | Magazines and Newsletters | Software Tips | | Products Announced | Technical Tips | | Commodore News Direct | Directory Descriptions | +-----------------------------------+-----------------------------------+ xviii INTRODUCTION ~ CHAPTER 1 BASIC PROGRAMMING RULES o Introduction o Screen Display Codes (BASIC Character Set) o Programming Numbers and variables o Expressions and Operators o Programming Techniques 1 ~ INTRODUCTION This chapter talks about how BASIC stores and manipulates data. The topics include: 1) A brief mention of the operating system components and functions as well as the character set used in the Commodore 64. 2) The formation of constants and variables. What types of variables there are. And how constants and variables are stored in memory. 3) The rules for arithmetic calculations, relationship tests, string handling, and logical operations. Also included are the rules for forming expressions, and the data conversions necessary when you're using BASIC with mixed data types. SCREEN DISPLAY CODES (BASIC CHARACTER SET) THE OPERATING SYSTEM (OS) The Operating System is contained in the Read Only Memory (ROM) chips and is a combination of three separate, but interrelated, program modules. 1) The BASIC Interpreter 2) The KERNAL 3) The Screen Editor 1) The BASIC Interpreter is responsible for analysing BASIC statement syntax and for performing the required calculations and/or data manipulation. The BASIC Interpreter has a vocabulary of 65 "keywords" which have special meanings. The upper and lower case alphabet and the digits 0-9 are used to make both keywords and variable names. Certain punctuation characters and special symbols also have meanings for the Interpreter. Table 1-1 lists the special characters and their uses. 2) The KERNAL handles most of the interrupt level processing in the system (for details on interrupt level processing, see Chapter 5). The KERNAL also does the actual input and output of data. 3) The Screen Editor controls the output to the video screen (tele- vision set) and the editing of BASIC program text. In addition, the Screen Editor intercepts keyboard input so that it can decide whether the characters put in should be acted upon immediately, or passed on to the BASIC Interpreter. 2 BASIC PROGRAMMING RULES ~ Table 1 - 1. CBM BASIC Character Set +-------------+---------------------------------------------------------+ | CHARACTER | NAME and DESCRIPTION | +-------------+---------------------------------------------------------+ | | BLANK - separates keywords and variable names | | ; | SEMI-COLON - used in variable lists to format output | | = | EQUAL SIGN - value assignment and relationship testing | | + | PLUS SIGN - arithmetic addition or string concatenation | | | (concatenation: linking together in a chain) | | - | MINUS SIGN - arithmetic subtraction, unary minus | | * | ASTERISK - arithmetic multiplication | | / | SLASH - arithmetic division | | ^ | UP ARROW - arithmetic exponentiation | | ( | LEFT PARENTHESIS - expression evaluation and functions | | ) | RIGHT PARENTHESIS - expression evaluation and functions | | % | PERCENT - declares variable name as an integer | | # | NUMBER - comes before logical file number in input/ | | | output statements | | $ | DOLLAR SIGN - declares variable name as a string | | , | COMMA - used in variable lists to format output; also | | | separates command parameters | | . | PERIOD - decimal point in floating point constants | | " | QUOTATION MARK - encloses string constants | | : | COLON - separates multiple BASIC statements in a line | | ? | QUESTION MARK - abbreviation for the keyword PRINT | | < | LESS THAN - used in relationship tests | | > | GREATER THAN - used in relationship tests | | {pi} | PI - the numeric constant 3.141592654 | +-------------+---------------------------------------------------------+ The Operating System gives you two modes of BASIC operation: 1) DIRECT Mode 2) PROGRAM Mode 1) When you're using the DIRECT mode, BASIC statements don't have line numbers in front of the statement. They are executed whenever the key is pressed. 2) The PROGRAM mode is the one you use for running programs. BASIC PROGRAMMING RULES 3 ~ When using the PROGRAM mode, all of your BASIC statements must have line numbers in front of them. You can have more than one BASIC statement in a line of your program, but the number of statements is limited by the fact that you can only put 80 characters on a logical screen line. This means that if you are going to go over the 80 character limit you have to put the entire BASIC statement that doesn't fit on a new line with a new line number. Always type NEW and hit before starting a new program. The Commodore 64 has two complete character sets that you can use either from the keyboard or in your programs. In SET 1, the upper case alphabet and the numbers 0-9 are available without pressing the key. If you hold down the key while typing, the graphics characters on the RIGHT side of the front of the keys are used. If you hold down the key while typing, the graphics characters on the LEFT side of the front of the key are used. Holding down the key while typing any character that doesn't have graphic symbols on the front of the key gives you the symbol on the top most part of the key. In SET 2, the lower case alphabet and the numbers 0-9 are available without pressing the key. The upper case alphabet is available when you hold down the key while typing. Again, the graphic symbols on the LEFT side of the front of the keys are displayed by press- ing the key, while the symbols on the top most part of any key without graphics characters are selected when you hold down the key while typing. To switch from one character set to the other press the and the keys together. PROGRAMMING NUMBERS AND VARIABLES INTEGER, FLOATING-POINT AND STRING CONSTANTS Constants are the data values that you put in your BASIC statements. BASIC uses these values to represent data during statement execution. CBM BASIC can recognize and manipulate three types of constants: 1) INTEGER NUMBERS 2) FLOATING-POINT NUMBERS 3) STRINGS 4 BASIC PROGRAMMING RULES ~ Integer constants are whole numbers (numbers without decimal points). Integer constants must be between -32768 and +32767. Integer constants do not have decimal points or commas between digits. If the plus (+) sign is left out, the constant is assumed to be a positive number. Zeros coming before a constant are ignored and shouldn't be used since they waste memory and slow down your program. However, they won't cause an error. Integers are stored in memory as two-byte binary numbers. Some examples of integer constants are: -12 8765 -32768 +44 0 -32767 +-----------------------------------------------------------------------+ | NOTE: Do NOT put commas inside any number. For example, always type | | 32,000 as 32000. If you put a comma in the middle of a number you | | will get the BASIC error message ?SYNTAX ERROR. | +-----------------------------------------------------------------------+ Floating-point constants are positive or negative numbers and can contain fractions. Fractional parts of a number may be shown using a decimal point. Once again remember that commas are NOT used between numbers. If the plus sign (+) is left off the front of a number, the Commodore 64 assumes that the number is positive. If you leave off the decimal point the computer will assume that it follows the last digit of the number. And as with integers, zeros that come before a constant are ignored. Floating-point constants can be used in two ways: 1) SIMPLE NUMBER 2) SCIENTIFIC NOTATION Floating-point constants will show you up to nine digits on your screen. These digits can represent values between -999999999. and +999999999. If you enter more than nine digits the number will be rounded based on the tenth digit. if the tenth digit is greater than or equal to 5 the number will be rounded upward. Less than 5 the number be rounded downward. This could be important to the final totals of some numbers you may want to work with. Floating-point numbers are stored (using five bytes of memory) and are manipulated in calculations with ten places of accuracy. However, BASIC PROGRAMMING RULES 5 ~ the numbers are rounded to nine digits when results are printed. Some examples of simple floating-point numbers are: 1.23 .7777777 -.998877 -333. +3.1459 .01 Numbers smaller than .01 or larger than 999999999. will be printed in scientific notation. In scientific notation a floating-point constant is made up of three parts: 1) THE MANTISSA 2) THE LETTER E 3) THE EXPONENT The mantissa is a simple floating-point number. The letter E is used to tell you that you're seeing the number in exponential form. In other words E represents * 10 (eg., 3E3 = 3*10^3 = 3000). And the exponent is what multiplication power of 10 the number is raised to. Both the mantissa and the exponent are signed (+ or -) numbers. The exponent's range is from -39 to +38 and it indicates the number of places that the actual decimal point in the mantissa would be moved to the left (-) or right (+) if the value of the constant were represented as a simple number. There is a limit to the size of floating-point numbers that BASIC can handle, even in scientific notation: the largest number is +1.70141183E+38 and calculations which would result in a larger number will display the BASIC error message ?OVERFLOW ERROR. The smallest floating-point number is +2.93873588E-39 and calculations which result in a smaller value give you zero as an answer and NO error message. Some examples of floating-point numbers in scientific notation (and their decimal values) are: 235.988E-3 (.235988) 2359E6 (2359000000.) -7.09E-12 (-.00000000000709) -3.14159E+5 (-314159.) String constants are groups of alphanumeric information like letters, numbers and symbols. When you enter a string from the keyboard, it can have any length up to the space available in an 80-character line 6 BASIC PROGRAMMING RULES ~ (that is, any character spaces NOT taken up by the line number and other required parts of the statement). A string constant can contain blanks, letters, numbers, punctuation and color or cursor control characters in any combination. You can even put commas between numbers. The only character which cannot be included in a string is the double quote mark ("). This is because the double quote mark is used to define the beginning and end of the string. A string can also have a null value-which means that it can contain no character data. You can leave the ending quote mark off of a string if it's the last item on a line or if it's followed by a colon (:). Some examples of string constants are: "" ( a null string) "HELLO" "$25,000.00" "NUMBER OF EMPLOYEES" +-----------------------------------------------------------------------+ | NOTE: Us CHR$(34) to include quotes (") in strings. | +-----------------------------------------------------------------------+ INTEGER, FLOATING-POINT AND STRING VARIABLES Variables are names that represent data values used in your BASIC statements. The value represented by a variable can be assigned by setting it equal to a constant, or it can be the result of calculations in the program. Variable data, like constants, can be integers, floating- point numbers, or strings. If you refer to a variable name in a program before a value has been assigned, the BASIC Interpreter will auto- matically create the variable with a value of zero if it's an integer or floating-point number. Or it will create a variable with a null value if you're using strings. Variable names can be any length but only the first two characters are considered significant in CBM BASIC. This means that all names used for variables must NOT have the same first two characters. Variable names may NOT be the same as BASIC keywords and they may NOT contain keywords in the middle of variable names. Keywords include all BASIC commands, state- ments, function names and logical operator names. If you accidentally use a keyword in the middle of a variable name, the BASIC error message ?SYNTAX ERROR will show up on your screen. The characters used to form variable names are the alphabet and the numbers 0-9. The first character of the name must be a letter. Data BASIC PROGRAMMING RULES 7 ~ type declaration characters (%) and ($) can be used as the last char- acter of the name. The percent sign declares the variable to be an integer and the dollar sign ($) declares a string variable. If no type declaration character is used the Interpreter will assume that the vari- able is a floating-point. Some examples of variable names, value as- signments and data types are: A$="GROSS SALES" (string variable) MTH$="JAN"+A$ (string variable) K%=5 (integer variable) CNT%=CNT%+1 (integer variable) FP=12.5 (floating-point variable) SUM=FP*CNT% (floating-point variable) INTEGER, FLOATING-POINT AND STRING ARRAYS An array is a table (or list) of associated data items referred to by a single variable name. In other words, an array is a sequence of related variables. A table of numbers can be seen as an array, for example. The individual numbers within the table become "elements" of the array. Arrays are a useful shorthand way of describing a large number of related variables. Take a table of numbers for instance. Let's say that the table has 10 rows of numbers with 20 numbers in each row. That makes total of 200 numbers in the table. Without a single array name to call on you would have to assign a unique name to each value in the table. But because you can use arrays you only need one name for the array and all the elements in the array are identified by their individual locations within the array. Array names can be integers, floating-points or string data types and all elements in the array have the same data type as the array name. Arrays can have a single dimension (as in a simple list) or they can have multiple dimensions (imagine a grid marked in rows and columns or a Rubik's Cube(R)). Each element of an array is uniquely identified and re- ferred to by a subscript (or index variable) following the array name, enclosed within parentheses ( ). The maximum number of dimensions an array can have in theory is 255 and the number of elements in each dimension is limited to 32767. But for practical purposes array sizes are limited by the memory space available to hold their data and/or the 80 character logical screen line. If an array has only one dimension and its subscript value will never 8 BASIC PROGRAMMING RULES ~ exceed 1 0 (1 I items: 0 thru 1 0) then the array will be created by the Interpreter and filled with zeros (or nulls if string type) the first time any element of the array is referred to, otherwise the BASIC DIM statement must be used to define the shape and size of the array. The amount of memory required to store an array can be determined as follows: 5 bytes for the array name + 2 bytes for each dimension of the array + 2 bytes per element for integers OR + 5 bytes per element for floating-point OR + 3 bytes per element for strings AND + 1 byte per character in each string element Subscripts can be integer constants, variables, or an arithmetic ex- pression which gives an integer result. Separate subscripts, with com- mas between them, are required for each dimension of an array. Sub- scripts can have values from zero up to the number of elements in the respective dimensions of the array. Values outside that range will cause the BASIC error message ?BAD SUBSCRIPT. Some examples of array names, value assignments and data types are: A$(0)="GROSS SALES" (string array) MTH$(K%)="JAN" (string array) G2%(X)=5 (integer array) CNT%(G2%(X))=CNT%(1)-2 (integer array) FP(12*K%)=24.8 (floating-point array) SUM(CNT%(1))=FP^K% (floating-point array) A(5)=0 (sets the 5th element in the 1 dimensional array called "A" equal to 0) B(5,6)=0 (sets the element in row position 5 and column position 6 in the 2 dimensional array called "B" equal to 0) C(1,2,3)=0 (sets the element in row position 1, column position 2, and depth position 3 in the 3 dimensional array called "C" equal to 0) EXPRESSIONS AND OPERATORS Expressions are formed using constants, variables and/or arrays. An expression can be a single constant, simple variable, or an array vari- BASIC PROGRAMMING RULES 9 ~ able of any type. It can also be a combination of constants and variables with arithmetic, relational or logical operators designed to produce a ingle value. How operators work is explained below. Expressions can be separated into two classes: 1) ARITHMETIC 2) STRING Expressions are normally thought of as having two or more data items called operands. Each operand is separated by a single operator to produce the desired result. This is usually done by assigning the value of the expression to a variable name. All of the examples of constants and variables that you've seen so for, were also examples of expressions. An operator is a special symbol the BASIC Interpreter in your Commodore 64 recognizes as representing an operation to be performed on the variables or constant data. One or more operators, combined with one or more variables and/or constants form an expression. Arithmetic, relational and logical operators are recognized by Commodore 64 BASIC. ARITHMETIC EXPRESSIONS Arithmetic expressions, when solved, will give an integer or floating- point value. The arithmetic operators (+, -, *, /, ^) are used to perform addition, subtraction, multiplication, division and exponentiation opera- tions respectively. ARITHMETIC OPERATIONS An arithmetic operator defines an arithmetic operation which is per- formed on the two operands on either side of the operator. Arithmetic operations are performed using floating-point numbers. Integers are converted to floating-point numbers before an arithmetic operation is performed. The result is converted back to an integer if it is assigned to an integer variable name. ADDITION (+): The plus sign (+) specifies that the operand on the right is added to the operand on the left. 10 BASIC PROGRAMMING RULES ~ EXAMPLES: 2+2 A+B+C X%+1 BR+10E-2 SUBTRACTION (-): The minus sign (-) specifies that the operand on the right is subtracted from the operand on the left. EXAMPLES: 4-1 100-64 A-B 55-142 The minus can also be used as a unary minus. That means that it is the minus sign in front of a negative number. This is equal to subtracting the number from zero (0). EXAMPLES: -5 -9E4 -B 4-(-2) same as 4+2 MULTIPLICATION (*): An asterisk (*) specifies that the operand on the left is multiplied by the operand on the right. EXAMPLES: 100*2 50*0 A*X1 R%*14 DIVISION (/): The slash (/) specifies that the operand on the left is divided by the operand on the right. EXAMPLES: 10/2 6400/4 A/B 4E2/XR BASIC PROGRAMMING RULES 11 ~ EXPONENTIATION The up arrow (^) specifies that the operand on the left is raised to the power specified by the operand on the right (the exponent). If the operand on the right is a 2, the number on the left is squared; if the exponent is a 3, the number on the left is cubed, etc. The exponent can be any number so long as the result of the operation gives a valid floating-point number. EXAMPLES: 2^2 Equivalent to: 2*2 3^3 Equivalent to: 3*3*3 4^4 Equivalent to: 4*4*4*4 AB^CD 3^-2 Equivalent to: 1/3*1/3 RELATIONAL OPERATORS The relational operators (<, =, >, <=, >=, <>) are primarily used to compare the values of two operands, but they also produce an arith- metic result. The relational operators and the logical operators (AND, OR, and NOT), when used in comparisons, actually produce an arithmetic true/false evaluation of an expression. If the relationship stated in the expression is true the result is assigned an integer value of - 1 and if it's false a value of 0 is assigned. These are the relational operators: < LESS THAN = EQUAL TO > GREATER THAN <= LESS THAN OR EQUAL TO >= GREATER THAN OR EQUAL TO <> NOT EQUAL TO EXAMPLES: 1 =5-4 result true (-1) 14>66 result false (0) 15>=15 result true (-1) Relational operators can be used to compare strings. For comparison purposes, the letters of the alphabet have the order A CC$ Numeric data items can only be compared (or assigned) to other numeric items. The same is true when comparing strings, otherwise the BASIC error message ?TYPE MISMATCH will occur. Numeric operands are compared by first converting the values of either or both operands from integer to floating-point form, as necessary. Then the relationship of the floating- point values is evaluated to give a true/false result. At the end of all comparisons, you get an integer no matter what data type the operand is (even if both are strings). Because of this, a comparison of two operands can be used as an operand in performing calculations. The result will be - 1 or 0 and can be used as anything but a divisor, since division by zero is illegal. LOGICAL OPERATORS The logical operators (AND, OR, NOT) can be used to modify the meanings of the relational operators or to produce an arithmetic result. Logical operators can produce results other than -1 and 0, though any nonzero result is considered true when testing for a true/false condition. The logical operators (sometimes called Boolean operators) can also be used to perform logic operations on individual binary digits (bits) in two operands. But when you're using the NOT operator, the operation is performed only on the single operand to the right. The operands must be in the integer range of values (-32768 to +32767) (floating-point numbers are converted to integers) and logical operations give an integer result. Logical operations are performed bit-by-corresponding-bit on the two operands. The logical AND produces a bit result of 1 only if both operand bits are 1. The logical OR produces a bit result of I if either operand bit is 1. The logical NOT is the opposite value of each bit as a single operand. In other words, it's really saying, "if it's NOT 1 then it is 0. If it's NOT 0 then it is 1." The exclusive OR (XOR) doesn't have a logical operator but it is per- formed as part of the WAIT statement. Exclusive OR means that if the bits of two operands are equal then the result is 0 otherwise the result is 1. Logical operations are defined by groups of statements which, taken together, constitute a Boolean "truth table" as shown in Table 1-2. BASIC PROGRAMMING RULES 13 ~ Table 1-2. Boolean Truth Table +-----------------------------------------------------------------------+ | The AND operation results in a 1 only if both bits are 1: | | | | 1 AND 1 = 1 | | 0 AND 1 = 0 | | 1 AND 0 = 0 | | 0 AND 0 = 0 | | | | The OR operation results in a 1 if either bit is 1: | | | | 1 OR 1 = 1 | | 0 OR 1 = 1 | | 0 OR 0 = 1 | | 0 OR 0 = 0 | | | | The NOT operation logically complements each bit: | | | | NOT 1 = 0 | | NOT 0 = 1 | | | | The exclusive OR (XOR) is part of the WAIT statement! | | | | 1 XOR 1 = 0 | | 1 XOR 0 = 1 | | 0 XOR 1 = 1 | | 0 XOR 0 = 0 | +-----------------------------------------------------------------------+ The logical operators AND, OR and NOT specify a Boolean arithmetic operation to be performed on the two operand expressions on either side of the operator. In the case of NOT, ONLY the operand on the RIGHT is considered. Logical operations (or Boolean arithmetic) aren't performed until all arithmetic and relational operations in an expression have been completed. EXAMPLES: IF A=100 AND B=100 THEN 10 (if both A and B have a value of 100 then the result is true) A=96 AND 32: PRINT A (A = 32) 14 BASIC PROGRAMMING RULES ~ IF A=100 OR B=100 THEN 20 (if A or B is 100 then the result is true) A=64 OR 32: PRINT A (A = 96) IF NOT X=Y the result is true) X= NOT 96 (result is -97 (two's complement)) HIERARCHY OF OPERATIONS All expressions perform the different types of operations according to a fixed hierarchy. In other words, certain operations are performed be- fore other operations. The normal order of operations can be modified by enclosing two or more operands within parentheses ( ), creating a "subexpression." The parts of an expression enclosed in parentheses will be reduced to a single value before working on parts outside the par- entheses. When you use parentheses in expressions, they must be paired so that you always have an equal number of left and right parentheses. Otherwise, the BASIC error message ?SYNTAX ERROR will appear. Expressions which have operands inside parentheses may themselves be enclosed in parentheses, forming complex expressions of multiple levels. This is called nesting. Parentheses can be nested in expressions to a maximum depth of ten levels-ten matching sets of parentheses. The inner-most expression has its operations performed first. Some examples of expressions are: A+B C^(D+E)/2 ((X-C^(D+E)/2)*10)+1 GG$>HH$ JJ$+"MORE" K%=1 AND M<>X K%=2 OR (A=B AND M = < | Relational Operations | A <= B | | | | | | NOT | Logical NOT | NOT K% | | | (Integer Two's Complement) | | | | | | | AND | Logical AND | JK AND 128 | | | | | | OR | Logical OR | PQ OR 15 | +---------------+---------------------------------+---------------------+ STRING OPERATIONS Strings are compared using the same relational operators (=, <>, <=, >=, <, >) that are used for comparing numbers. String compari- sons are mode by taking one character at a time (left-to-right) from each string and evaluating each character code position from the PET/ CBM character set. If the character codes are the same, the characters are equal. If the character codes differ, the character with the lower code number is lower in the character set. The comparison stops when 16 BASIC PROGRAMMING RULES ~ the end of either string is reached. All other things being equal, the shorter string is considered less than the longer string. Leading or trailing blanks ARE significant. Regardless of the data types, at the end of all comparisons you get an integer result. This is true even if both operands are strings. Because of this a comparison of two string operands can be used as an operand in performing calculations. The result will be - 1 or 0 (true or false) and can be used as anything but a divisor since division by zero is illegal. STRING EXPRESSIONS Expressions are treated as if an implied "<>0" follows them. This means that if an expression is true then the next BASIC statements on. the same program line are executed. If the expression is false the rest of the line is ignored and the next line in the program is executed. Just as with numbers, you can also perform operations on string vari- ables. The only string arithmetic operator recognized by CBM BASIC is the plus sign (+) which is used to perform concatenation of strings. When strings are concatenated, the string on the right of the plus sign is appended to the string on the left, forming a third string as a result. The result can be printed immediately, used in a comparison, or assigned to a variable name. If a string data item is compared with (or set equal to) a numeric item, or vice-versa, the BASIC error message ?TYPE MISMATCH will occur. Some examples of string expressions and concatenation are: 10 A$="FILE": B$="NAME" 20 NAM$=A$+B$ (gives the string: FILENAME) 30 RES$="NEW "+A$+B$ (gives the string: NEW FILENAME) ^ | +-----------------+ +-------+ Note space here.| +-----------------+ BASIC PROGRAMMING RULES 17 ~ PROGRAMMING TECHNIQUES DATA CONVERSIONS When necessary, the CBM BASIC Interpreter will convert a numeric data item from an integer to floating-point. or vice-versa, according to the following rules: o All arithmetic and relational operations are performed in floating point format. Integers are converted to floating-point form for evaluation of the expression, and the result is converted back to integer. logical operations convert their operands to integers an return an integer result. o If a numeric variable name of one type is set equal to a numeric data item of a different type, the number will be converted and stored as the data type declared in the variable name. o When a floating-point value is converted to an integer, the frac- tional portion is truncated (eliminated) and the integer result is less than or equal to the floating-point value. If the result is outside the range of +32767 thru -32768, the BASIC error message ?ILLEGAL QUANTITY will occur. USING THE INPUT STATEMENT Now that you know what variables are, let's take that information an put it together with the INPUT statement for some practical program- ming applications. In our first example, you can think of a variable as a "storage com- partment" where the Commodore 64 stores the user's response to your prompt question. To write a program which asks the user to type in a name, you might assign the variable N$ to the name typed in. Now every time you PRINT N$ in your program, the Commodore 64 will automatically PRINT the name that the user typed in. Type the word NEW on your Commodore 64. Hit the key and try this example: 10 PRINT"YOUR NAME": INPUT N$ 20 PRINT"HELLO",N$ 18 BASIC PROGRAMMING RULES ~ In this example you used N to remind yourself that this variable stands for "NAME". The dollar sign ($) is used to tell the computer that you're using a string variable. It is important to differentiate between the two types of variables: 1) NUMERIC 2) STRING You probably remember from the earlier sections that numeric vari- ables are used to store number values such as 1, 100, 4000, etc. A numeric variable can be a single letter (A), any two letters (AB), a letter and a number (AI), or two letters and a number (AB1). You can save memory space by using shorter variables. Another helpful hint is to use letters and numbers for different categories in the same program (AI, A2, A3). Also, if you want whole numbers for an answer instead of numbers with decimal points, all you have to do is put a percent sign (%) at the end of your variable name (AB%, AI%, etc.) Now let's look at a few examples that use different types of variables and expressions with the INPUT statement. 10 PRINT"ENTER A NUMBER": INPUT A 20 PRINT A 10 PRINT"ENTER A WORD": INPUT A$ 20 PRINT A$ 10 PRINT"ENTER A NUMBER": INPUT A 20 PRINT A "TIMES 5 EQUALS" A*5 +-----------------------------------------------------------------------+ | NOTE: Example 3 shows that MESSAGES or PROMPTS are inside the | | quotation marks (" ") while the variables are outside. Notice, too, | | that in line 20 the variable A was printed first, then the message | | "TIMES 5 EQUALS", and then the calculation, multiply variable A by 5 | | (A*5). | +-----------------------------------------------------------------------+ Calculations are important in most programs. You have a choice of using "actual numbers" or variables when doing calculations, but if you're working with numbers supplied by a user you must use numeric variables. Begin by asking the user to type in two numbers like this: 10 PRINT"TYPE 2 NUMBERS": INPUT A: INPUT B BASIC PROGRAMMING RULES 19 ~ INCOME/EXPENSE BUDGET EXAMPLE start tok64 page20.prg 5 print"{clear}" 10 print"monthly income":input in 20 print 30 print"expense category 1":input e1$ 40 print"expense amount":input e1 50 print 60 print"expense category 2":input e2$ 70 print"expense amount":input e2 80 print 90 print"expense category 3":input e3$ 100 print"expense amount":input e3 110 print"{clear}" 120 e=e1+e2+e3 130 ep=e/in 140 print"monthly income: $"in 150 print"total expenses: $"e 160 print"balance equals: $"in-e 170 print 180 print e1$"="(e1/e)*100"% of total expenses" 190 print e2$"="(e2/e)*100"% of total expenses" 200 print e3$"="(e3/e)*100"% of total expenses" 210 print 220 print"your expenses="ep*100"% of your total income" 230 forx=1to5000:next:print 240 print"repeat? (y or n)":input y$:if y$="y"then 5 250 print"{clear}":end stop tok64 +-----------------------------------------------------------------------+ | NOTE:IN can NOT = 0, and E1, E2, E3 can NOT all be 0 at the same time.| +-----------------------------------------------------------------------+ 20 BASIC PROGRAMMING RULES ~ LINE-BY-LINE EXPLANATION OF INCOME/EXPENSE BUDGET EXAMPLE +-----------+-----------------------------------------------------------+ | Line(s) | Description | +-----------+-----------------------------------------------------------+ | 5 | Clears the screen. | | 10 | PRINT/INPUT statement. | | 20 | Inserts blank line. | | 30 | Expense Category 1 = E1$. | | 40 | Expense Amount = E1. | | 50 | Inserts blank line. | | 60 | Expense Category 2 = E2. | | 70 | Expense Amount 2 = E2. | | 80 | Inserts blank line. | | 90 | Expense Category 3 = E3. | | 100 | Expense Amount 3 = E3. | | 110 | Clears the screen. | | 120 | Add Expense Amounts = E. | | 130 | Calculate Expense/income%. | | 140 | Display Income. | | 150 | Display Total Expenses. | | 160 | Display Incomes - Expenses. | | 170 | Inserts blank line. | | 180-200 | lines 180-200 calculate % each expense | | | amount is of total expenses. | | 210 | Inserts blank line. | | 220 | Display E/IN %. | | 230 | Time delay loop. | +-----------+-----------------------------------------------------------+ Now multiply those two numbers together to create a new variable C as shown in line 20 below: 20 C=A*B To PRINT the result as a message type 30 PRINT A "TIMES" B "EQUALS" C Enter these 3 lines and RUN the program. Notice that the messages are inside the quotes while the variables are not. BASIC PROGRAMMING RULES 21 ~ Now let's say that you wanted a dollar sign ($) in front of the number represented by variable C. The $ must be PRINTed inside quotes and in front of variable C. To add the $ to your program hit the and keys. Now type in line 40 as follows: 40 PRINT"$" C Now hit , type RUN and hit again. The dollar sign goes in quotes because the variable C only represents a number and can't contain a $. If the number represented by C was 100 then the Commodore 64 screen would display $ 100. But, if you tried to PRINT $C without using the quotes, you would get a ?SYNTAX ERROR message. One last tip about $$$: You can create a variable that represents a dollar sign which you can then substitute for the $ when you want to use it with numeric variables. For example: 10 Z$="$" Now whenever you need a dollar sign you can use the string variable Z$. Try this: 10 Z$="$": INPUT A 20 PRINT Z$A line 10 defines the $ as a string variable called Z$, and then INPUTs a number called A. line 20 PRINTs Z$ ($) next to A (number). You'll probably find that it's easier to assign certain characters, like dollar signs, to a string variable than to type "$" every time you want to calculate dollars or other items which require "" like %. USING THE GET STATEMENT Most simple programs use the INPUT statement to get data from the person operating the computer. When you're dealing with more complex needs, like protection from typing errors, the GET statement gives you more flexibility and your program more "intelligence." This section shows you how to use the GET statement to add some special screen editing features to your programs. 22 BASIC PROGRAMMING RULES ~ The Commodore 64 has a keyboard buffer that holds up to 10 characters. This means that if the computer is busy doing some operation and it's not reading the keyboard, you can still type in up to 10 characters, which will be used as soon as the Commodore 64 finishes what it was doing. To demonstrate this, type in this program on your Commodore 64: NEW 10 TI$="000000" 20 IF TI$ < "000015" THEN 20 Now type RUN, hit and while the program is RUNning type in the word HELLO. Notice that nothing happened for about IS seconds when the program started. Only then did the message HELLO appear on the screen. Imagine standing in line for a movie. The first person in the line is the first to get a ticket and leave the line. The last person in line is last for a ticket. The GET statement acts like a ticket taker. First it looks to see if there are any characters "in line." In other words have any keys been typed. If the answer is yes then that character gets placed in the appropriate variable. If no key was pressed then an empty value is assigned to a variable, At this point it's important to note that if you try to put more than 10 characters into the buffer at one time, all those over the 10th character will be lost. Since the GET statement will keep going even when no character is typed, it is often necessary to put the GET statement into a loop so that it will have to wait until someone hits a key or until a character is received through your program. Below is the recommended form for the GET statement. Type NEW to erase your previous program. 10 GET A$: IF A$ ="" THEN 10 Notice that there is NO SPACE between the quote marks("") on this line. This indicates an empty value and sends the program back to the GET statement in a continuous loop until someone hits a key on the computer. Once a key is hit the program will continue with the line following line 10. Add this line to your program: 100 PRINT A$;: GOTO 10 BASIC PROGRAMMING RULES 23 ~ Now RUN the program. Notice that no cursor appears on the screen, but any character you type will be printed in the screen. This 2-line program can be turned into part of a screen editor program as shown below. There are many things you can do with a screen editor. You can have a flashing cursor. You can keep certain keys like from accidentally erasing the whole screen. You might even want to be able to use your function keys to represent whole words or phrases. And speaking of function keys, the following program lines give each function key a special purpose. Remember this is only the beginning of a program that you can customize for your needs. 20 IF A$ = CHR$(133) THEN POKE 53280,8: GOTO 10 30 IF A$ = CHR$(134) THEN POKE 53281,4: GOTO 10 40 IF A$ = CHR$(135) THEN A$="DEAR SIR:"+CHR$(13) 50 IF A$ = CHR$(136) THEN A$="SINCERELY,"+CHR$(13) The CHR$ numbers in parentheses come from the CHR$ code chart in Appendix C. The chart lists a different number for each character. The four function keys are set up to perform the tasks represented by the instructions that follow the word THEN in each line. By changing the CHR$ number inside each set of parentheses you can designate different keys. Different instructions would be performed if you changed the information after the THEN statement. HOW TO CRUNCH BASIC PROGRAMS You can pack more instructions - and power - into your BASIC programs by making each program as short as possible. This process of shortening programs is called "crunching." Crunching programs lets you squeeze the maximum possible number of instructions into your program. It also helps you reduce the size of programs which might not otherwise run in a given size; and if you're writing a program which requires the input of data such as inventory items, numbers or text, a short program will leave more memory space free to hold data. ABBREVIATING KEYWORDS A list of keyword abbreviations is given in Appendix A. This is helpful when you program because you can actually crowd more information on each line using abbreviations. The most frequently used abbreviation is 24 BASIC PROGRAMMING RULES ~ the question mark (?) which is the BASIC abbreviation for the PRINT command. However, if you LIST a program that has abbreviations, the Commodore 64 will automatically print out the listing with the full- length keywords. If any program line exceeds 80 characters (2 lines on the screen) with the keywords unabbreviated, and you want to change it, you will have to re-enter that line with the abbreviations before saving the program. SAVEing a program incorporates the keywords without inflating any lines because BASIC keywords are tokenized by the Commodore 64. Usually, abbreviations are added after a program is written and it isn't going to be LISTed any more before SAVEing. SHORTENING PROGRAM LINE NUMBERS Most programmers start their programs at line 100 and number each fine at intervals of 10 (i.e., 100, 110, 120). This allows extra lines of instruction to be added (111, 112, etc.) as the program is developed. One means of crunching the program after it is completed is to change the fine numbers to the lowest numbers possible (i.e., 1, 2, 3) because longer line numbers take more memory than shorter numbers when referenced by GOTO and GOSUB statements. For instance, the number 100 uses 3 bytes of memory (one for each number) while the number I uses only 1 byte. PUTTING MULTIPLE INSTRUCTIONS ON EACH LINE You can put more than one instruction on each numbered line in your program by separating them by a colon. The only limitation is that all the instructions on each line, including colons, should not exceed the standard 80-character line length. Here is an example of two programs, before and after crunching: BEFORE CRUNCHING: AFTER CRUNCHING: 10 PRINT"HELLO..."; 10 PRINT "HELLO...";:FORT=1TO500:NEXT: 20 FOR T=1 TO 500: NEXT PRINT"HELLO, AGAIN...":GOTO10 30 PRINT"HELLO, AGAIN..." 40 GOTO 10 REMOVING REM STATEMENTS REM statements are helpful in reminding yourself-or showing other programmers - what a particular section of a program is doing. However, when the program is completed and ready to use, you probably BASIC PROGRAMMING RULES 25 ~ won't need those REM statements anymore and you can save quite a bit of space by removing the REM statements. If you plan to revise or study the program structure in the future, it's a good idea to keep a copy on file with the REM statements intact. USING VARIABLES If a number, word or sentence is used repeatedly in your program it's usually best to define those long words or numbers with a one or two letter variable. Numbers can be defined as single letters. Words and sentences can be defined as string variables using a letter and dollar sign. Here's one example: BEFORE CRUNCHING: AFTER CRUNCHING: 10 POKE 54296,15 10 V=54296:F=54273 20 POKE 54276,33 20 POKEV,15:POKE54276,33 30 POKE 54273,10 30 POKEF,10:POKEF,40:POKEF,70 40 POKE 54273,40 40 POKEV,0 50 POKE 54273,70 60 POKE 54296,0 USING READ AND DATA STATEMENTS Large amounts of data can be typed in as one piece of data at a time, over and over again ... or you can print the instructional part of the program ONCE and print all the data to be handled in a long running list called the DATA statement. This is especially good for crowding large lists of numbers into a program. USING ARRAYS AND MATRICES Arrays and matrices are similar to DATA statements in that long amounts of data can be handled as a list, with the data handling portion of the program drawing from that list, in sequence. Arrays differ in that the list can be multi-dimensional ELIMINATING SPACES One of the easiest ways to reduce the size of your program is to eliminate all the spaces. Although we often include spaces in sample 26 BASIC PROGRAMMING RULES ~ programs to provide clarity, you actually don't need any spaces in your program and will save space if you eliminate them. USING GOSUB ROUTINES If you use a particular line or instruction over and over, it might be wise to GOSUB to the line from several places in your program, rather than write the whole line or instruction every time you use it. USING TAB AND SPC Instead of PRINTing several cursor commands to position a character on the screen, it is often more economical to use the TAB and SPC in- structions to position words or characters on the screen. BASIC PROGRAMMING RULES 27 ~~ CHAPTER 2 BASIC LANGUAGE VOCABULARY o Introduction o BASIC Keywords, Abbreviations, and Function Types o Description of BASIC Keywords (Alphabetical) o The Commodore 64 Keyboard and Features o Screen Editor ~ INTRODUCTION This chapter explains CBM BASIC Language keywords. First we give you an easy to read list of keywords, their abbreviations and what each letter looks like on the screen. Then we explain how the syntax and operation of each keyword works in detail, and examples are shown to give you an idea as to how to use them in your programs. As a convenience, Commodore 64 BASIC allows you to abbreviate most keywords. Abbreviations are entered by typing enough letters of the keyword to distinguish it from all other keywords, with the last letter or graphics entered holding down the key. Abbreviations do NOT save any memory when they're used in programs, because all keywords are reduced to single-character "tokens" by the BASIC Interpreter. When a program containing abbreviations is listed, all keywords appear in their fully spelled form. You can use abbreviations to put more statements onto a program line even if they won't fit onto the 80-character logical screen line. The Screen Editor works on an 80- character line. This means that if you use abbreviations on any line that goes over 80 characters, you will NOT be able to edit that line when LISTed. Instead, what you'll have to do is (1) retype the entire line including all abbreviations, or (2) break the single line of code into two lines, each with its own line number, etc. A complete list of keywords, abbreviations, and their appearance on the screen is presented in Table 2-1. They are followed by an alphabetical description of all the statements, commands, and functions available on your Commodore 64. This chapter also explains the BASIC functions built into the BASIC Language Interpreter. Built-in functions can be used in direct mode statements or in any program, without having to define the function further. This is NOT the case with user-defined functions. The results of built-in BASIC functions can be used as immediate output or they can be assigned to a variable name of an appropriate type. There are two types of BASIC functions: 1) NUMERIC 2) STRING Arguments of built-in functions are always enclosed in parentheses (). The parentheses always come directly after the function keyword and NO SPACES between the last letter of the keyword and the left parenthesis (. 30 BASIC LANGUAGE VOCABULARY ~ The type of argument needed is generally decided by the data type in the result. Functions which return a string value as their result are identified by having a dollar sign ($) as the last character of the keyword. In some cases string functions contain one or more numeric argument. Numeric functions will convert between integer and floating- point format as needed. In the descriptions that follow, the data type of the value returned is shown with each function name. The types of argu- ments are also given with the statement format. Table 2-1. COMMODORE 64 BASIC KEYWORDS +-----------+----------------------+----------------+-------------------+ | COMMAND | ABBREVIATION | SCREEN | FUNCTION TYPE | +-----------+----------------------+----------------+-------------------+ | | | | | | ABS | A | | NUMERIC | | | | | | | AND | A | | | | | | | | | ASC | A | | NUMERIC | | | | | | | ATN | A | | NUMERIC | | | | | | | CHR$ | C | | STRING | | | | | | | CLOSE | CL | | | | | | | | | CLR | C | | | | | | | | | CMD | C | | | | | | | | | CONT | C | | | | | | | | | COS | none | COS | NUMERIC | | | | | | | DATA | D | | | | | | | | | DEF | D | | | | | | | | | DIM | D | | | BASIC LANGUAGE VOCABULARY 31 ~ +-----------+----------------------+----------------+-------------------+ | COMMAND | ABBREVIATION | SCREEN | FUNCTION TYPE | +-----------+----------------------+----------------+-------------------+ | | | | | | END | E | | | | | | | | | EXP | E | | NUMERIC | | | | | | | FN | none | FN | | | | | | | | FOR | F | | | | | | | | | FRE | F | | NUMERIC | | | | | | | GET# | none | GET# | | | | | | | | GOSUB | GO | | | | | | | | | GOTO | G | | | | | | | | | IF | none | IF | | | | | | | | INPUT | none | INPUT | | | | | | | | INPUT# | I | | | | | | | | | INT | none | INT | NUMERIC | | | | | | | LEFT$ | LE | | STRING | | | | | | | LEN | none | LEN | NUMERIC | | | | | | | LET | L | | | | | | | | | LIST | L | | | | | | | | | LOAD | L | | | | | | | | | LOG | none | LOG | NUMERIC | 32 BASIC LANGUAGE VOCABULARY ~ +-----------+----------------------+----------------+-------------------+ | COMMAND | ABBREVIATION | SCREEN | FUNCTION TYPE | +-----------+----------------------+----------------+-------------------+ | | | | | | MID$ | M | | STRING | | | | | | | NEW | none | NEW | | | | | | | | NEXT | N | | | | | | | | | NOT | N | | | | | | | | | ON | none | ON | | | | | | | | OPEN | O | | | | | | | | | OR | none | OR | | | | | | | | PEEK | P | | NUMERIC | | | | | | | POKE | P | | | | | | | | | POS | none | POS | NUMERIC | | | | | | | PRINT | ? | ? | | | | | | | | PRINT# | P | | | | | | | | | READ | R | | | | | | | | | REM | none | REM | | | | | | | | RESTORE| RE | | | | | | | | | RETURN | RE | | | | | | | | | RIGHT$ | R | | STRING | | | | | | | RND | R | | NUMERIC | | | | | | | RUN | R | | | BASIC LANGUAGE VOCABULARY 33 ~ | | | | | | SAVE | S | | | | | | | | | SGN | S | | NUMERIC | | | | | | | SIN | S | | NUMERIC | | | | | | | SPC( | S | | SPECIAL | | | | | | | SQR | S | | NUMERIC | | | | | | | STATUS | ST | ST | NUMERIC | | | | | | | STEP | ST | | | | | | | | | STOP | S | | | | | | | | | STR$ | ST | | STRING | | | | | | | SYS | S | | | | | | | | | TAB( | T | | SPECIAL | | | | | | | TAN | none | TAN | NUMERIC | | | | | | | THEN | T | | | | | | | | | TIME | TI | TI | NUMERIC | | | | | | | TIME$ | TI$ | TI$ | STRING | | | | | | | TO | none | TO | | | | | | | | USR | U | | NUMERIC | | | | | | | VAL | V | | NUMERIC | | | | | | | VERIFY | V | | | | | | | | | WAIT | W | | | +-----------+----------------------+----------------+-------------------+ 34 BASIC LANGUAGE VOCABULARY ~ DESCRIPTION OF BASIC KEYWORDS ABS TYPE: Function-Numeric FORMAT: ABS() Action: Returns the absolute value of the number, which is its value without any signs. The absolute value of a negative number is that number multiplied by -1. EXAMPLES of ABS Function: 10 X = ABS (Y) 10 PRINT ABS (X*J) 10 IF X = ABS (X) THEN PRINT"POSITIVE" AND TYPE: Operator FORMAT: AND Action: AND is used in Boolean operations to test bits. it is also used in operations to check the truth of both operands. In Boolean algebra, the result of an AND operation is 1 only if both numbers being ANDed are 1. The result is 0 if either or both is 0 (false). EXAMPLES of 1-Bit AND operation: 0 1 0 1 AND 0 AND 0 AND 1 AND 1 ------ ----- ----- ----- 0 0 0 1 The Commodore 64 performs the AND operation on numbers in the range from -32768 to +32767. Any fractional values are not used, and numbers beyond the range will cause an ?ILLEGAL QUANTITY error message. When BASIC LANGUAGE VOCABULARY 35 ~ converted to binary format, the range allowed yields 16 bits for each number. Corresponding bits are ANDed together, forming a 16-bit result in the same range. EXAMPLES of 16-Bit AND Operation: 17 AND 194 -------- 0000000000010001 AND 0000000011000010 -------------------------- (BINARY) 0000000000000000 -------------------------- (DECIMAL) 0 32007 AND 28761 ---------- 0111110100000111 AND 0111000001011001 -------------------------- (BINARY) 0111000000000001 -------------------------- (DECIMAL) 28673 -241 AND 15359 ---------- 1111111100001111 AND 0011101111111111 -------------------------- (BINARY) 0011101100001111 -------------------------- (DECIMAL) 15119 36 BASIC LANGUAGE VOCABULARY ~ When evaluating a number for truth or falsehood, the computer assumes the number is true as long as its value isn't 0. When evaluating a comparison, it assigns a value of -I if the result is true, while false has a value of 0. In binary format, -1 is all 1's and 0 is all 0's. Therefore, when ANDing true/false evaluations, the result will be true if any bits in the result are true. EXAMPLES of Using AND with True/False Evaluations: 50 IF X=7 AND W=3 THEN GOTO 10: REM ONLY TRUE IF BOTH X=7 AND W=3 ARE TRUE 60 IF A AND Q=7 THEN GOTO 10: REM TRUE IF A IS NON-ZERO AND Q=7 IS TRUE ASC TYPE: Function-Numeric FORMAT: ASC() Action: ASC will return a number from 0 to 255 which corresponds to the Commodore ASCII value of the first character in the string. The table of Commodore ASCII values is shown in Appendix C. EXAMPLES OF ASC Function: 10 PRINT ASC("Z") 20 X = ASC("ZEBRA") 30 J = ASC(J$) If there are no characters in the string, an ?ILLEGAL QUANTITY error results. In the third example above, if J$="", the ASC function will not work. The GET and GET# statement read a CHR$(0) as a null string. To eliminate this problem, you should add a CHR$(0) to the end of the string as shown below. EXAMPLE of ASC Function Avoiding ILLEGAL QUANTITY ERROR: 30 J = ASC(J$ + CHR$(0)) BASIC LANGUAGE VOCABULARY 37 ~ ATN TYPE: Function-Numeric FORMAT: ATN() Action: This mathematical function returns the arctangent of the number. The result is the angle (in radians) whose tangent is the number given. The result is always in the range -pi/2 to +pi/2. EXAMPLES of ATN Function: 10 PRINT ATN(0) 20 X = ATN(J)*180/ {pi} : REM CONVERT TO DEGREES CHR$ TYPE: Function-String FORMAT: CHR$ () Action: This function converts a Commodore ASCII code to its character equivalent. See Appendix C for a list of characters and their codes. The number must have a value between 0 and 255, or an ?ILLEGAL QUANTITY error message results. EXAMPLES of CHR$ Function: 10 PRINT CHR$(65) : REM 65 = UPPER CASE A 20 A$=CHR$(13) : REM 13 = RETURN KEY 50 A=ASC(A$) : A$ = CHR$(A) : REM CONVERTS TO C64 ASCII CODE AND BACK 38 BASIC LANGUAGE VOCABULARY ~ CLOSE TYPE: I/O Statement FORMAT: CLOSE Action: This statement shuts off any data file or channel to a device. The file number is the same as when the file or device was OPENed (see OPEN statement and the section on INPUT/OUTPUT programming). When working with storage devices like cassette tape and disks, the CLOSE operation stores any incomplete buffers to the device. When this is not performed, the file will be incomplete on the tape and unreadable on the disk. The CLOSE operation isn't as necessary with other devices, but it does free up memory for other files. See your external device manual for more details. EXAMPLES of CLOSE Statement: 10 CLOSE 1 20 CLOSE X 30 CLOSE 9*(1+J) CLR TYPE: Statement FORMAT: CLR Action: This statement makes available RAM memory that had been used but is no longer needed. Any BASIC program in memory is untouched, but all variables, arrays, GOSUB addresses, FOR...NEXT loops, user-defined functions, and files are erased from memory, and their space is mode available to new variables, etc. BASIC LANGUAGE VOCABULARY 39 ~ In the case of files to the disk and cassette tape, they are not properly CLOSED by the CLR statement. The information about the files is lost to the computer, including any incomplete buffers. The disk drive will still think the file is OPEN. See the CLOSE statement for more information on this. EXAMPLE of CLR Statement: 10 X=25 20 CLR 30 PRINT X RUN 0 READY CMD TYPE: I/O Statement FORMAT: [,string] Action: This statement switches the primary- output device from the TV screen to the file specified. This file could be on disk, tape, printer, or an I/O device like the modem. The file number must be specified in a prior OPEN statement. The string, when specified, is sent to the file. This is handy for titling printouts, etc. When this command is in effect, any PRINT statements and LIST commands will not display on the screen, but will send the text in the same format to the file. To re-direct the output back to the screen, the PRINT# command should send a blank line to the CMD device before CLOSEing, so it will stop expecting data (called "un-listening" the device). 40 BASIC LANGUAGE VOCABULARY ~ Any system error (like ?SYNTAX ERROR) will cause output to return to the screen. Devices aren't un-listened by this, so you should send a blank line after an error condition. (See your printer or disk manual for more details.) EXAMPLES of CMD Statement: OPEN 4,4: CMD 4,"TITLE" : LIST: REM LISTS PROGRAM ON PRINTER PRINT#4: CLOSE 4: REM UN-LISTENS AND CLOSES PRINTER 10 OPEN 1,1,1,"TEST" : REM CREATE SEQ FILE 20 CMD 1 : REM OUTPUT TO TAPE FILE, NOT SCREEN 30 FOR L = 1 TO 100 40 PRINT L: REM PUTS NUMBER IN TAPE BUFFER 50 NEXT 60 PRINT#1 : REM UNLISTEN 70 CLOSE 1 : REM WRITE UNFINISHED BUFFER, PROPERLY FINISH CONT TYPE: Command FORMAT: CONT Action: This command re-starts the execution of a program which was halted by a STOP or END statement or the key being pressed. The program will re-start at the exact place from which it left off. While the program is stopped, the user can inspect or change any variables or look at the program. When debugging or examining a program, STOP statements can be placed at strategic locations to allow examination of variables and to check the flow of the program. The error message CAN'T CONTINUE will result from editing the program (even just hitting with the cursor on an unchanged line), or if the program halted due to an error, or if you caused an error before typing CONT to re-start the program. EXAMPLE of CONT Command: 10 PI=0:C=1 20 PI=PI+4/C-4/(C+2) 30 PRINT PI 40 C=C+4:GOTO 20 BASIC LANGUAGE VOCABULARY 41 ~ This program calculates the value of PI. RUN this program, and after a short while hit the key. You will see the display: +----------------------------------+ BREAK IN 20 | NOTE: Might be different number. | +----------------------------------+ Type the command PRINT C to see how far the Commodore 64 has gotten. Then use CONT to resume from where the Commodore 64 left off. COS TYPE: Function FORMAT: COS () Action: This mathematical function calculates the cosine of the number, where the number is an angle in radians. EXAMPLES of COS Function: 10 PRINT COS(0) 20 X = COS(Y* {pi} /180) : REM CONVERT DEGREES TO RADIANS DATA TYPE: Statement FORMAT: DATA Action: DATA statements store information within a program. The program uses the information by means of the READ statement, which pulls successive constants from the DATA statements. The DATA statements don't have to be executed by the program, they only have to be present. Therefore, they are usually placed at the end of the program. All data statements in a program are treated as a continuous list. Data is READ from left to right, from the lowest numbered line to the highest. If the READ statement encounters data that doesn't fit the type requested (if it needs a number and finds a string) an error message occurs. 42 BASIC LANGUAGE VOCABULARY ~ Any characters can be included as data, but if certain ones are used the data item must be enclosed by quote marks (" "). These include punctuation like comma (,), colon (:), blank spaces, and shifted letters, graphics, and cursor control characters. EXAMPLES of DATA Statement: 10 DATA 1,10,5,8 20 DATA JOHN,PAUL,GEORGE,RINGO 30 DATA "DEAR MARY, HOW ARE YOU, LOVE, BILL" 40 DATA -1.7E-9, 3.33 DEF FN TYPE: Statement FORMAT: DEF FN ( ) = Action: This sets up a user-defined function that can be used later in the program. The function can consist of any mathematical formula. User- defined functions save space in programs where a long formula is used in several places. The formula need only be specified once, in the definition statement, and then it is abbreviated as a function name. It must be executed once, but any subsequent executions are ignored. The function name is the letters FN followed by any variable name. This can be 1 or 2 characters, the first being a letter and the second a letter or digit. EXAMPLES of DEF FN Statement: 10 DEF FN A(X)=X+7 20 DEF FN AA(X)=Y*Z 30 DEF FN A9(Q) = INT(RND(1)*Q+1) The function is called later in the program by using the function name with a variable in parentheses. This function name is used like any other variable, and its value is automatically calculated, BASIC LANGUAGE VOCABULARY 43 ~ EXAMPLES of FN Use: 40 PRINT FN A(9) 50 R=FN AA(9) 60 G=G+FN A9(10) In line 50 above, the number 9 inside the parentheses does not affect the outcome of the function, because the function definition in line 20 doesn't use the variable in the parentheses. The result is Y times Z, regardless of the value of X. In the other two functions, the value in parentheses does affect the result. DIM TYPE: Statement FORMAT: DIM ( )[ ( )...] Action: This statement defines an array or matrix of variables. This allows you to use the variable name with a subscript. The subscript points to the element being used. The lowest element number in an array is zero, and the highest is the number given in the DIM statement, which has a maximum of 32767. The DIM statement must be executed once and only once for each array. A REDIM'D ARRAY error occurs if this line is re-executed. Therefore, most programs perform all DIM operations at the very beginning. There may be any number of dimensions and 255 subscripts in an array, limited only by the amount of RAM memory which is available to hold the variables. The array may be mode up of normal numeric variables, as shown above, or of strings or integer numbers. If the variables are other than normal numeric, use the $ or % signs after the variable name to indicate string or integer variables, 44 BASIC LANGUAGE VOCABULARY ~ If an array referenced in a program was never DiMensioned, it is automatically dimensioned to 11 elements in each dimension used in the first reference. EXAMPLES of DIM Statement: 10 DIM A(100) 20 DIM Z (5,7), Y(3,4,5) 30 DIM Y7%(Q) 40 DIM PH$(1000) 50 F(4)=9 : REM AUTOMATICALLY PERFORMS DIM F(10) EXAMPLE of FOOTBALL SCORE-KEEPING Using DIM: 10 DIM S(1,5), T$(1) 20 INPUT"TEAM NAMES"; T$(0), T$(1) 30 FOR Q=1 TO 5: FOR T=0 TO 1 40 PRINT T$(T),"SCORE IN QUARTER" Q 50 INPUT S(T,Q): S(T,0)= S(T,0)+ S(T,Q) 60 NEXT T,Q 70 PRINT CHR$(147) "SCOREBOARD" 80 PRINT "QUARTER" 90 FOR Q= 1 TO 5 100 PRINT TAB(Q*2+9) Q; 110 NEXT: PRINT TAB(15) "TOTAL" 120 FOR T=0 TO 1: PRINT T$(T); 130 FOR Q= 1 TO 5 140 PRINT TAB(Q*2+9) S(T,Q); 150 NEXT: PRINT TAB(15) S(T,0) 160 NEXT CALCULATING MEMORY USED BY DIM: 5 bytes for the array name 2 bytes for each dimension 2 bytes/element for integer variables 5 bytes/element for normal numeric variables 3 bytes/element for string variables 1 byte for each character in each string element BASIC LANGUAGE VOCABULARY 45 ~ END TYPE: Statement FORMAT: END Action: This finishes a program's execution and displays the READY message, returning control to the person operating the computer. There may be any number of END statements within a program. While it is not necessary to include any END statements at all, it is recommended that a program does conclude with one, rather than just running out of lines. The END statement is similar to the STOP statement. The only difference is that STOP causes the computer to display the message BREAK IN LINE XX and END just displays READY. Both statements allow the computer to resume execution by typing the CONT command. EXAMPLES of END Statement: 10 PRINT"DO YOU REALLY WANT TO RUN THIS PROGRAM" 20 INPUT A$ 30 IF A$ = "NO" THEN END 40 REM REST OF PROGRAM . . . 999 END EXP TYPE: Function-Numeric FORMAT: EXP ( ) Action: This mathematical function calculates the constant e (2.71828183) raised to the power of the number given. A value greater than 88.0296919 causes an ?OVERFLOW error to occur. EXAMPLES of EXP Function: 10 PRINT EXP (1) 20 X = Y*EXP (Z*Q) 46 BASIC LANGUAGE VOCABULARY ~ FN TYPE: Function-Numeric FORMAT: FN ( ) Action: This function references the previously DEFined formula spec- ified by name. The number is substituted into its place (if any) and the formula is calculated. The result will be a numeric value. This function can be used in direct mode, as long as the statement DEFining it has been executed. If an FN is executed before the DEF statement which defines it, an UNDEF'D FUNCTION error occurs. EXAMPLES of FN (User-Defined) Function: PRINT FN A(Q) 1100 J = FN J(7)+ FN J(9) 9990 IF FN B7 (1+1)= 6 THEN END FOR ... TO ... [STEP ... TYPE: Statement FORMAT: FOR = TO [ STEP ] Action: This is a special BASIC statement that lets you easily use a variable as a counter. You must specify certain parameters: the floating-point variable name, its starting value, the limit of the count, and how much to add during each cycle. Here is a simple BASIC program that counts from 1 to 10, PRINTing each number and ENDing when complete, and using no FOR statements: 100 L = 1 110 PRINT L 120 L = 1 + 1 130 IF L <= 10 THEN 110 140 END BASIC LANGUAGE VOCABULARY 47 ~ Using the FOR statement, here is the same program: 100 FOR L = 1 TO 10 110 PRINT L 120 NEXT L 130 END As you can see, the program is shorter and easier to understand using the FOR statement. When the FOR statement is executed, several operations take place. The value is placed in the being used in the counter. In the example above, a I is placed in L. When the NEXT statement is reached, the value is added to the . If a STEP was not included, the is set to + 1. The first time the program above hits line 120, 1 is added to L, so the new value of L is 2. Now the value in the is compared to the . If the has not been reached yet, the program G0es TO the line after the original FOR statement. In this case, the value of 2 in L is less than the limit of 10, so it GOes TO line 110. Eventually, the value of is exceeded by the . At that time, the loop is concluded and the program continues with the line following the NEXT statement. In our example, the value of L reaches 11, which exceeds the limit of 10, and the program goes on with line 130. When the value of is positive, the must exceed the , and when it is negative it must become less than the . +---------------------------------------------+ | NOTE: A loop always executes at least once. | +---------------------------------------------+ EXAMPLES of FOR...TO...STEP...Statement: 100 FOR L = 100 TO 0 STEP -1 100 FOR L = PI TO 6* {pi} STEP .01 100 FOR AA = 3 TO 3 48 BASIC LANGUAGE VOCABULARY ~ FRE TYPE: Function FORMAT: FRE ( ) Action: This function tells you how much RAM is available for your program and its variables. If a program tries to use more space than is available, the OUT OF MEMORY error results. The number in parentheses can have any value, and it is not used in the calculation. +-----------------------------------------------------------------------+ | NOTE: If the result of FRE is negative, add 65536 to the FRE number | | get the number of bytes available in memory. | +-----------------------------------------------------------------------+ EXAMPLES of FRE Function: PRINT FRE(0) 10 X = (FRE(K)-1000)/7 950 IF FRE(0)< 100 THEN PRINT "NOT ENOUGH ROOM" +-----------------------------------------------------------------------+ | NOTE: The following always tells you the current available RAM: | | PRINT FRE(0) - (FRE(0) < 0)* 65536 | +-----------------------------------------------------------------------+ GET TYPE: Statement FORMAT: GET Action: This statement reads each key typed by the user. As the user is typing, the characters are stored in the Commodore 64's keyboard buffer. Up to 10 characters are stored here, and any keys struck after the 10th are lost. Reading one of the characters with the GET statement makes room for another character. If the GET statement specifies numeric data, and the user types a key other than a number, the message ?SYNTAX ERROR appears. To be safe, read the keys as strings and convert them to numbers later. BASIC LANGUAGE VOCABULARY 49 ~ The GET statement can be used to avoid some of the limitations of the INPUT statement. For more on this, see the section on Using the GET Statement in the Programming Techniques section. EXAMPLES of GET Statement: 10 GET A$: IF A$ ="" THEN 10: REM LOOPS IN 10 UNTIL ANY KEY HIT 20 GET A$, B$, C$, D$, E$