Original Title: Commodore 128 Personal Computer System Guide Published by: Commodore Business Machines, Ltd. 1985 Typed by: Rene van Belzen Version: April 7, 2000 Notes from the typist ===================== Entering (data typing) the Commodore 128 System Guide... This entailed far more than I bargained for. This is because not only because the original text contained errors, which had to be corrected, but also because some useful information and hints were missing. I could have written a separate e-book containing what I feel should have been included in the C128 System Guide as well (and I still may do that one day). In stead I added some words here and there to clarify matters, to avoid wandering off too much from the original text. This means this e-text is not an exact 1:1 replica of the original, but I'm sure the authors of the original System Guide wouldn't object (too much). They pro- bably had to write the System Guide in a jiffie, while I could take as long as I wanted to get the text just right. Credits: ------- Most of the e-text I have typed (and corrected) myself. However, some of the ASCII art and some of the appendixes I have copied and adapted from the C64 Programmer's Reference Guide, the e-text version by Ville Muikkula. Also, where the original text by Commodore had shortcomings I added/corrected text. Many thanks to all those people who pointed me to the existing errors in one of my earlier publications of the C128 System Guide. April 7, 2000 Rene van Belzen mailto:hurray@xs4all.nl http://www.xs4all.nl/~hurray/cbm/ (Note that both the e-mail and web address may change at any point in the future.) System Guide Commodore 128 Personal Computer (c) Commodore Electronics, Ltd. 1985. All rights reserved. Copyright (c) 1985 by Commodore Electronics Limited All rights reserved This manual contains copyrighted and proprietary information. No part of this publication may be reproduced, stored in a retrieval system, or trans- mitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of Commodore Electronics Limited. Commodore BASIC 7.0 Copyright (c) 1985 by Commodore Electronics Limited; All rights reserved Copyright (c) 1977 by Microsoft Corp. All rights reserved CP/M (R) Plus Version 3.0 Copyright (c) 1982 Digital Research Inc. All rights reserved CP/M is a registered trademark of Digital Research Inc. CONTENTS C128 SYSTEM GUIDE CHAPTER I - INTRODUCTION SECTION 1 - HOW TO USE THIS GUIDE SECTION 2 - OVERVIEW OF THE COMMODORE 128 PERSONAL COMPUTER CHAPTER II - USING C128 MODE SECTION 3 - GETTING STARTED IN BASIC SECTION 4 - ADVANCED BASIC PROGRAMMING SECTION 5 - SOME BASIC COMMANDS AND KEYBOARD OPERATIONS UNIQUE TO C128 SECTION 6 - COLOR, ANIMATION AND SPRITE GRAPHICS SECTION 7 - SOUND AND MUSIC IN C128 MODE SECTION 8 - USING 80 COLUMNS CHAPTER III - USING C64 MODE SECTION 9 - USING BASIC IN C64 MODE SECTION 10 - STORING AND REUSING YOUR PROGRAMS IN C64 MODE CHAPTER IV - CP/M MODE SECTION 11 - INTRODUCTION OT CP/M 3.0 SECTION 12 - FILES, DISKS AND DRIVES IN CP/M 3.0 SECTION 13 - USING THE CONSOLE AND PRINTER IN CP/M 3.0 SECTION 14 - SUMMARY OF MAJOR CP/M 3.0 COMMANDS SECTION 15 - COMMODORE ENHANCEMENTS TO CP/M 3.0 CHAPTER V - BASIC 7.0 ENCYCLOPAEDIA SECTION 16 - INTRODUCTION SECTION 17 - BASIC COMMANDS AND STATEMENTS SECTION 18 - BASIC FUNCTIONS SECTION 19 - VARIABLES AND OPERATIONS SECTION 20 - RESERVED WORDS AND SYMBOLS APPENDICES APPENDIX A - BASIC LANGUAGE ERROR MESSAGES APPENDIX B - DOS ERROR MESSAGES APPENDIX C - CONNECTORS/PORTS FOR PERIPHERAL EQUIPMENT APPENDIX D - SCREEN DISPLAY CODES APPENDIX E - ASCII AND CHR$ CODES APPENDIX F - SCREEN AND COLOR MEMORY MAPS APPENDIX G - DERIVED MATHEMATICAL FUNCTIONS APPENDIX H - MEMORY MAP APPENDIX I - CONTROL AND ESCAPE CODES APPENDIX J - MACHINE LANGUAGE MONITOR APPENDIX K - BASIC 7.0 ABBREVIATIONS APPENDIX L - DISK COMMAND SUMMARY GLOSSARY INDEX CHAPTER 1 INTRODUCTION SECTION 1 1. How to Use This Guide This Commodore 128 System Guide is designed to help you make full use of the advanced capabilities of the Commodore 128 computer. Before you read any further in this System Guide, make sure you have read the other book that comes with your computer, the Commodore 128 Personal Computer Introductory Guide. This introductory guide contains important information on getting started with the Commodore 128. If you are primarily interested in using the BASIC language to create and run your own programs, you should read Chapter II, USING C128 MODE. This chapter introduces you to the BASIC programming language as used in both C128 and C64 modes, describes the Commodore 128 keyboard, defines some advanced commands you can use in both C128 and C64 modes, shows how to use a number of powerful new BASIC commands (including colour, graphic and sound commands) that are unique to C128 Mode, and describes how to use the 80-column capabilities available in C128 Mode. If you want to use BASIC in C64 Mode, read Chapter III, USING C64 MODE. If you want to use CP/M on the Commodore 128, read Chapter IV, USING CP/M MODE. This chapter tells you how to start up and use CP/M on the Commodore 128. In CP/M you can choose from thousands of commercial software packages, including the PERFECT series (PERFECT WRITER, PERFECT CALC, PERFECT FILER). You can also create your own CP/M programs. If you want details on the BASIC 7.0 commands, read Chapter IV, BASIC 7.0 ENCYCLOPAEDIA. This chapter gives format and usage details on all BASIC 7.0 commands, statements and functions. If, after reading Chapters I through V, you are looking for additional technical information about a particular Commodore 128 topic, first check the Appendices to this System Guide. These appendices contain a wide range of information, such as a complete list of BASIC and DOS error messages and a summary of disk commands. A Glossary following the Appendices provides definitions of computing terms. For complete technical details about any feature of the Commodore 128, con- sult the Commodore 128 Programmer's Reference Guide. SECTION 2 2. Overview of the Commodore C128 Personal Computer 2.1 OVERVIEW OF THE COMMODORE C128 PERSONAL COMPUTER 2.1.1 C128 MODE 2.1.2 C64 MODE 2.1.3 CP/M MODE 2.2 SWITCHING BETWEEN MODES 2.2.1 MODE SWITCHING CHART 2.1 OVERVIEW OF THE COMMODORE C128 PERSONAL COMPUTER The Commodore 128 Personal Computer offers three primary operating modes: * C128 Mode * C64 Mode * CP/M Mode 2.1.1 C128 Mode In C128 Mode, the Commodore 128 Personal Computer provides access to 128K of RAM and a powerful extended BASIC language known as BASIC 7.0. BASIC 7.0 offers over 140 commands, statements and functions. C128 Mode also provides both 40 and 80 column output and full use of the 92-key keyboard. A built- in machine language monitor allows you to create and debug your own machine language programs. In C128 Mode you can use a number of new peripheral devices from Commodore, including a new fast serial disk drive (the 1571), a mouse, and a 40/80 column composite video/RGBI monitor (the 1901). You can also use all standard Commodore serial peripherals. 2.1.2 C64 Mode In C64 Mode, the Commodore 128 operates exactly like a Commodore 64 com- puter, allowing you to take full advantage of the wide range of available C64 software. You also have full compatibility with all C64 peripherals. C64 Mode provides BASIC 2.0 language, 40 column output and access to 64K of RAM. 2.1.3 CP/M Mode In CP/M Mode, an onboard Z80 microprocessor gives you all the capabilities of Digital Research's CP/M Plus version 3.0, plus several new capabilities by Commodore. The Commodore 128's CP/M package, called CP/M Plus, provides 128K of RAM, 40 and 80 column output, access to the full keyboard, inclu- ding the numeric keypad and special keys, and access to the new Commodore 1571 fast serial disk drive as well as standard serial peripherals. Chapters II, III and IV, which include Sections 3 through 15, tell you how to access and use the capabilities of the three powerful and versatile operating modes of the Commodore 128 Personal Computer. 2.2 Switching Between Modes The following chart tells you how to switch to one mode from another. NOTE: If you are using a Commodore 1901 dual monitor remember to move the video switch on the monitor from the COMPOSITE or SEPARATED to RGBI when switching from 40 column to 80 column display. Reverse this step when switching from 80 to 40 columns. 2.2.1 MODE SWITCHING CHART FROM T| OFF C128 C128 C64 CP/M CP/M O| 40 COL(1) 80 COL(2) (3) 40 COL(4) 80 COL(5) -+------------+-----------+-----------+-----------+-----------+-----------+ 1|1.Check that| |1.Press |1.Check |1.Check |1.Check | | {40/80} | | {esc} | that | that | that | | key is UP.| | key; | {40/80} | {40/80} | {40/80} | |2.Turn | | release. | key is | key is | key is | | computer | |2.Press X | UP. | UP. | UP. | | ON. | | key. |2.Turn |2.Remove |2.Remove | | | OR | computer | CP/M | CP/M | | | |1.Check | OFF, then| system | system | | | | that | ON. | disk, if | disk, if | | | | {40/80} | | neces- | neces- | | | | key is | | sary. | sary. | | | | UP. | |3.Turn |3.Turn | | | |2.Press | | computer | computer | | | | {reset} | | OFF, then| OFF, then| | | | button. | | ON. | ON. | -+------------+-----------+-----------+-----------+-----------+-----------+ 2|1.Press |1.Press | |1.Press |1.Press |1.Check | | {40/80} | {esc} | | {40/80} | {40/80} | that | | key DOWN. | key; | | key DOWN.| key DOWN.| {40/80} | |2.Turn | release. | |2.Turn |2.Remove | key is | | computer |2.Press X | | computer | CP/M | DOWN. | | ON. | key. | | OFF, then| system |2.Remove | | | OR | | ON. | disk from| CP/M | | |1.Press | | | drive, if| system | | | {40/80} | | | neces- | disk from| | | key DOWN.| | | sary. | drive, if| | |2.Press | | |3.Turn | neces- | | | {reset} | | | computer | sary. | | | button. | | | OFF, then|3.Turn | | | | | | ON. | computer | | | | | | | OFF, then| | | | | | | ON. | -+------------+-----------+-----------+-----------+-----------+-----------+ 3|1.Hold {C=} |1.Type |1.Type | |1.Turn |1.Turn | | key DOWN. | GO 64; | GO 64; | | computer | computer | |2.Turn | press | press | | OFF. | OFF. | | computer | {return}.| {return}.| |2.Check |2.Check | | ON. |2.The |2.The | | that | that | | OR | computer | computer | | {40/80} | {40/80} | |1.Insert C64| responds:| responds:| | key is | key is | | cartridge.| ARE YOU | ARE YOU | | UP. | UP. | |2.Turn | SURE? | SURE? | |3.Hold DOWN|3.Hold DOWN| | computer | Type Y; | Type Y; | | {C=} key | {C=} key | | ON. | press | press | | while | while | | | {return}.| {return}.| | turning | turning | | | | | | computer | computer | | | | | | ON. | ON. | | | | | | OR | OR | | | | | |1.Turn |1.Turn | | | | | | computer | computer | | | | | | OFF. | OFF. | | | | | |2.Insert |2.Insert | | | | | | C64 car- | C64 car- | | | | | | tridge. | tridge. | | | | | |3.Turn |3.Turn | | | | | | power ON.| power ON.| -+------------+-----------+-----------+-----------+-----------+-----------+ 4|1.Turn disk |1.Turn disk|1.Turn disk|1.Check | |1.Insert | | drive ON. | drive ON.| drive ON.| that | | CP/M | |2.Insert |2.Insert |2.Insert | {40/80} | | utilities| | CP/M sys- | CP/M sys-| CP/M sys-| key is | | disk in | | tem disk | tem disk | tem disk | UP. | | drive. | | in disk | in disk | in disk |2.Turn disk| |2.At screen| | drive. | drive. | drive. | drive ON.| | prompt, | |3.Check that|3.Check |3.Check |3.Insert | | A> type: | | {40/80} | that | that | CP/M | | DEVICE | | key is UP.| {40/80} | {40/80} | system | | CONOUT | |4.Turn | key is | key is | disk in | | = 40COL. | | computer | UP. | UP. | drive. | |3.Press | | ON. |4.Type: |4.Type: |4.Turn | | {return}.| | | BOOT. | BOOT. | computer | | | | |5.Press |5.Press | OFF, then| | | | | {return}.| {return} | ON. | | | -+------------+-----------+-----------+-----------+-----------+-----------+ 5|1.Turn disk |1.Turn disk|1.Turn disk|1.Press |1.Insert | | | drive ON. | drive ON.| drive ON.| {40/80} | CP/M | | |2.Insert |2.Insert |2.Insert | key DOWN.| utilities| | | CP/M sys- | CP/M sys-| CP/M sys-|2.Turn disk| disk in | | | tem disk | tem disk | tem disk | drive ON.| drive. | | | in disk | in disk | in disk |3.Insert |2.At screen| | | drive. | drive. | drive. | CP/M | prompt | | |3.Press |3.Press |3.Check | system | A> type: | | | {40/80} | {40/80} | that | disk in | DEVICE | | | key DOWN. | key DOWN.| {40/80} | drive. | CONOUT | | |4.Turn |4.Type: | key is |4.Turn | = 80COL. | | | computer | computer | DOWN. | computer |3.Press | | | ON. | BOOT. |4.Type: | OFF, then| {return}.| | | |5.Press | BOOT. | ON. | | | | | {return}.|5.Press | | | | | | | {return}.| | | | -+------------+-----------+-----------+-----------+-----------+-----------+ NOTE: If you are using a Commodore 1902 dual monitor, remember to move the video switch on the monitor from COMPOSITE or SEPARATED to RGBI when switching from 40-column to 80-column display; reverse this step when switching from 80 to 40 columns. Also, when switching between modes remove any cartridges from the expansion port and any disks from the disk drive. CHAPTER 2 USING C128 MODE SECTION 3 3. Getting Started in Basic 3.1 BASIC PROGRAMMING LANGUAGE 3.1.1 Direct Mode 3.1.2 Program Mode 3.2 USING THE KEYBOARD 3.2.0.1 C128 Keyboard Lay-Out 3.2.1 Keyboard Character Sets 3.2.2 Using the Command Keys 3.2.2.1 Return 3.2.2.2 Shift 3.2.2.3 Shift Lock 3.2.2.4 Moving the cursor 3.2.2.4.1 Using the four Arrow Cursor keys 3.2.2.4.2 Using the CRSR keys 3.2.2.5 INST/DEL 3.2.2.5.1 Insterting characters 3.2.2.5.2 Deleting characters 3.2.2.5.3 Using INSerT and DELete together 3.2.2.6 Control 3.2.2.7 Run/Stop 3.2.2.8 Restore 3.2.2.9 CLR/Home 3.2.2.10 Commodore key 3.2.3 Function Keys 3.2.4 Displaying Graphic Characters 3.2.5 Rules for Typing BASIC Language Programs 3.3 GETTING STARTED - THE PRINT COMMAND 3.3.1 Printing Numbers 3.3.2 Using the Question Mark to Abbreviate the PRINT Command 3.3.3 Printing Text 3.3.4 Printing in Different Colors Table 3-1. Available Colors in 40- and 80-Column Screen Formats. 3.3.5 Using the Cursor Keys Inside Quotes with the PRINT Command 3.4 BEGINNING TO PROGRAM 3.4.1 What a Program Is 3.4.2 Line Numbers 3.4.3 Viewing your Program - The LIST Command 3.4.4 A Simple Loop - The GOTO Command 3.4.5 Clearing the Computer's Memory - The NEW Command 3.4.6 Using Color in a Program 3.5 EDITING YOUR PROGRAM 3.5.1 Erasing a Line from a Program 3.5.2 Duplicating a Line 3.5.3 Replacing a Line 3.5.4 Changing a Line 3.6 MATHEMATICAL OPERATIONS 3.6.1 Addition and Subtraction 3.6.2 Multiplication and Division 3.6.3 Exponentiation 3.6.4 Order of Operations 3.6.5 Using Parentheses to Define the Order of Operations 3.7 CONSTANTS, VARIABLES AND STRINGS 3.7.1 Constants 3.7.2 Variables 3.7.3 Strings 3.8 SAMPLE PROGRAM 3.9 STORING AND REUSING YOUR PROGRAMS 3.9.1 Formatting a Disk - The HEADER Command 3.9.2 SAVEing on Disk 3.9.3 SAVEing on Cassette 3.9.4 LOADing from Disk 3.9.5 LOADing from Cassette Tape 3.9.6 Other Disk-Related Commands 3.9.6.1 Verifying a Program 3.9.6.2 Displaying Your Disk Directory 3.1 BASIC PROGRAMMING LANGUAGE The BASIC programming language is a special language that lets you communi- cate with your Commodore 128. Using BASIC is one means by which you instruct your computer what to do. BASIC has its own vocabulary (made up of commands, statements and func- tions) and its own rules of structure (called syntax). You can use the BASIC vocabulary and syntax to create a set of instructions called a program, which your computer can then perform or "run". Using BASIC, you can communicate with your Commodore 128 in two ways: within a program, or directly (outside a program). 3.1.1 Direct Mode Your Commodore 128 is ready to accept BASIC commands in direct mode as soon as you turn on the computer. In the direct mode, you type commands on the keyboard and enter them into the computer by pressing the {return} key. Most BASIC commands in your Commodore 128 can be used in direct mode as well as in a program. 3.1.2 Program Mode In program mode you enter a set of instructions that perform a specific task. Each instruction is contained in a sequential program line. A state- ment in a program may be as long as 160 characters; this is equivalent to four full screen lines in 40-column format, and two full screen lines in 80-column format. Once you have typed a program, you can use it immediately by typing the RUN command and pressing the {return} key. You can also store the program on disk or tape by using the DSAVE (or SAVE) command. Then you recall it from the disk or tape by using the DLOAD (or LOAD) command. This command copies the program from the disk or tape and places that program in the Commodore 128's memory. You can then use or "execute" the program again by entering the RUN command. All these commands are explained later in this section. Most of the time you will be using you computer with programs, including programs you yourself write, and commercially available software packages. The only time you operate in direct mode is when you are manipulating or editing your programs with commands such as LIST, LOAD, SAVE and RUN. As a rule, the difference between direct mode and operation within a program is that direct mode commands have no line numbers. 3.2 USING THE KEYBOARD Shown below is the keyboard of the Commodore 128 Personal Computer. 3.2.0.1 C128 Keyboard Lay-Out +--------------+ /E\/T\/A\/C\ /H\/L\/4\/N\ /u\/d\/l\/r\ | /F\/F\/F\/F\ | |s a l | |l | |p w f g| | |1 3 5 7| | \c/\b/\t/\L/ \p/\F/\8/\S/ \ /\n/\t/\t/ | \ /\ /\ /\ / | +--------------------------------------------------+--------------+ | /L\/!\/"\/#\/$\/%\/&\/'\/(\/)\/ \/ \/ \/l\/C\/I\ | / \/ \/ \/ \ | | 0 + - b | | |7 8 9 +| | \A/\1/\2/\3/\4/\5/\6/\7/\8/\9/\ /\ /\ /\s/\H/\D/ | \ /\ /\ /\ / | | | /co\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/U\/RES\ | / \/ \/ \/ \ | |nt Q W E R T Y U I O P @ * STO| | |4 5 6 -| | \rl/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\A/\RE / | \ /\ /\ /\ / | | | /R\/S\/ \/ \/ \/ \/ \/ \/ \/ \/ \/ \/[\/]\/RE \ | / \/ \/ \/ \ | | h A S D E F G H J K L TURN| | |1 2 3||E| | \S/\L/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\:/\;/\ / | \ /\ /\ /|N| | | |T| | /C\/SH\/ \/ \/ \/ \/ \/ \/ \/<\/>\/?\/SHI\/C\/C\ | / \/ \|E| | |= IF Z X C V B N M FT ||u||l| | | 0 .||R| | \ /\T /\ /\ /\ /\ /\ /\ /\ /\,/\./\//\ /\d/\r/ | \ /\ /\ / | | | [ spacebar ] | +--------------------------------------------------+ C L = {caps lock} Hlp = {help} L F = {line feed} 4 8 = {40/80 dsp} N S = {no scroll} up = {crsr up} dwn = {crsr down} lft = {crsr left} rgt = {crsr right} L A = {left arrow} lbs = {pound} C H = {clr/home} I D = {inst/del} contrl = {ctrl} U A = {up arrow} R S = {run/stop} ShL = {shift lock} C= = {commodore} Cud = {crsr up/down} Clr = {crsr left/right} Note: Outlined key areas can be used in C64 Mode. Using BASIC is essentially the same in both C64 and C128 modes. Most of the keys, and many of the commands you will learn, can be used to program BASIC in either mode. The keys that are shaded in the diagram above can be used in C64 mode. In C128 mode you can use all of the keys on the keyboard. 3.2.1 Keyboard Character Sets The Commodore 128 keyboard offers two different sets of characters: - Uppercase letters and graphic characters - Upper- and lowercase letters In 80-column format, both character sets are available simultaneously. This gives you a total of 512 different characters that you can display on the screen. In 40-column format you can use only one character set at a time. When you turn on the Commodore 128 in 40-column format, the keyboard nor- mally is using the uppercase/graphic character set. This means that every- thing you type is in capital letters. To switch back and forth between the two character sets, press the {shift} key and the {C=} key (the COMMODORE key) at the same time. To practice using the two character sets turn on your computer and press several letters or graphic characters. Then press the {shift} key and the {C=}(Commodore) key. Notice how the screen changes to upper- and lowercase characters. Press {shift} and {C=} again to return to the uppercase and graphic character set. 3.2.2 Using the Command Keys COMMAND keys are keys that send messages to the computer. Some command keys (such as {return}) are used by themselves. Other keys such as {shift}, {ctrl}, {C=} and {restore}) are used with other keys. The use of each of the command keys is explained below. The keys used in C128 mode are des- cribed in Section 5. 3.2.2.1 Return When you press the {return} key, what you have typed is sent to the Commo- dore 128 computer's memory. Pressing the {return} key also moves the cursor (the small flashing rectangle that marks where the next character you type will appear) to the next line. At times you may misspell a command or type in something the computer does not understand. Then, when you press the {return} key, you probably will get a message like SYNTAX ERROR on the screen. This is called an "Error Message". Appendix A lists the error messages and tells how to correct the errors. 3.2.2.2 Shift There are two {shift} keys on the bottom row of the keyboard. One key is the one on the left and the other on the right, just as on a standard type- writer keyboard. The {shift} key can be used in three ways: 1. With the upper/lowercase character set, the {shift} key is used like the shift key on a regular typewriter. When the {shift} key is hold down, it lets you print capital letters or the top characters on double-character keys. 2. The {shift} key can be used with some of the other command keys to per- form special functions. 3. When the keyboard is set for the uppercase/graphic character set, you can use the {shift} key to print the graphic symbols or characters that appear on the right of the front face of certain keys. See paragraph 3.2.4 at the end of this section for more details. 3.2.2.3 Shift Lock When you press this key down, it locks into place. Then, whatever you type will either be a capital letter, or the top character of a double-character key. To release the lock, press down on the {shift lock} key again. 3.2.2.4 Moving the cursor In C128 mode, you can move the cursor by using either the four arrow keys located just above the top right of the main keyboard, or the two keys labeled {crsr}, at the right of the bottom row of the main keyboard. 3.2.2.4.1 Using the four Arrow Cursor keys In C128 mode, the cursor can be moved in any direction simply by using the arrow key in the top row that points in the direction you want to move the cursor. (These keys cannot be used in C64 mode). 3.2.2.4.2 Using the CRSR keys In both C128 and C64 mode, you can use the two keys on the right side of the bottom row of the main keyboard to move the cursor: - Pressing the {crsr up/down} key alone moves the cursor down. - Pressing the {crsr up/down} and {shift} keys together moves the cursor up. - Pressing the {crsr left/right} key alone moves the cursor right. - Pressing the {crsr left/right} and {shift} keys together moves the cursor left. You don't have to keep tapping a cursor key to move more than one space. Just hold the key down and the cursor continues to move, release it when it reaches the position you want. Notice that when the cursor reaches the right side of the screen, it "wraps", or starts again at the beginning of the next row. When moving left, the cursor will move along until it reaches the edge of the screen, then it will jump up to the end of the preceding line. You should try to become very familiar with the cursor keys, because moving the cursor makes your programming much easier. With a little practice you will find that you can move the cursor almost without thinking about it. 3.2.2.5 Inst/Del This is a dual purpose key. INST stands for INSerT, and DEL for DELete. 3.2.2.5.1 Inserting Characters You must use the {shift} key with the {inst/del} key when you want to insert characters in a line. Suppose you left some characters out of a line like this: WHILE WERE OUT_ To insert the missing characters, first use the cursor keys to move the cursor back to the error. like this: WHILE_WERE OUT Then, while you hold down the {shift} key, press the {inst/del} key until you have enough space to add the missing characters: WHILE_ WERE OUT Notice that {inst} doesn't move the cursor; it just adds space between the cursor and the character to its right. To make the correction type the mis- sing {space}, {y}, {o} and {u} like this: WHILE YOU_WERE OUT 3.2.2.5.2 Deleting characters When you press the {del} key, the cursor move one space to the left and erases the character that is there and moves any characters to the right of the cursor one position to the left. This means that when you want to delete something, you move the cursor just to the right of the character you want to DELete. Suppose you have made a mistake in typing, like this: PRINT "ERROER"_ You wanted to type the word ERROR, not ERROER. To delete the incorrect E that precedes the final R, position the cursor on the final R. When you press the {del} key, the R automatically moves over one space to the left. You now have the correct wording like this: PRINT "ERROR" 3.2.2.5.3 Using INSerT and DELete together You can use the INSerT and DELete functions together to fix incorrect characters. First, move the cursor one space after the incorrect characters and press the {inst/del} key by itself to delete the incorrect characters. Next, press the {shift} key and the {inst/del} key together to add any necessary space. 3.2.2.6 Control The {ctrl} key is used with other keys to do special task called control functions. To perform a control function, hold down the {ctrl} key while you press some other key. A full list of control sequences is given in ASCII, CHR$ and ESC codes. Control functions are often used in prepackaged software such as a word processing system. One control function that is used often is setting the character and cursor color. To select a color, hold down the {ctrl} key while you press a number key ({1} throught {8}), on the top row of the main keyboard. There are eight more colors available to you; these can be selected with the {C=} key, as explained later. 3.2.2.7 Run/Stop This is a dual function key. Under certain conditions you can use the RUN function of this key by pressing the {shift} and {run/stop} key together. It is also possible to use the STOP function of the key to halt a program or a printout by pressing this key while the program is running. However, in most prepackaged programs, the STOP function of the {run/stop} key is intentionally disabled (made unusable). This is done to prevent the user from trying to stop a program that is running before it reaches its normal end point. If the user were able to stop the program, valuable data could be lost. 3.2.2.8 Restore The {restore} key is used with the {run/stop} key to return the computer to its standard condition. Most prepackaged programs disable the {restore} key for the same reason the disable the STOP function of the {run/stop} key: to prevent losing valuable data. 3.2.2.9 CLR/Home CLR stands for CLeaR. HOME refers to the upper left corner of the screen, which is called the HOME position. If you press this by itself the cursor returns to the HOME position. When you use the {shift} key with the {clr/home} key, the screen CLeaRs and the cursor returns to the HOME position. 3.2.2.10 Commodore key The {C=} key (known as the {commodore} key) has a number of functions, including the following ones: 1. When used with the {shift} key, the {C=} key lets you switch between uppercase/graphics mode and upper-/lowercase text modes. 2. When you're in either mode, the {C=} key acts as a shift to let you type graphics symbols pictured on the LEFT front of each key. Just hold down the {C=} and press teh graphic key you want. 3. When you want to change the color you are typing in to one of the 8 colors listed on the BOTTOM row of the face of the color keys (number keys {1} through {8} on the main keyboard): press {C=} and the color you want. 4. When you want to slow down a scrolling program display, hold down the {C=} key. The display scrolling speed slows down considerably. When you release this key, the screen scrolling resumes at normal speed. 5. If you hold down the {C=} key while turning on the computer, you immediately access C64 mode. 3.2.3 Function Keys The four keys above the numeric keypad (marked F1, F3, F5 and F7 on the top and F2, F4, F6 and F8 on the front) are called function keys. In both C128 and C64 modes, you can program the function keys. (See the KEY command des- criptions in Section 5, paragraph 5.9.2 of Chapter II and in Section 17, paragraph 17.53 of Chapter V, BASIC 7.0 Encyclopaedia). These keys are often used by prepackaged software to allow you to perform a task with a single keystroke. 3.2.4 Displaying Graphic Characters To display the graphic symbol on the right front of a key, hold down the {shift} key while you press the key that has the graphic character you want to print. You can display the right side graphic character only when the keyboard is in the uppercase/graphics character set (one normal character set usually available at power-up). To display the graphic character on the left front face of a key, hold down the {C=} key while you press the key that has the graphic character you want. You can display the left graphic character while the keyboard is in either character set. 3.2.5 Rules for Typing BASIC Language Programs You can type and use BASIC language programs even without knowing BASIC. You must type carefully, however, because a typing error may cause the computer to reject your information. The following guidelines will help minimize errors when typing or copying a program listing. 1. Spacing between words is not critical; e.g. typing FORT=1TO10 is the same as typing FORT=1 TO 10. However, a BASIC keyword itself must not be broken up by spaces (see Section 20, paragraph 20.1, of the BASIC 7.0 Encyclopaedia in Chapter V for a list of BASIC keywords). 2. Any characters can be typed inside quotation marks. Some characters have special functions when placed inside quotation marks, These functions are explained later in this guide. 3. Be careful with punctuation marks. Commas, colons and semicolons also have special properties, explained later in this guide. 4. Always press the {return} key after completing a numbered line. 5. Never type more than 160 characters in a program line. Remember, this is the same as four full screen lines in 40-column format, or two full screen lines in 80-column format. See Section 8 for more details on 40- and 80-columns formats. 6. Distinguish clearly between the letter {l} and the numeral {1} and between the capital letter {O} and the numeral {0} (zero). 7. The computer ignores anything following the letters REM on a program line. REM stands for REMark. You can use the REM statement to put com- ments in you program that tell anyone listing the program what is happe- ning at a specific point. Follow these guidelines when you type the examples and programs shown in this section. 3.3 GETTING STARTED - THE PRINT COMMAND The PRINT command tells the computer to display information on the screen. You can print both numbers and text (letters), but there are special rules for each case, described in the following paragraphs. 3.3.1 Printing Numbers To print numbers, use the PRINT command followed by the number(s) you want to print. Try typing this on you Commodore 128: PRINT 5 Then press the {return} key. Notice the number 5 is now displayed on the screen. Now type this and press {return}: PRINT 5,6 In this PRINT command, the comma tells the Commodore 128 that you want to print more than one number. When the computer finds commas in a string of numbers in a PRINT statement, the output is displayed to the nearest tenth column. If you don't want all the extra spaces, use a semicolon (;) in your PRINT statement instead of a comma. The semicolon tells the computer to print the numbers next to each other. A number when printed has either a space or a minus sign preceding it and a skip character after it. Type these examples and see what happens: PRINT 5;6 {return} PRINT 100;-200;300;-400;500 {return} 3.3.2 Using the Question Mark to Abbreviate the PRINT Command You can use a quotation mark (?) as an abbreviation for the PRINT command. Many of the examples in this section use the ? symbol in place of the word PRINT. In fact, most of the BASIC commands can be abbreviated. The abbreviations for BASIC commands can be found in Appendix K of this Guide. 3.3.3 Printing Text Now that you know how to print numbers, it's time to learn how to print text. It's actually very simple. Any words or characters you want to dis- play are typed on the screen, with a quote symbol at each end of the string of characters. String is the BASIC name for any set of characters sur- rounded by quotes. The quote character is obtained by pressing "SHIFT" and the number {2} key on top of the main keyboard (not the {2} in the numeric keypad). Try these examples: ? "COMMODORE 128" {return} ? "4*5" {return} Notice that when you press {return}, the computer displays the character within the quotes on the screen. Also note that the second example did not calculate 4*5 since it was treated as a string and not a mathematical cal- culation. If you want to calculate the result of 4*5, use the following com- mand: ? 4*5 {return} You can PRINT any string you want by using the PRINT command and surroun- ding the printed characters with quotes. You can combine text and calcula- tions in a single PRINT command like this: ? "4*5 = "4*5 {return} See how the computer PRINTs the characters in quotes, makes the calculation and PRINTs the result. It doesn't matter whether the text or calculation comes first. In fact, you can use both several times in one PRINT command. Type the following statement: ? 4*(2+3)" is the same as "4*5 {return} Notice that even spaces inside the quotation marks are printed on the screen. Type: ? " OVER HERE" {return} 3.3.4 Printing in Different Colors The Commodore 128 is capable of displaying 16 different colors on the screen. You can change colors easily. All you do is hold down the {ctrl} key and press a numbered key between one and eight on the top row of the main keyboard. Notice that the cursor changes color according to the num- bered key you pressed. All the succeeding characters are displayed in the color you selected. Hold down the {C=} key and press a numbered key between one and eight, and eight additional colors are displayed on the screen. Table 3-1 list the colors available in C128 mode, for both 40-column and 80-column screen formats. The tables also show the key sequence (CONTROL key plus number key, or {C=} key plus number key) used to specify a given color. Table 3-1. Available Colors in 40- and 80-Column Screen Formats. CONTROL + Color {C=} + Color 1 Black 1 Orange 2 White 2 Brown 3 Red 3 Light Red 4 Cyan 4 Dark Grey 5 Purple 5 Middle Grey 6 Green 6 Light Green 7 Blue 7 Light Blue 8 Yellow 8 Light Grey Colors in 40-Column Format CONTROL + Color {C=} + Color 1 Black 1 Dark Purple 2 White 2 Brown 3 Dark Red 3 Light Red 4 Light Cyan 4 Dark Cyan 5 Light Purple 5 Middle Grey 6 Dark Green 6 Light Green 7 Dark Blue 7 Light Blue 8 Light Yellow 8 Light Grey Colors in 80-Column Format 3.3.5 Using the Cursor Keys Inside Quotes with the PRINT Command When you type the cursor keys inside quotation marks, graphic characters are shown on the screen to represent the keys. These characters will NOT be printed on the screen when you press {return}. Try typing a question mark ({?}), open quotes ({shift}ed {2} key); then press either of the down cursor keys 10 times, enter the words "DOWN HERE", and close the quotes. The line should look like this: ?"QQQQQQQQQQDOWN HERE" Now press {return}. The Commodore 128 prints 10 blank lines, and on the eleventh line, it prints "DOWN HERE". As this example shows, you can tell the computer to print anywhere on your screen by using the cursor control keys inside quotation marks. 3.4 BEGINNING TO PROGRAM So far most of the commands we have discussed have been performed in DIRECT mode. That is, the command was executed as soon as the {return} key was pressed. However, most BASIC commands and functions can also be used in programs. 3.4.1 What a Program Is A program is just a set of numbered BASIC instructions that tell your com- puter what you want it to do. These numbered instructions are referred to as statements or lines. 3.4.2 Line Numbers The lines of a progam are numbered so that the computer knows in what order yo want them executed or RUN. The computer executes the program lines in numerical order, unless the program instructs otherwise. You can use any whole number from 0 to 63999 for a line number. Never use a comma in a line number. Many of the commands you have learned to use in DIRECT mode can easily be made into program statements. For example, type this: 10 ?"COMMODORE 128" {return} Notice the computer did not display COMMODORE 128 when you pressed {return}, as it would do if you were using the PRINT command in DIRECT mode. This is because the number, 10, that comes before the PRINT symbol (?) tells the computer that you are entering a BASIC program. The computer just stores the numbered statement and waits for the next input from you. Now type RUN and press {return}. The computer prints the words COMMODORE 128. This not the same as using the PRINT command in DIRECT mode. What has happened here is that YOU HAVE WRITTEN AND RUN YOUR FIRST BASIC PROGRAM as small as it may seem. The program is still in the computer's memory, so you can run it as many times as you want. 3.4.3 Viewing your Program - The LIST Command Your one-line program is still in the C128 memory. Now clear the screen by pressing the {shift} and {clr/home} keys together. The screen is empty. At this point you may want to see the program listing to be sure it is still in memory. The BASIC language is equipped with a command that lets you do just this - the LIST command. Type LIST and press {return}. The Commodore 128 responds with: 10 PRINT "COMMODORE 128" READY. Anytime you want to see all the lines in your program, type LIST. This is especially helpful if you make changes, because you can check to be sure the new lines have been registered in the computer's memory. In response to the command, the computer displays the changed version of the line, lines, or program. Here are the rules for using the LIST command: - To see line n only, type LIST n and press {return}. - To see from line n to the end of the program, type LIST n- and press {return}. - To see the lines from the beginning of the program to line n, type LIST -n and press {return}. - To see from line n1 to line n2 inclusive, type LIST n1-n2 and press {return}. 3.4.4 A Simple Loop - The GOTO Command The line numbers in a program have another purpose besides putting your commands in the proper order for the computer. The serve as a reference for the computer in case you want to execute the command in that line repeti- tively in your program. You use the GOTO command to tell the computer to go to a line and execute the command(s) in it. Now type: 20 GOTO 10 When you press {return} after typing line 20, you add it to your program in the computer's memory. Notice that we numbered the first line 10 and the second line 20. It is very helpful to number program lines in increments of 10 (that is 10, 20, 30, 40, etc.) in case you want to go back and add lines in between. You can number such added lines by fives (15, 25...), or ones (1, 2...) - in fact, by any whole number - to keep the lines in proper order. (See the RENUMBER and AUTO commands in the BASIC Encyclopaedia, paragraphs.) Type RUN and press {return}, and watch the words COMMODORE 128 move down your screen. To stop the message from printing on the screen, press the {run/stop} key on the left side of the main keyboard. The two lines that you have typed make up a simple program that repeats it- self endlessly, because the second line keeps referring the computer back to the first line. The program will continue indefinitely unless you stop it or turn off the computer. Now type LIST {return} The screen should say: 10 PRINT "COMMODORE 128" 20 GOTO 10 READY. Your program is still in memory. You can RUN it again if you want to. This is an important difference between PROGRAM mode and DIRECT mode. Once a command is executed in DIRECT mode, it is no longer in the computer's memory. Notice that even though you used the ? symbol for the PRINT state- ment, your computer has converted it into the full command. This happens when you LIST any command you have abbreviated in a program. 3.4.5 Clearing the Computer's Memory - The NEW Command Anytime you want to start all over again or erase a BASIC program in the computer's memory, just type NEW and press {return}. This command clears out the computer's BASIC memory, the area where programs are stored. 3.4.6 Using Color in a Program To select color within a program, you must include the color selection information within a PRINT statement. For example, clear your computer's memory by typing NEW and pressing {return}, the type the following, being sure to leave space between each letter: 10 PRINT " R A I N B O W" {return} Now type line 10 again, but this time hold down the {ctrl} key and press the (numeral) {1} key directly after entering the first set of quote marks. Release the {ctrl} key and type the {r}. Now hold down the {ctrl} again and press the {2} key. Release the {ctrl} key and type the {a}. Next hold down the {ctrl} again and press the {3} key. Continue this process until you have typed all the letters in the word RAINBOW and selected a color between each letter. Press the {shift} and the {2} keys to type a set of the clo- sing quotation marks and press the {return} key. Now type RUN and press the {return} key. The computer displays the word RAINBOW with each letter in a different color. Now type LIST and press the {return} key. Notice the graphic characters that appear in the PRINT statement in line 10. These characters tells the computer what color you want for each printed letter. Note that these graphic characters do not appear when the Commodore 128 PRINTs the word RAINBOW in different colors. The color selection characters, known as control characters, in the PRINT statement in line 10 tell the Commodore 128 to change colors. The computer then prints the characters that follow in the new color until another color selection character is encountered. While characters enclosed in quotation marks are usually PRINTed exactly as they appear, control characters are only displayed within a program LISTing. 3.5 EDITING YOUR PROGRAM The following paragraphs will help you to type in your programs and make corrections and additions to them. 3.5.1 Erasing a Line from a Program Use the LIST command to display the program you typed previously. Now type 10 and press {return}. You just erased line 10 from the program. LIST your program and see for yourself. If the old line 10 is still on the screen, move the cursor up so that it is blinking anywhere on that line. Now, if you press {return}, line 10 is back in the computer's memory. 3.5.2 Duplicating a Line Hold down the {shift} key and press the {clr/home} key on the upper right side of the main keyboard. This will clear your screen. Now LIST the pro- gram. Move the cursor up again so that it is blinking in the (numeral) "0" in the line numbered 10. Now type a {5} and press {return}. You have just duplicated (i.e. copied) line 10. The duplicated line is numbered 15. Type LIST and press RETURN to see the program with the duplicated line. 3.5.3 Replacing a Line You can replace a whole line by typing in the old line number followed by the text of the new line, the pressing {return}. The old version of the line will be erased from memory and replaced by the new line as soon as you press {return}. 3.5.4 Changing a Line Suppose you want to add something in the middle of a line. Simply move the cursor to the character or space that immediately follows the spot where you want to insert the new material. Then hold down the {shift} key and the {inst/del} key together until there is enough space to insert your new characters. Try this example. Clear the computer's memory by typing NEW and pressing {return}. The type: 10 ? "MY 128 IS GREAT" {return} Let's say you want to add the word COMMODORE in front of the number 128. Just move the cursor so that it is blinking on the "1" in 128. Hold down the {shift} and {inst/del} keys until you have enough room to type in COMMODORE (don't forget to leave enough room for a space after the last letter "E"). Then type in the word COMMODORE. 3.6 MATHEMATICAL OPERATIONS You can use the PRINT command to perform calculations like addition, sub- traction, multiplication, division and exponentiation. You type the calcu- lation after the PRINT command. 3.6.1 Addition and Subtraction Try typing these examples: PRINT 6 + 4 {return} PRINT 50 - 20 {return} PRINT 10 + 15 - 5 {return} PRINT 75 - 100 {return} PRINT 30 + 40,55 - 25 {return} PRINT 30 + 40;55 - 25 {return} Notice that the fourth calculation (75-100) resulted in a negative number. Also notice that you can tell the computer to make more than one calcula- tion with a single PRINT command. You can use either a comma or semicolon in your command, depending on whether or not you want your results printed tabulated or next to each other. 3.6.2 Multiplication and Division Find the asterisk key (*) on the right side of the main keyboard. This is the symbol that the Commodore 128 uses for multiplication. The slash (/) key, located next to the right {shift} key, is used for division. Try these examples: PRINT 5*3 {return} PRINT 100/2 {return} 3.6.3 Exponentiation Exponentiation means to raise a number to a power. The up arrow key ({up arrow}, located next to the asterisk on the main keyboard, is used for exponentiation. If you want to raise a number to a power, use the PRINT command, followed by the number, the up arrow and the power, in that order. For example, to find out what 3 squared is, type: PRINT 3{up arrow}2 {return} NOTE: From now on, the {up arrow} keystroke is represented by the {^} key- stroke, or simply ^. 3.6.4 Order of Operations You have seen how you can combine addition and subtraction in the same PRINT command. If you combine multiplication or division with addition or subtraction operations, you may not get the result you expect. For example, type: PRINT 4 + 6/2 {return} If you assumed you were dividing 10 by 2, you were probably surprised when the computer responded with the answer 7. The reason you got this answer is that multiplication and division operations are performed by the computer before addition or subtraction. Multiplication and division are said to take precedence over addition and subtraction. It doesn't matter in what order you type the operation. In computing, the order in which mathematical operations are performed is known as the order of operations. Exponentiation, or raising a number to a power, takes precedence over the other four mathematical operations. For example, if you type: PRINT 16/4^2 {return} the Commodore 128 responds with 1, because it squares the 4 before it divides 16. 3.6.5 Using Parentheses to Define the Order of Operations You can tell the Commodore 128 which mathematical operation you want per- formed first by enclosing that operation in parentheses in the PRINT command. For instance, in the first example above, if you want to tell the computer to add before dividing, type: PRINT (4 + 6)/2 {return} This gives you the desired answer, 5. If you want the computer to divide before squaring in the second example, type: PRINT (16/4)^2 {return} Now you have the expected answer, 16. If you don't use parentheses, the computer performs the calculations accor- ding to the above rules. When all operations in a calculation have equal precedence, they are performed from left to right. For example, type: PRINT 4*5/10*6 {return} Since the operations in this example are performed in order from left to right, the result is 12 (4*5 = 20... 20/10 = 2... 2*6 = 12). If you want to divide 4*5 by 10*6 you type: PRINT (4*5)/(10*6) {return} The answer is now .333333333. 3.7 CONSTANTS, VARIABLES AND STRINGS 3.7.1 Constants Constants are numeric values that are permanent: that is, they do not change in value over the course of an equation or program. For example, the number 3 is a constant, as is any number. This statement illustrates how your program uses constants: 10 PRINT 3 No matter how many times you execute this line, the answer will always be 3. 3.7.2 Variables Variables are values that can change over the course of an equation or program statement. There is a part of the computer's BASIC memory that is reserved for the characters (number, letters and symbols) you use in your program. Think of this memory as a number of storage compartments in the computer that store information about your program; this part of the com- puter's memory is referred to as variable storage. Type in this program: 10 X=5 20 ?X Now RUN the program and see how the computer prints a 5 on your screen. You told the computer in line 10 that the letter X will represent the number 5 for the remaninder of the program. The letter X is called a variable, be- cause the value of X varies depending on the value to the right of the equals sign. We call this an assignment statement because now there is a storage compartment labeled X in the computer's memory, and the number 5 has been assigned to it. The = sign tells the computer that whatever comes to the right of it will be assigned to a storage compartment (a memory location) labeled with the letter X to the left of the equals sign. The variable name on the left side of the = sign can be either one or two letters, or one letter and one number (the letter MUST come first). The names can be longer, but the computer only looks at the first two charac- ters. This means the names PA and PART would refer to the same storage compartment. Also, the words used for BASIC commands (LOAD, RUN, LIST, etc.) or functions (INT, ABS, SQR, etc.) cannot be used as names in your programs. Refer to the BASIC Encyclopaedia in Chapter V if you have any questions about whether a variable name is a BASIC keyword. Notice that the = in assigment statements is not the same as the mathematical symbol meaning "equals", but rather means allocate a variable (storage compart- ment) and assign a value to it. In the sample program you just typed, the value of the variable X remains at 5 throughout. You can put calculations to the right of the = sign to assign the result to a variable. You can mix text with constants in a PRINT statement to identify them. Type NEW and press {return} to clear the Commo- dore 128's memory; then try this program: 10 A = 3*100 20 B = 3*200 30 ?"A IS EQUAL TO"A 40 ?"B IS EQUAL TO"B Now there are two variables, labeled A and B, in the computer's memory, containing the numbers 300 and 600 respectively. If, later in the program, you want to change the value of a variable, just put another assignment statement in the program. Add these lines to the program above and RUN it again. 50 A = 900*30/10 60 B = 95 + 32 + 128 70 GOTO 30 You'll have to press the {stop} key to halt the program. Now LIST the program and trace the steps taken by the computer. First, it assigns the value to the right of the = sign in line 10 to the letter A. It does the same thing in line 20 for the letter B. Next, it prints the messa- ges in lines 30 and 40 that give you the values of A and B. Finally, it assigns new values to A and B in lines 50 and 60. The old values are repla- ced and cannot be recovered unless the computer executes lines 10 and 20 again. When the computer is sent to line 30 to begin printing the values of A and B again, it prints the new values calculated in lines 50 and 60. Lines 50 and 60 reassign the same values to A and B and line 70 sends the computer back to line 30. This is called an endless loop, because lines 30 through 70 are executed over and over again until you press the {run/stop} key to halt the program. Other methods of looping are discussed later in this and following two sections. 3.7.3 Strings A string is a character or group of characters enclosed in quotes. These characters are stored in the computer's memory as a variable in much the same way numeric variables are stored. You can also use variable names to represent strings, just as you use them to represent numbers. When you put the dollar sign ($) after the variable name, it tells the computer that the name is for a string variable, and not a numeric variable. Type NEW and press {return} to clear your computer's memory, then type in the program below: 10 A$ = "COMMODORE" 20 X = 128 30 B$ = "COMPUTER" 40 Y = 1 50 ? "THE "A$;X;B$" IS NUMBER"Y See how you can print numeric and string variables in the same statement? Try experimenting with variables in your own short programs. You can print the value of a variable in DIRECT mode, after the program has been RUN. Type ?A$;B$;X;Y {return} after running the program above and see that those four variable values are still in the computer's memory. If you want to clear this area of BASIC memory but still leave your program intact, use the CLR command. Just type CLR {return} and all constants, variables and strings are erased. But when you type LIST, you can see the program is still in memory. The NEW command discussed earlier erases both the program and the variables. 3.8 SAMPLE PROGRAM Here is a sample program incorporating many of the techniques and commands discussed in the section. This program calculates the avarage of three numbers (X, Y and Z) and prints their values and their avarages on the screen. You can edit the pro- gram and change the calculations in line 10 through 30 to change the values of the variables. Line 40 adds the variables and divides them by 3 to get the average. Note the use of parentheses to tell the computer to add the numbers before it divides. TIP: Whenever you are using more than one set of parentheses in a statement, it's a good idea to count the number of left parentheses and right parentheses to make sure they are equal. 10 X = 46 20 Y = 73 30 Z = 114 40 A = (X + Y + Z)/3 50 ?"THE AVERAGE OF"X;Y;"AND"Z;"IS"A; 60 END 3.9 STORING AND REUSING YOUR PROGRAMS Once you have created your program, you will probably want to store it permanently so you will be able to recall and use it at some later time. To do this, you'll need either a Commodore disk drive or the Commodore 1530 (or 1531) Datassette, or similar storing device. You will learn several commands that let you communicate between your com- puter and your disk drive or Datassette. These commands are structured with the use of a command word followed by several parameters. Parameters are letters, words or symbols in a command that supply specific information to the computer, such as a filename, or a numeric variable that specifies a device number. Each command may have several parameters. For example, the parameter of the disk format command include a name for the disk and an identifying number or code, plus several other parameters. Parameters are used in almost every BASIC command; some are variables which change and others are constant. These are the parameters that supply disk information to the C128 and the disk drive: 3.9.0.1 Disk Handling Parameters disk name - arbitrary 16 character identifying name you supply. filename - arbitrary 16 character identifying name you supply. i.d. number - arbitrary two-character identifying code you supply. drive number - must use 0 for a single disk drive, 0 or 1 in a dual disk drive. device number - a preassigned number for a peripheral device. For example, the device number for a Commodore disk drive is 8. 3.9.1 Formatting a Disk - The HEADER Command To store programs on a new (or blank) disk, you must first prepare the disk to receive data. This is called "formatting" the disk. NOTE: Make sure you turn on the disk drive before inserting any disk. The formatting process divides the disk into sections called tracks and sectors. A table of contents, called a directory, is created. Each time you store a program on disk, the name you assign to that program will be added to the directory. The Commodore 128 has two kinds of formatting commands. One can be used in C128 mode only, and one can be used in both C64 and C128 mode. The follo- wing describes the C128 mode formatting command only. See your disk drive manual for the disk handling in C64 mode. The command that formats a diskette is called the HEADER command. It has a long form and a short form. To format a blank (new) disk, you MUST use the long form as follows: HEADER "diskname", Ii.d. [,Ddrive number] [,[ON]Udevice number] After the word HEADER, you type a name of your choice for the disk, within quotes. You can choose any name with up to 16 characters. You should choose disk names that help you identify what will be stored on the disk. Follow the diskname with a comma and the letter "I". Now a two character i.d. Your disk i.d. does not have to be numbers; you can also choose let- ters. You may want to develop a consecutive coding system for your disk, such as A1, A2, B1, B2. If you have one single disk drive, just press {return} at this point since the Commodore 128 automatically assumes the drive number is 0 and the device number is 8. You can specify these parameters if you have more than one drive or a dual drive. The next parameter in the command selects the drive number. Press the {d} key and if you have a single disk drive, press the {zero} key followed by a {comma}. Dual drives are labeled 0 and 1. The device number parameter starts with the letter U so press the {u} key followed by the preassigned device number for a Commodore disk drive which is {8}. Here is an example of the long form of the HEADER command: HEADER"RECS",IA1,D0,U8 {return} This command formats the diskette, calling it "RECS", the i.d. number "A1", on drive 0, unit 8. The default values for disk drive (0) and device number (8) will be used if none are supplied. This is an acceptable long form of the HEADER command: HEADER "MYDISK",I51 {return} The HEADER command can also be used to erase all data from a used disk, so the disk can be reused as if it were a brand new disk. Be careful that you don't erase a disk that contains data you may want someday. The quick form of the HEADER command can be used if the disk was previously formatted with the long form of the HEADER command. The quick form clears the directory, erasing all data in the same way as the long form, but keeps the same i.d. as was previously used. Here is what the quick HEADER might look like: HEADER "NEWPROGS" {return} 3.9.2 SAVEing on Disk In C128 mode, you can store you program on disk by using either of the following commands: DSAVE "program name" {return} SAVE "program name",8 {return} Either command can be used. Remember that the character sequence DSAVE" can be displayed on the screen by pressing the function key labeled {f5}, or you can type the sequence yourself. The progam name can be any name you choose, up to 16 characters long. Be sure to enclose the program name in quotes. You cannot put two programs with the same name on the same disk. If you do, the second program will not be accepted; the disk will retain the first one. In the second example, the 8 indicates that you are saving your program on device number 8. You do not need the 8 with DSAVE, because the computer automatically assumes you are using device number 8. 3.9.3 SAVEing on Cassette If you are using a Datassette to store your program, insert a blank tape in the recorder, rewind the tape if necessary, and type: SAVE "program name" {return} You must type the word SAVE, followed by the program name. The program name can be any name you choose up to 16 characters. NOTE: The 40-column screen will go blank while the program is being SAVEd, but returns to normal when the process is completed. Unlike disk, you can save two programs to tape under the same name. However when you load it back into the computer, the first progam sequentially on the tape will be loaded, so avoid giving programs the same name. Once a program has been SAVEd, you can LOAD it back into the computer's memory and RUN it anytime you wish. 3.9.4 LOADing from Disk Loading a program simply copies the contents of the program from the disk into the computer's memory. If a BASIC program was already in memory before you issued the LOAD command, it is erased. To load your BASIC program from a disk, use either ot the following com- mands in C128 mode: DLOAD "program name" {return} LOAD "program name",8 {return} Remember, in C128 mode you can use the {f2} function key (which you acti- vate by pressing {shift} and {f1} together) to display the sequence DLOAD", or you can type the letters yourself. In the second example, the 8 indi- cates to the computer that you are loading from device number 8. Again, like DSAVE, DLOAD assumes the disk drive device number is 8. Be careful to type the program name exactly as you typed it when SAVEing the program, or the computer will respond FILE NOT FOUND. Once the program is loaded, type RUN to execute. The Commodore 128 has a special form of the RUN command used to LOAD and RUN the program in C128 mode with one command. Type RUN, followed by the name of the program (also known as the filename) in quotes: RUN"MYPROG" {return} 3.9.5 LOADing from Cassette Tape To LOAD your program from cassette tape, type: LOAD "program name" {return} If you do not know the name of the program, you can type: LOAD {return} and the next program on tape will be found. While the Datassette is sear- ching for the program the 40 column screen is blank. When the program is found, the screen displays: FOUND PROGRAM NAME To actually load the program, you then press the Commodore key, or in 128 mode press the space bar to find the next program on tape. You can use the counter on the Datassette to identify the starting position of the programs. Then, when you want to retrieve a program, simple wind the tape forward from 000 to the program's start location, and type: LOAD {return} In this case you don't have to specify the program name; your program will load automatically because it is the next program on the tape. 3.9.6 Other Disk-Related Commands 3.9.6.1 Verifying a Program To verify that a program has been correctly saved, use the following com- mand in C128 mode: DVERIFY "program name" {return} If the program in the computer is identical to the one on the disk, the screen display will respond with the letters "OK". The VERIFY command also works for tape programs. You type: VERIFY "program name" {return} You do not enter the comma and a device number. 3.9.6.2 Displaying Your Disk Directory In C128 mode, you can see a list or directory of the programs on your disk by using the following command: DIRECTORY {return} This lists the contents of the directory. The easy way is to press the {f3} function key. When you press {f3}, the C128 displays the word DIRECTORY and performs the command. For further information on SAVEing and LOADing your programs, or other disk related information refer to your Datassette or disk drive manual. Also consult the LOAD and SAVE command descriptions in the Chapter V, BASIC 7.0 Encyclopaedia. ********** You now know something about the BASIC language and some elementary pro- gramming concepts. The next section builds on these concepts, introducing additional commands, functions and techniques that you can use to program in BASIC. SECTION 4 4. Advanced Basic Programming 4.1 COMPUTER DECISIONS - The IF-THEN Statement 4.1.1 Using the Colon 4.2 LOOPS - The FOR-NEXT Command 4.2.1 Empty Loops - Inserting Delays in a Program 4.2.2 The STEP Command 4.3 INPUTTING DATA 4.3.1 The INPUT Command 4.3.1.1 Assigning a value to a variable 4.3.1.2 Prompt Messages 4.3.2 The GET Command 4.3.3 Sample Program 4.3.4 The READ-DATA Commands 4.3.5 The RESTORE Command 4.3.5.1 Assigning values to string variables 4.3.6 Using Arrays 4.3.6.1 Subscripted Variables 4.3.6.2 Dimensioning Arrays 4.3.6.3 Sample Program 4.4 PROGRAMMING SUBROUTINES 4.4.1 The GOSUB-RETURN Commands 4.4.2 The ON GOTO/GOSUB Commands 4.5 USING MEMORY LOCATION 4.5.1 Using PEEK and POKE for RAM Access 4.5.1.1 Using PEEK 4.5.1.2 Using POKE 4.6 BASIC FUNCTIONS 4.6.1 What is a Function? 4.6.2 The INTEGER Function (INT) 4.6.3 Generating Random Numbers - The RND Function 4.6.4 The ASC and CHR$ Functions 4.6.5 Converting Strings and Numbers 4.6.5.1 The VAL Function 4.6.5.2 The STR$ Function 4.6.6 The Square Root Function (SQR) 4.6.7 The Absolute Value Function (ABS) 4.7 THE STOP AND CONT (CONTINUE) COMMANDS This section describes how to use a number of powerful BASIC commands, functions and programming techniques that can be used in both C128 and C64 modes. These commands and functions allow you to program repeated actions through looping and nesting techniques; handle tables of values; branch or jump to another section of a program, and return from that section; assign varying values to a quantity - and more. Examples and sample programs show just how these BASIC concepts work and interact. 4.1 COMPUTER DECISIONS - The IF-THEN Statement Now you know how to change the values of variables, the next step is to have the computer make decisions based on these updated values. You do this with the IF-THEN statement. You tell the computer to execute a command only IF a condition is true (e.g. IF X=5). The command you want the computer to execute when the condi- tion is true comes after the word THEN in the statement. Clear your computer's memory by typing NEW and pressing {return}, then type in this program: 10 J=0 20 J=J+1 30 ? J,"COMMODORE 128" 40 IF J=5 THEN GOTO 60 50 GOTO 20 60 END You no longer have to press the {stop} key to break out of a looping pro- gram. The IF-THEN statement tells the computer to keep printing "COMMODORE 128" and incrementing (increasing) J until J=5 is true. When an IF condi- tion is false, the computer jumps to the next line of the program, no matter what comes after the word THEN. Notice the END command in line 60. It is good practice to put an END state- ment as the last line in your program. It tells the computer where to stop executing statements. Below is a list of comparison symbols that may be used in the IF statement and their meanings: SYMBOL MEANING = EQUALS > GREATER THAN <> NOT EQUAL TO >= GREATER THAN OR EQUAL TO <= LESS THAN OR EQUAL TO You should be aware that these comparisons work in expected mathematical ways with numbers. There are different ways to determine if one string is greater than, less than, or equal to another. You can learn about these "string handling" functions by referring to Chapter V, Basic 7.0 Encyclo- paedia. Section 5 describes some powerful extensions of the IF-THEN concept, con- sisting of the BASIC 7.0 commands BEGIN, BEND and ELSE. 4.1.1 Using the Colon A very useful tool in programming is the colon (:). You can use the colon to separate two (or more) BASIC commands on the same line. Statements after a colon on a line will be executed in order, from left to right. In one program line you can put as many statements you can fit into 160 characters, including the line number. This is equivalent to four full screen lines in 40-column format, and two full lines in 80-column format. This provides an excellent oppurtunity to take advantage of the THEN part of the IF-THEN statement. You can tell the computer to execute several com- mands when you IF statement is true. Clear the computer's memory and type in the following progam: 10 N=1 20 IF N<5 THEN PRINT N;"LESS THAN 5":GOTO 40 30 ? N;"GREATER THAN OR EQUAL TO 5" 40 END Now change line 10 to read N=20, and RUN the program again. Notice you can tell the computer to execute more than one statement when N is less than 5. You can put any statement(s) you want after the THEN command. Remember that the GOTO 40 will not be reached if N is true. Any command that should be followed whether or not the specified condition is met should appear on a separate line. 4.2 LOOPS - The FOR-NEXT Command In the program used for the IF-THEN example, we made the computer print COMMODORE five times by telling it to increase or "increment" the variable J by units of one, until the value of J equalled five; then we ended the program. There is a simpler way to do this in BASIC. We can use a FOR-NEXT loop, like this: 10 FOR J=1 TO 5 20 ?J,"COMMODORE 128" 30 NEXT J 40 END Type and RUN this program and compare the result with the result of the IF-THEN program - they are the same. In fact, the steps taken by the com- puter are almost identical for the two programs. The FOR-NEXT loop is a very powerful programming tool. You can specify the number of times the computer should repeat an action. Let's trace the computer's steps for the program above. First, the computer assigns a value of 1 to the variable J. The 5 in the FOR statement tells the computer to execute all statements between the FOR statement and the NEXT statement, until J is equal to 5. In this case there is just one statement - the PRINT statement. The computer first assigns 1 to J, it then goes on to execute the PRINT statement. When the computer reaches the NEXT J statement, J is incremented and compared with 5. If J has not exceeded 5 the computer loops back to the PRINT statement. After five executions of this loop the value of J exceeds 5, the program drops down to the statement that comes immediately after the NEXT statement and continues from there. In this case the following statement is the END statement, so the program stops. 4.2.1 Empty Loops - Inserting Delays in a Program Before you proceed any further, it will be helpful to understand about loops and some ways they are used to get the computer to do what you want. You can use a loop to slow down the computer (by now you have witnessed the speed with which the computer executes commands). See if you can predict what this program will do before you run it. 10 A$="COMMODORE 128" 20 FOR J=1 TO 20 30 PRINT 40 FOR K=1 TO 1500 50 NEXT K 60 PRINT A$ 70 NEXT J 80 END Did you get what you expected? The loop contained in line 40 and 50 tells the computer to count to 1500 before executing the remainder of the program. This is known as a delay loop and is often used. Because it is inside the main loop of the program, it is called a nested loop. Nested loops can be very useful when you want the computer to perform a number of tasks in a given order, and repeat the entire sequence of commands a certain number of times. Section 5 describes an advanced way to insert delays through the use of the new BASIC 7.0 command, SLEEP. 4.2.2 The STEP Command You can tell the computer to increment your counter by units (e.g. 10, 0.5 or any other number). You do this by using a STEP command with the FOR statement. For example, if you want the computer to count by tens to 1000, type: 10 FOR X=0 TO 1000 STEP 10 20 ? X 30 NEXT Notice that you do not need the X in the NEXT statement if you are only executing one loop at a time - this is discussed later in this section. Also, note that you do not have to increase (or "increment") your counter - you can decrease (or "decrement") it as well. For example, change line 10 in the program above to read: 10 FOR X=100 TO 0 STEP - 10 The computer will count backward from 100 to 0, in units of 10. If you don't use a STEP command with a FOR statement, the computer will automatically increment the counter by units of 1. The parts of the FOR-NEXT commands are: FOR - word used to indicate beginning of loop. X - counter variable; any number variable can be used. 1 - starting value; may be any number, positive, negative or zero. TO - connects starting value to ending value. 100 - ending value; may be any number, positive, negative or zero. STEP - indicates an increment other than 1 will be used. 2 - increment; can be any number, positive, negative or zero. Section 5 describes DO/LOOP, a new, more powerful BASIC 7.0 command to per- form a similar task to the STEP command. 4.3 INPUTTING DATA 4.3.1 The INPUT Command 4.3.1.1 Assigning a value to a variable Clear the computer's memory by typing NEW and pressing {return}, and then type and RUN this program: 10 K=10 20 FOR I=1 TO K 30 ?"COMMODORE 128" 40 NEXT In this program you can change the value of K in line 10 to make the com- puter execute the loop as many times as you want it to. You have to do this when you are typing in the program, before it is RUN. What if you wanted to be able to tell the computer how many times to execute the loop at the time the program is RUN? In other words, you want to be able to change the value of the variable K each time you run the program, without having to change to program itself. We call this the ability to interact with the computer. You can have the computer ask how many times you want it to execute the loop. To do this, use the INPUT command. For example, replace line 10 in the program with: 10 INPUT K Now when you RUN the program, the computer reponds with a ? to let you know it is waiting for you to enter what you want the value of K to be. Type 15 and press {return}. The computer will execute the loop 15 times. 4.3.1.2 Prompt Messages You can also make the computer print a message in an INPUT statement to tell you what variable it's waiting for. Replace line 10 with: 10 INPUT"PLEASE ENTER A VALUE FOR K";K Remember to enclose the message to be printed in quotes. This message is called a prompt. Also, notice that you must use a semicolon (;) between the ending quote marks of the prompt and the K. You may put any message you want in the prompt, but the INPUT statement must be 160 characters or less, just as any BASIC command must. The INPUT statement can also be used with string variables. The same rules that apply for numeric variables apply for strings. Don't forget to use the {$} to identify all you string variables. Clear you computer's memory by typing NEW and pressing {return}. Then type this program. 10 INPUT"WHAT IS YOUR NAME";NM$ 20 ? "HELLO ";N$ Now RUN the program. When the computer prompts "WHAT IS YOUR NAME?", then type your name. Don't forget to press {return} after you type your name. Once the value of a variable (numeric or string) has been inserted into a program through the use of INPUT, you can refer to it by its variable name any time in the program. Type ?N$ {return} - your computer remembers your name! 4.3.2 The GET Command There are other BASIC commands you can use in your program to interact with the computer. One is the GET command and is similar to INPUT. To see how the GET command works, clear the computer's memory and type this program: 10 GET A$ 20 IF A$="" THEN 10 30 ? A$ 40 END When you type RUN and press {return}, nothing seems to happen. The reason is that the computer is waiting for you to press a key. The GET command, in effect, tells the computer to check the keyboard and find out what character or key is being pressed. The computer is satisfied with a null character (that is, no character). This is the reason for line 20. This line tells the computer that if it gets a null character, indicated by double quotes with no space in between them, it should go back to line 10 and try to GET another character. This loop continues until you press a key. The computer then assigns the character on that key to A$. The GET command is very important because you can use it, in effect, to program a key on your keyboard. The example below prints a message on the screen when {q} is pressed. Type the program and RUN it. The press {q} and see what happens. 10 ?"PRESS Q TO VIEW MESSAGE" 20 GET A$ 30 IF A$="" THEN 20 40 IF A$="Q" THEN 60 50 GOTO 20 60 FOR I=1 TO 25 70 ? "NOW I CAN USE THE GET STATEMENT" 80 NEXT 90 END Notice that if you try to press any key other than the {q}, the computer will not display the message, but will go back to line 20 to GET another character. Section 5 describes how to use the GETKEY statement, which is a new and more powerful BASIC 7.0 command that can be used to perform a similar task. 4.3.3 Sample Program Now that you know how to use the FOR-NEXT loop and the INPUT command, clear the computer's memory by typing NEW {return}, then type the following program: 10 T=0 20 INPUT"HOW MANY NUMBERS";N 30 FOR J=1 TO N 40 INPUT"PLEASE ENTER A NUMBER";X 50 T=T+X 60 NEXT 70 A=T/N 80 PRINT 90 ? "YOU HAVE";N"NUMBERS TOTALING "T 100 ? "AVERAGE = ";A 110 END This program lets you tell the computer how many numbers you want to ave- rage. You can change the numbers every time you run the program without having to change the program itself. Let's see what the program does, line by line: Line 10 assigns a value of 0 to T (which will be the running total of the numbers). Line 20 lets you determine how many numbers to average, stored in variable N. Line 30 tells the computer to execute a loop N times. Line 40 lets you type in the actual numbers to be averaged. Line 50 adds each number to the running total. Line 60 tells the computer to increment the counter (J) and loop back to line 30 while the counter (J) <= N. Line 70 divides the total by the amount of numbers you typed in (N) after the loop has been executed N times. Line 80 prints a blank line on the screen. Line 90 prints the message that gives you the amount of numbers and their total. Line 100 prints the average of the numbers. Line 110 tells the computer that your progam is finished. 4.3.4 The READ-DATA Commands There is another powerful way to tell the computer what numbers or charac- ters to use in your program. You can use the READ statement in your program to tell the computer to get a number or character(s) from the DATA state- ment. For example, if you want the computer to find the average of five numbers, you can use the READ and DATA statements this way: 10 T=0 20 FOR J=1 TO 5 30 READ X 40 T=T+X 50 NEXT 60 A=T/5 70 ? "AVERAGE =";A 80 END 90 DATA 5,12,1,34,18 When you RUN the program, the computer will print AVERAGE = 14. The program uses the variable T to keep a running total, and calculates the average in the same way as the INPUT average program. The READ-DATA average program, however, finds the numbers to average on a DATA line. Notice line 30, READ X. The READ command tells the computer there must be a DATA statement in the program. It finds the DATA line, and uses the first number as the cur- rent value for the variable X. The next time through the loop the second number in the DATA statement will be used as the value for X, and so on. You can put any number you want in a DATA statement, but you cannot put calculations in a DATA statement. The DATA statement can be anywhere you want in the program - even after the END statement, or as the first program line. This is because the computer never really executes the DATA state- ment; it will just refer to it. Be sure to separate your data items with commas, but be sure not to put a comma between the word DATA and the first number in the list. If you have more than one DATA statement in your program, the computer will start READing from the first DATA statement in the program listing when the program is RUN. The computer uses a pointer to remind itself which piece of data it read last. After the computer reads the first number in the DATA statement, the pointer moves to the next number. When the computer comes to the READ statement again, it assigns the value the pointer indicates to the variable in the READ statement. You can use as many READ and DATA statement as you need in a program, but make sure there is enough data in the DATA statements for the computer to READ. Remove one of the numbers from the DATA statement in the last program and RUN it again. The computer responds with ?OUT OF DATA ERROR IN 30. What happened is that when the computer executed the loop for the fifth time, there was no data for it to read. That is what the error message is telling you. Putting too much into the DATA statement doesn't create a problem in this program, because the computer never realizes the extra data exists. 4.3.5 The RESTORE Command You can use the RESTORE command in a program to reset the data pointer to the first piece of data if you need to. Replace the END statement (line 80) in the program above with: 80 RESTORE and add: 85 GOTO 10 Now RUN the program. The program will run continuously using the same DATA statement. NOTE: If the computer gives you an OUT OF DATA error message, it is because you forgot to replace the number that you removed previously from the DATA statement, so the data is all used before the READ statement has been exe- cuted the specific number of times. 4.3.5.1 Assigning values to string variables You can use DATA statements to assign values to string variables. The same rules apply as for numeric data. Clear the computer's memory and type the following program: 10 FOR J=1 TO 3 20 READ A$ 30 ? A$ 40 NEXT 50 END 60 DATA COMMODORE,128,COMPUTER If the READ statement calls for a string variable, you can place letters or numbers in the DATA statement. Notice however, that since the computer is READing a string, numbers will be stored as a string of characters, not as a value which can be manipulated. Numbers stored as strings can be printed, but not used in calculations. Also you cannot place letters in a DATA statement if the READ statement calls for a number variable. 4.3.6 Using Arrays You have seen how to use READ-DATA to provide many values for a variable. But what if you want the computer to remember all the data in the DATA statement instead of replacing the value of a variable with the new data? What if you want to be able to recall the third number, or the second string of characters? Each time you assign a new value to a variable, the computer erases the old value in the variable's box in memory and stores the new value in its place. You can tell the computer to reserve a row of boxes in memory and store every value that you assign to that variable in your program. This row of boxes is called an array. 4.3.6.1 Subscripted Variables If the array contains all of these values assigned to the variable X in the READ-DATA example, it is called the X array. The first value assigned to X in the program is called X(1), the second value is X(2), and so on. These are called subscripted variables. The numbers in the parentheses are called subscripts. You can use the value of a variable or the result of a calcu- lation as a subscript. The following is another version of the averaging program, this time using subscripted variables. 5 DIM X(5) 10 T=0 20 FOR J=1 TO 5 30 READ X(J) 40 T=T+X(J) 50 NEXT 60 A=T/5 70 ? "AVERAGE =";A 80 END 90 DATA 5,12,1,34,18 Notice there are not many changes. Line 5 is the only new statement. It tells the computer to set aside five boxes in memory for the X array. Line 30 has been changed so that each time the computer executes the loop, it assigns a value from the DATA statement to the position in the X array that corresponds to the loop counter (J). Line 40 calculates the total, just as it did before, but you must use a subscipted variable to do it. After you RUN the program, if you want to recall the third number, type: ?X(3) {return} The computer remembers every number in the array X. You can create string arrays to store the charachters in string variables the same way. Try updating the COMMODORE 128 COMPUTER READ-DATA program so the computer will remember the elements in the A$ array. 5 DIM A$(3) 10 FOR J=1 TO 3 20 READ A$(J) 30 ? A$(J) 40 NEXT 50 END 60 DATA COMMODORE,128,COMPUTER TIP: You do not need the DIM statement in your program unless the array you use has more than 10 elements, see the next paragraaf, Dimensioning Arrays. 4.3.6.2 Dimensioning Arrays Arrays can be used with nested loops, so the computer can handle data in a more advanced way. What if you had a large chart with 10 rows and 5 numbers in each row. Suppose you wanted to find the average of the five numbers in each row. You could create 10 arrays and have the computer calculate the average of the five numbers in each one. This is not necessary, because you can put all the numbers in a two-dimensional array. This array would have the same dimensions as the chart of numbers you want to work with - 10 rows by 5 columns. The DIM statement for this array (we will call it array X) should be: 10 DIM X(10,5) This tells the computer to reserve space in its memory for a two dimen- sional array named X. The computer reserves enough space for 50 numbers. You do not have to fill an array with as many numbers as you DIMensioned it for, but the computer will still reserve enough space for all the positions in the array. 4.3.6.3 Sample Program Now it becomes very easy to refer to any number in the chart by its column and row position. Refer to the chart below. Find the third element in the tenth row (1500). You would refer to this number as X(10,3) in your program. The following program reads the numbers from the chart into a two-dimen- sional array (X) and calculates the average of the numbers in each row. Column ----------+-------------------------------------------------- Row | 1 2 3 4 5 ----------+-------------------------------------------------- 1 | 1 3 5 7 9 2 | 2 4 6 8 10 3 | 5 10 15 20 25 4 | 10 20 30 40 50 5 | 20 40 60 80 100 6 | 30 60 90 120 150 7 | 40 80 120 160 180 8 | 50 100 150 200 250 9 | 100 200 300 400 500 10 | 500 1000 1500 2000 2500 10 DIM X(10,5), A(10) 20 FOR R=1 TO 10 30 T=0 40 FOR C=1 TO 5 50 READ X(R,C) 60 T=T+X(R,C) 70 NEXT C 80 A(R)=T/5 90 NEXT R 100 FOR R=1 TO 10 110 PRINT "ROW #";R 120 FOR C=1 TO 5 130 PRINT X(R,C) 140 NEXT C 150 PRINT "AVERAGE =";A(R) 160 FOR D=1 TO 1000:NEXT 170 NEXT R 180 DATA 1,3,5,7,9 190 DATA 2,4,6,8,10 200 DATA 5,10,15,20,25 210 DATA 10,20,30,40,50 220 DATA 20,40,60,80,100 230 DATA 30,60,90,120,150 240 DATA 40,80,120,160,200 250 DATA 50,100,150,200,250 260 DATA 100,200,300,400,500 270 DATA 500,1000,1500,2000,2500 280 END 4.4 PROGRAMMING SUBROUTINES 4.4.1 The GOSUB-RETURN Commands Until now, the only method you have had to tell the computer to jump to another part of your program is to use the GOTO command. What if you want the computer to jump to another part of the program, execute the statements in that section, then return to the point it left off and continue execu- ting the program? The part of program that the computer jumps to and executes is called a subroutine. Clear your computer's memory and enter the program below. 10 A$="SUBROUTINE":B$="PROGRAM" 20 FOR J=1 TO 5 30 INPUT "ENTER A NUMBER";X 40 GOSUB 100 50 PRINT B$:PRINT 60 NEXT 70 END 100 PRINT A$:PRINT 110 Z=X^2:PRINT Z 120 RETURN This program will square the numbers you type and print the result. The other print messages tell you when the computer is executing the subroutine or the main program. Line 40 tells the computer to jump to line 100, exe- cute it and the statements following it until it sees a RETURN command. The RETURN statement tells the computer to go back in the program to the line immediately following the GOSUB command and continue executing. The subrou- tine can be anywhere in the program - including after the END statement. Also, remember that the GOSUB and RETURN commands must always be used to- gether in a program (like FOR-NEXT and IF-THEN), otherwise the computer will give an error message. 4.4.2 The ON GOTO/GOSUB Commands There is another way to make the computer jump to another section of your program (called branching). Using the ON statement, you can have the com- puter decide what part of the program to branch to, based on a calculation or keyboard input. The ON statement is used with either the GOTO or GOSUB-RETURN commands, depending on what you need the program to do. A variable or calculation should be after to ON command. After the GOTO or GOSUB command, there should be a list of line numbers. Type in the program below to see how the ON command works. 10 ?"ENTER A NUMBER BETWEEN ONE AND FIVE" 20 INPUT X 30 ON X GOSUB 100,200,300,400,500 40 END 100 ?"YOUR NUMBER WAS ONE":RETURN 200 ?"YOUR NUMBER WAS TWO":RETURN 300 ?"YOUR NUMBER WAS THREE":RETURN 400 ?"YOUR NUMBER WAS FOUR":RETURN 500 ?"YOUR NUMBER WAS FIVE":RETURN When the value of X is 1, the computer branches to the first line number in the list (100). When X is 2, the computer branches to the second number in the list (200), and so on. 4.5 USING MEMORY LOCATION 4.5.1 Using PEEK and POKE for RAM Access Each area of the computer's memory has a special function. For instance, there is a very large area to store your programs and the variables asso- ciated with them. This part of memory, called RAM, is cleared when you use the NEW command. Other areas are not as large, but they have very specia- lized functions. For instance, there is an area of memory locations that controls the music features of the computer. There are two BASIC keywords - PEEK and POKE - that you can use to access and manipulate the computer's memory. Use of the PEEK function and the POKE command can be a powerful programming device because the contents of the computer's memory locations determine exactly what the computer should be doing at a specific time. 4.5.1.1 Using PEEK PEEK can be used to make the computer tell you what value is being stored in a memory location (a memory location can store any value between 0 and 255). You can PEEK the value of any memory location (RAM or ROM) in DIRECT or PROGRAM mode. Type: P=PEEK(2594) {return} ? P {return} The computer assigns the value in memory location 2594 to the variable P when you press {return} after the first line. Then it prints the value when you press {return} after entering the ? P command. Memory location 2594 determines whether or not keys like the SPACEBAR and CRSR repeat when you hold them down. A 128 in location 2594 tells the computer to repeat these keys when you hold them down. Hold down the SPACEBAR and watch the cursor move across the screen. 4.5.1.2 Using POKE To change the value stored in a RAM location, use the POKE command. Type: POKE 2594,96 {return} The computer stores the value after the comma (i.e. 96) in the memory loca- tion before the comma (i.e. 2594). A 96 in memory location 2594 tells the computer not to repeat keys like the SPACEBAR and CRSR keys when you hold them down. Now hold down the SPACEBAR and watch the cursor. The cursor moves one position to the right, but it does not repeat. To return your computer to its normal state, type: POKE 2594,128 {return} You cannot alter the value of all the memory locations in the computer - the values in ROM can be read, but not changed. NOTE: These examples assume you are in bank 0. See also the descrip- tion of the BANK command in chapter V, BASIC 7.0 Encyclopaedia for details on banks. 4.6 BASIC FUNCTIONS 4.6.1 What is a Function? A function is a predefined operation of the BASIC language that generally provides you with a single value. When the function provides the value, it is said to "return" the value. For instance, the SQR (square) function is a mathematical function that returns the value of a specific number when it is raised to the second power - i.e., squared. There are two kinds of functions: Numeric - returns a result which is a single number. Numeric functions range from calculating mathematical values to specifying the numeric value of a memory location. String - returns a result which is a character. Following are descriptions of some of the more commonly used functions. For a complete list, see Section 18 of Chapter V, BASIC 7.0 Encyclopaedia. 4.6.2 The INTEGER Function (INT) What if you want to round off a number to the nearest integer? You'll need to use INT, the integer function. The INT function takes away everything after the decimal point. Try typing these examples: ? INT(4.25) {return} ? INT(4.75) {return} ? INT(SQR(50)) {return} If you want to round off to the nearest whole number, then the second example should return a value of 5. In fact, you should round up any number with a decimal above 0.5. To do this, you have to add 0.5 to the number before using the INT function. In this way, numbers with decimal portions equal to or above 0.5 will be increased by 1 before rounding down by the INT function. Try this: ? INT(4.75+0.5) {return} The computer added 0.5 to 0.75 before it executed the INT function, so that it rounded 5.25 down to 5 for the result. If you want to round off the result of a calculation, do this: ? INT((100/6)+0.5) {return} You can substitute any calculation for the division shown in the inner parenteses. What if you want to round off numbers to the nearest of 0.01? Instead of adding 0.5 to your number, add 0.005, then multiply by 100. Let's say you want to round 2.876 to the nearest 0.01. Using this method, you start with: ?(2.876 + 0.005)*100 {return} Now use the INT function to get rid of everything after the decimal point (which moves two places to the right when you multiply by 100). You are left with: ?INT((2.876 + 0.005)*100) {return} which gives you a value of 288. All that's left to do is divide by 100 to get the value of 2.88, which is the answer you want. Using this technique, you can round off calculations like the following to the nearest of 0.01: ?INT(((2.876+1.29+16.1-9.534) + 0.005)*100) {return} 4.6.3 Generating Random Numbers - The RND Function The RND function tells the computer to generate a random number. This can be useful in simulating games of chance, and in creating interesting graphics or music programs. All random (RND) numbers are nine digits, in decimal form, between the value 0.000000001 and 0.999999999. Type: ? RND(0) {return} Multiplying the randomly generated number by six makes the range of gene- rated numbers increase to greater than 0 and less than six. In order to in- clude 6 (and exclude zero) among the numbers generated, we add one to the result of RND(0)*6. This makes the range 1 10 R=(INT(RND(1)*6+1) 20 ? R 30 GOTO 10 Each number generated represents one toss of a die. To simulate a pair of dice, use two commands of this nature. Each number is generated separately, and the sum of the two numbers represents the total of the dice. 4.6.4 The ASC and CHR$ Functions Every character that the Commodore 128 can display (including graphic characters) has a number assigned to it. This number is called a character string code (CHR$) and there are 255 of them in the Commodore 128. There are two functions associated with this concept that are very useful. The first is the ASC function. Type: ? ASC(Q) {return} The computer responds with 81. 81 is the character string code for the {q} key. Substitute any key for {q} in the command above to find out the Com- modore ASCII code number for any character. The second function is the CHR$ function. Type: ? CHR$(81) {return} The computer responds with Q. In effect, the CHR$ function is the opposite of the ASC function. They both refer to the table of character string codes in the computer's memory. CHR$ values can be used to program function keys. See Section 5 for more information about the use of these functions. See Appendix E of this Guide for a listing of ASC and CHR$ codes. 4.6.5 Converting Strings and Numbers Sometimes you may need to perform calculations on numeric characters that are stored as string variables in your program. Other times, you may want to perform string operations on numbers. There are two BASIC functions you can use to convert your variables from numeric to string type and vice versa. 4.6.5.1 The VAL Function The VAL function returns a numeric value for a string argument. Clear the computer's memory and type in this program: 10 A$="64" 20 A=VAL(A$) 30 ? "THE VALUE OF ";A$;" IS";A 40 END 4.6.5.2 The STR$ Function The STR$ function returns the string representation of a numeric value. Clear the computer's memory and type this program: 10 A=65 20 A$=STR$(A) 30 ? A"IS THE VALUE OF ";A$ 4.6.6 The Square Root Function (SQR) The square root function is SQR. For example, to find the square root of 50, type: ? SQR(50) {return} You can find the square root of any positive number in this way. 4.6.7 The Absolute Value Function (ABS) The absolute value (ABS) is very useful in dealing with negative numbers. You can use this function to get the positive value of any number, positive or negative. Try these examples: ? ABS(-10) {return} ? ABS(5)"IS EQUAL TO"ABS(-5) {return} 4.7 THE STOP AND CONT (CONTINUE) COMMANDS You can make the computer stop a program, and resume running it when you are ready. The STOP command must be included in the program. You can put a STOP command anywhere you want to in a program. When the computer "breaks" from the program (that is, stops running the program), you can use DIRECT mode commands to find out exactly what is going on in the program. For example, you can find the value of a loop counter or other variable. This is a powerful device when you are "debugging" or fixing your program. Clear the computer's memory and type the progam below. 10 X=INT(SQR(630)) 20 Y=(.025*80)^2 30 X=INT(X*Y) 40 STOP 50 FOR J=0 TO Z STEP Y 60 ? "STOP AND CONTINUE" 70 NEXT 80 END Now RUN this program. The computer responds with BREAK IN 40. At this point, the computer has calculated the values of X, Y and Z. If you want to be able to figure out what the rest of the program is supposed to do, tell the computer to PRINT X;Y;Z. Often when you are debugging a large program (or a complex small one), you'll want to know the value of a variable at a certain point in the program. Once you have all the information you need, you can type CONT (for CONTinue) and press {return} assuming you have not editing anything on the screen. The computer then CONTinues with the program, starting with the statement after the STOP command. *************************************************************************** This section and the preceding one have been designed to familiarize you with the BASIC programming language and its capabilities. The remaining four sections of this chapter describe commands that are unique to Com- modore 128 mode. Some Commodore 128 mode commands provide capabilities that are not available in C64 mode. Other Commodore 128 mode commands let you do the same things as a certain C64 command, but more easily. The syntax for all Commodore 7.0 commands is given in Chapter V, BASIC 7.0 Encyclopaedia. SECTION 5 5. Some BASIC Commands and Keyboard Operations Unique to C128 5.1 INTRODUCTION 5.2 ADVANCED LOOPING 5.2.1 The DO/LOOP Statement 5.2.1.1 UNTIL 5.2.1.2 WHILE 5.2.1.3 EXIT 5.2.2 The ELSE Clause with IF-THEN 5.2.3 The BEGIN/BEND Sequence with IF-THEN 5.2.4 The SLEEP Command 5.3 FORMATTING OUTPUT 5.3.1 The PRINT USING Command 5.3.2 The PUDEF Command 5.4 SAMPLE PROGRAM 5.5 INPUTTING DATA WITH THE GETKEY COMMAND 5.6 PROGRAMMING AIDS 5.6.1 Entering Programs 5.6.1.1 AUTO 5.6.1.2 RENUMBER 5.6.1.3 DELETE 5.6.2 Identifying Problems in Your Programs 5.6.2.1 HELP 5.6.2.2 Error Trapping - The TRAP Command 5.6.2.3 Program Tracing - The TRON and TROFF Commands 5.7 WINDOWING 5.7.1 Using the WINDOW Command to Create a Window 5.7.2 Using the ESC Key to Create a Window 5.8 2 MHZ OPERATION 5.8.1 The FAST and SLOW Commands 5.9 KEYS UNIQUE TO C128 MODE 5.9.1 Function Keys 5.9.2 Redefining Function Keys 5.9.3 Other Keys Used in C128 Mode Only 5.9.3.1 HELP 5.9.3.2 NO SCROLL 5.9.3.3 CAPS LOCK 5.9.3.4 40/80 DISPLAY 5.9.3.5 ALT 5.9.3.6 TAB 5.9.3.7 LINE FEED 5.1 INTRODUCTION This section introduces you to some powerful BASIC commands and statements that you probably have not seen before, even if you are an experienced BASIC programmer. If you are familiar with programming in BASIC, you have probably encountered many situations in which you could have used these commands and statements. This section explains the concepts behind each command and gives examples of how to use each command in a program. (A com- plete list and an explanation of these commands and statements may be found in Chapter V, BASIC 7.0 Encyclopaedia.) This section also describes how to use the special keys that are available to you in C128 mode. 5.2 ADVANCED LOOPING 5.2.1 The DO/LOOP Statement The DO/LOOP statement provides more sophisticated ways to create a loop than do the GOTO, GOSUB or FOR/NEXT statements. The DO/LOOP statement com- bination brings to the BASIC language a very powerful and versatile tech- nique normally only available in structured programming languages. We discuss just a few possible uses of DO/LOOP in this explanation. If you want to create an infinite loop, you start with a DO statement, then enter the line or lines that specify the action you want the computer to perform. Then end with a LOOP statement like this: 100 DO 110 PRINT "REPETITION" 120 LOOP Press the {run/stop} key to stop the program. The directions following the DO statement are carried out until the program reaches the LOOP statement (line 120); control is then transferred back to the DO statement (line 100). Thus any statements in between DO and LOOP are performed indefinitely. 5.2.1.1 UNTIL Another useful technique is to combine the DO/LOOP with the UNTIL state- ment. The UNTIL statement sets up a condition that directs the loop. The loop will run continually unless the condition for UNTIL happens. 100 DO:INPUT "DO YOU LIKE YOUR COMPUTER";A$ 110 LOOP UNTIL A$="YES" 120 PRINT "THANK YOU" The DO/LOOP statement is often used to repeat an entire routine indefinite- ly in the body of a program, as in the following: 10 PRINT "PROGRAM CONTINUES UNTIL YOU TYPE 'QUIT'" 20 DO UNTIL A$="QUIT" 30 INPUT "DEGREES FAHRENHEIT";F 40 C=(5/9)*(F-32) 50 PRINT F;"DEGREES FAHRENHEIT EQUALS ";C;"DEGREES CELCIUS" 60 INPUT "AGAIN OR QUIT";A$ 70 LOOP 80 END Another use of DO/LOOP is as a counter, where the UNTIL statement is used to specify a certain number of repetitions. 10 N=2*2 20 PRINT"TWO DOUBLED EQUALS";N 30 DO UNTIL X=25 40 X=X+1 50 N=N*2 60 PRINT"DOUBLED";X+1;"TIMES...";N 70 LOOP 80 END Notice that if you leave the counter statement out (the UNTIL X=25 part in line 30), the number is doubled indefinitely until an OVERFLOW error occurs. 5.2.1.2 WHILE The WHILE statement works in a similar way to UNTIL, but the loop is re- peated only while the condition is in effect, such as in the reworking of the last brief program: 100 DO:INPUT "DO YOU LIKE YOUR COMPUTER";A$ 110 LOOP WHILE A<>"YES" 120 PRINT "THANK YOU" 5.2.1.3 EXIT An EXIT statement can be placed within the body of a DO/LOOP. When the EXIT statement is encountered, the program jumps to the next statement following the LOOP statement. 5.2.2 The ELSE Clause with IF-THEN The ELSE clause provides a way to tell the computer how to respond if the condition of the IF-THEN statement is false. Rather than continuing to the next program line, the computer will execute the command or branch to the program line mentioned in the ELSE clause. For example, if you wanted the computer to print the square of a number, you could use the ELSE clause like this: 10 INPUT "TYPE A NUMBER TO BE SQUARED";N 20 IF N<100 THEN PRINT N*N:ELSE 40 30 END 40 ?"NUMBER MUST BE < 100":GOTO 10 Notice that you must use a colon (:) between the IF-THEN statement and the ELSE clause. 5.2.3 The BEGIN/BEND Sequence with IF-THEN BASIC 7.0 allows you to take the IF-THEN condition one step further. The BEGIN/BEND sequence permits you to include a number of program lines to be executed if the IF condition is true, rather than one simple action or GOTO. The command is constructed like this: IF condition THEN BEGIN: (program lines): BEND:ELSE Be sure to place a colon (:) between BEGIN and any instruction to the com- puter, and again between the last command in the sequence and the word BEND. BEGIN/BEND can be used without an ELSE clause, or can be used fol- lowing the ELSE clause when only a single command follows THEN and multiple commands follow the ELSE clause (of course BEGIN/BEND can also be used both after THEN and ELSE). Try this program: 10 INPUT A 20 IF A<100 THEN BEGIN: ?"YOUR NUMBER WAS"A 30 SLEEP 2:REM DELAY 40 FOR X=1 TO A 50 ?"THIS IS AN EXAMPLE OF BEGIN/BEND" 60 NEXT X 70 ?"THAT'S ENOUGH":BEND:ELSE ?"TOO MANY" 80 END This program asks for a number from the user. IF the number is less than 100, the statement between the keywords BEGIN and BEND are performed, along with any statements on the same line as BEND (except for ELSE). The message "YOUR NUMBER WAS" n appears on the screen. Line 30 is a delay used to keep the message on the screen long enough so it can be read easily. Then a FOR/NEXT loop is used to display a message the number of times specified by the user. If the number is greater than or equal to 100, the part after the THEN condition is skipped, and part after the ELSE condition (printing "TOO MANY") is carried out. The ELSE keyword must be on the same line as BEND. 5.2.4 The SLEEP Command Note the use of the SLEEP command in line 30 of the program just discussed. SLEEP provides an easier, more accurate way of inserting and timing a delay in program operation. The format of the SLEEP command is: SLEEP n where n indicates the number of seconds (rounded down to a whole number of seconds), in the range of 0 to 65535, that you want the program to delay. In the command shown in line 30, the 2 specifies a delay of two seconds. 5.3 FORMATTING OUTPUT 5.3.1 The PRINT USING Command Suppose you were writing a sales program that calculated a dollar amount. Total sales divided by number of salespeople equals average sales. But per- forming this calculation might result in dollar amounts with four or five decimal places! You can format the result the computer prints so that only two decimal places are displayed. The command which performs this function is PRINT USING. PRINT USING lets you create a format for your output, using spaces, commas, decimal points and dollar signs. Hash marks (the {#} sign) are used to re- present spaces or characters in the displayed result. For example: PRINT USING "#$######.##";A tells the computer that when A is printed, it should be in the form given, with up to six places to the left of the decimal point, and two places to the right. The hash mark in front of the dollar sign indicates that the {$} should float, that is, it should always be placed next to the left-most number in the format. If you want a comma to appear before the last three dollar places (as in $1,000.00), include the comma in the PRINT USING statement. Remember you can format output with spaces, commas, decimal points, and dollar signs. There are several other special characters for PRINT USING, see paragraph 17.68 of the BASIC Encyclopaedia for more information. 5.3.2 The PUDEF Command If you want formatted output representing something other than dollars and cents, use the PUDEF (Print Using DEFine) command. You can replace any of four format characters with any character on the keyboard. The PUDEF command has four positions, but you do not have to redefine all four. The command looks like this: PUDEF " ,.$" 1234 Here: * position 1 is the filler character. A blank will appear if you do not redefine this position. * position 2 is the comma character. Default is the comma. * position 3 is the decimal point. * position 4 is the dollar sign. If you wrote a program that converted a dollar amount to English pounds, you could format the output with these commands: 10 PUDEF " ,.{pound}" 20 PRINT USING "#$####.##";X 5.4 SAMPLE PROGRAM This program calculates interest and loan payments, using some of the com- mands and statements you just learned. It sets a minimum value for the loan using the ELSE clause with an IF-THEN statement, and sets up a dollar and cents format with PRINT USING. 10 INPUT "LOAN AMOUNT IN DOLLARS";A 20 IF A<100 THEN 70:ELSE P=.15 30 I=A*P 40 ?"TOTAL PAYMENT EQUALS"; 50 PRINT USING "#$#####.##";A+1 60 GOTO 80 70 ?"LOANS UNDER $100 ARE NOT AVAILABLE" 80 END 5.5 INPUTTING DATA WITH THE GETKEY COMMAND You have learned to use the INPUT and GET commands to enter DATA during a program. Another way for you to enter data while a program is being RUN is with the GETKEY statement. The GETKEY statement accepts only one key at a time. GETKEY is usually followed by a string variable (A$ for example). Any key that is pressed is assigned to that string variable. GETKEY is useful because it allows you to enter data one character at a time without having to press the RETURN key after each character. The GETKEY statement may only be used in a program. Here is an example of using GETKEY in a program: 1000 PRINT "PLEASE CHOOSE A, B, C, D, E OR F" 1010 GETKEY K$ 1020 PRINT A$;" WAS THE KEY YOU PRESSED." The computer waits until a single key is pressed; when the key is pressed, the character is assigned to variable A$, and printed out in line 1020. The following program features the GETKEY in more complex and useful fashions: for answering multiple-choice question and also asking if the question should be repeated. If the answer given is incorrect, the user has the option to try again by pressing the {y} key (line 80). The key pressed for the multiple choice answer is assigned to variable A$ while the "TRY AGAIN" answer is assigned to B$, through the GETKEY statements in line 60 and 90. IF/THEN statements are used for loops in the program to get the proper computer reaction to the different keyboard inputs. 10 PRINT "WHO WROTE 'THE RAVEN'?" 20 PRINT "A. EDGAR ELLEN POE" 30 PRINT "B. EDGAR ALLEN POE" 40 PRINT "C. IGOR ALLEN POE" 50 PRINT "D. ROB RAVEN" 60 GETKEY A$ 70 IF A$="B" THEN 150 80 PRINT "WRONG. TRY AGAIN? (Y OR N)" 90 GETKEY B$ 100 IF B$="Y" THEN PRINT "A,B,C OR D": GOTO 60 110 IF B$="N" THEN 140 120 PRINT "TYPE EITHER Y OR N - TRY AGAIN" 130 GOTO 90 140 PRINT "THE CORRECT ANSWER IS B." 145 GOTO 160 150 PRINT "CORRECT!" 160 END GETKEY is very similar to GET, except GETKEY will wait for a key to be pressed. 5.6 PROGRAMMING AIDS In earlier sections you learned how to make changes in your programs, and correct typing mistakes with {inst/del}. BASIC also provides other commands and functions which help you locate actual programming errors, and commands which you can use to make programming sessions flow more smoothly. 5.6.1 Entering Programs 5.6.1.1 AUTO C128 BASIC provides an auto-numbering process. You determine the increment for the line numbers. Say you want to number your program in the usual man- ner, by tens. Before you begin to program, while in DIRECT mode, type: AUTO 10 {return} The computer automatically numbers your programs by tens. After you enter a line and press the {return} key, the next line number appears, and the cur- sor is in the correct place for you to type the next statement. You can choose to have the computer number the commands with any increment; you might choose 5 or even 50. Just place the number after the word AUTO and press {return}. To turn off the auto-numbering feature, type AUTO with no increment, and press {return}. 5.6.1.2 RENUMBER If you write a program and later add statements to it, sometimes the line numbering can be awkward. Using the RENUMBER command you can change the line numbers to an even increment for part or all of your program. The RENUMBER command has several optional parameters, as listed below in brackets: RENUMBER [new starting line] [,[increment] [,old starting line]] The new starting line is what the first program line wil be numbered after the RENUMBER command is used. If you do not specify, the default is 10. The increment is the spacing between line numbers, and it also defaults to 10. The old starting line number is the line number where the renumbering is to begin. This feature allows you to renumber a portion of your program, rather than all of it. It defaults to the first line of the program. For example: RENUMBER 40,,80 tells the computer to renumber the program starting at line 80, in incre- ments of 10. Line 80 becomes line 40. Notice that this command, like AUTO, can only be executed in DIRECT mode. 5.6.1.3 DELETE You know how to delete program lines by typing the line number and pressing the {return} key. This can be tedious if you want to erase an entire por- tion of your program. The DELETE command can save you time because you can specify a range of program lines to erase all at once. For example: DELETE 10-50 will erase line 10, 50, and any in between. The use of DELETE is similar to that of LIST, in that you can specify a range of lines up to a given line, or following it, or a single line only, as in these examples: DELETE -120 erases all lines up to and including 120 DELETE 120- erases line 120 and any line after it DELETE 120 erases line 120 only 5.6.2 Identifying Problems in Your Programs When a program does not work the way you expected, an error message usual- ly occurs. Sometimes the messages are vague, however, and you still do not understand the problem. The Commodore 128 computer has several ways of helping you locate the problem. 5.6.2.1 HELP The Commodore 128 provides a HELP command that specifies the line in which a problem has occurred. To actuate the HELP command, just press the special {help} key on the row of keys located above the main keyboard. Type the following statement. It contains an intentional error, so type it just as is: 10?3;4:5;6 When you RUN this one-line program, the computer prints 3 and 4 as expec- ted, but then responds ?SYNTAX ERROR IN 10. Suppose you cannot see the error (a colon instead of a semicolon between 4 and 5). You press the {help} key. (You can also type HELP and press {return}.) The computer dis- plays the line again, but the 5;6 is highlighted to show the error is in that part of the line: 10?3;4:5;6 5.6.2.2 Error Trapping - The TRAP Command Usually, if an error occurs in a program, the program "crashes" (stops run- ning). At that point, you can press the {help} key to track down the error. However, you can use the BASIC 7.0 TRAP command to include an error- trapping capability within your program. The TRAP command advises you to locate and correct an error, then resume program operation. Usually, the error trapping function is set in the first line of a program: 5 TRAP 100 tells the computer that if an error occurs to go to a certain line (in this case, line 100). Line 100 appears at the end of the program, and sets up a contingency. Neither line is executed UNLESS there is an error. When an error occurs, the line with the TRAP statement is enacted, and control is directed to another part of the program. You can uses these statements to catch anticipated errors in entering data, resume execution, or return to text mode from graphics mode, to name just a few options. If you run the last DO/LOOP example (with doubled numbers) without an UNTIL statement, you can get an OVERFLOW error and the program crashes. You can prevent that from happening by adding two lines, one at the beginning and one at the end. For example, you might add these two lines: 5 TRAP 100 100 IF N<1 THEN END Even though N has been much greater than one for the entire program, the statement is not considered until there is an error. When the number "overflows" (is greater than the computer can accept), the TRAP statement goes into effect. Since N is greater than one, the program is directed to END (rather than crashing). Here is an example in which trapping is used to prevent a zero from being input for division. 10 TRAP 1000 100 INPUT "I CAN DIVIDE BY ANY NUMBER, GIVE ME A NUMBER TO DIVIDE";D 110 INPUT "WHAT SHOULD I DIVIDE IT BY";B 120 A=D/B 130 PRINT D;"DIVIDED BY ";B;"EQUALS ";A 140 END 1000 IF B=0 THEN PRINT"EVEN I CAN'T DO THAT" 1100 INPUT "PICK A DIFFERENT NUMBER";B:RESUME 120 Notice the RESUME in line 1100. This tells the computer to return to the line mentioned (in this case, 120) and continue. Depending on the error that was trapped, resuming executing may or may not be possible. For additional information on error trapping, see the error functions ERR$ (paragraph 18.8), EL and ER (paragraph 19.1), described in Chapter V, BASIC 7.0 Encyclopaedia. 5.6.2.3 Program Tracing - The TRON and TROFF Commands When a problem in a program occurs, or you do not get the result you ex- pect, it can be useful to methodically work through the program and do exactly what the computer would do. This process is called tracing. Draw variable boxes and update the values according to the program statements. Perform calculations and print results following each instruction. (All done by hand, using the program listing as a guideline.) This kind of tracing may show you, for example, that you have used a GOTO with an incorect line number, or calculated a result but never stored it in a variable. Many program errors can be located by pretending to be the com- puter, and following only one instruction at a time. Your C128 can perform a type of trace using the special commands TRON and TROFF (short for TRace ON and TRace OFF). When the program is run, with TRace ON, the computer prints the line numbers in the order they are exe- cuted. In this way, you may be able to see why your program is not giving the results you expected. Type any short program we have used so far, or use one of your own design. To activate trace mode, type TRON in DIRECT mode. When you run the program, notice how line numbers appear in brackets before any results are dis- played. Try to follow the line numbers and see how many steps the computer needed to arrive at a certain point. TRON will be more interesting if you pick a program with many branches, such as GOTO, GOSUB and IF-THEN-line number. Type TROFF to turn trace mode off before continuing. You do not have to trace an entire program. You can place TRON within a program as a line prior to the program section causing problems. Put the word TROFF as a program line after the troublesome section. When you run the program, only the lines between TRON and TROFF will be bracketed in the results. 5.7 WINDOWING Windows are a specific area on the screen that you define as your work- space. Everything you type (lines you type, listings of programs, etc.) after setting a window, appears within the window's bounderies, not affec- ting the screen outside the window area. The Commodore 128 provides two methods of creating windows: the WINDOW command and {esc} key functions. 5.7.1 Using the WINDOW Command to Create a Window The Commodore 128 BASIC 7.0 language features a command that allows you to create and manipulate windows: the WINDOW command. The command format is: WINDOW top-left column, top-left row, bottom-right column, bottom-right row [,clear option] The first two numbers after WINDOW specify the column and row number of where you want the top left corner of the window to be; the next two num- bers are the coordinates for the bottom right corner. Remember that the screen format (40- or 80-columns) dictates the acceptable range of these coordinates. You can also include a clear option with this command. If you add 1 onto the end of the command, the window screen area is cleared, as in this example: WINDOW 10,10,20,20,1 Here's a sample program that creates four windows on the screen, in either 40- or 80-column format. 10 SCNCLR :REM CLEAR SCREEN 20 WINDOW 0,0,39,24 :REM SET WINDOW TO FULL SCREEN 30 COLOR 0,13:COLOR 4,13 :REM SET 40 SCREEN TO MED. GREY 40 A$="ABCDEFGHIJKLMNOPQRST" 50 COLOR 5,5 :REM SELECT PURPLE TEXT 60 FOR I=1 TO 25 :REM FILL SCREEN WITH CHARACTERS 70 PRINT A$;A$:NEXT I 80 WINDOW 1,1,7,20 :REM DEFINE WINDOW 1 90 COLOR 5,3 :REM SELECT RED TEXT 100 PRINT CHR$(18);A$; :REM PRINT A$ IN REVERSE RED TEXT 110 WINDOW 15,15,39,20,1 :REM DEFINE SECOND WINDOW 120 COLOR 5,7 :REM SELECT BLUE TEXT 130 FOR I=1 TO 6:PRINT A$;: NEXT :REM FILL WINDOW 2 WITH CHARACTERS 140 WINDOW 30,1,39,22,1 :REM DEFINE THIRD WINDOW 150 COLOR 5,8:LIST :REM LIST IN YELLOW TEXT 160 WINDOW 5,5,33,18,1 :REM DEFINE FOURTH WINDOW 170 COLOR 5,2 :REM SELECT WHITE TEXT 180 PRINT A$:LIST :REM PRINT A$ AND LIST IN WHITE TEXT 190 END 5.7.2 Using the ESC Key to Create a Window To set a window with the {esc} (Escape) key, follow these steps: 1. Move the cursor to the screen position you want as the top left corner of the window. 2. Press the {esc} key and release it, and then press {t}. 3. Move the cursor to the position you want to be the bottom right corner of the window. 4. Press {esc} and release, then {b}. Your window is now set. You can manipulate the window and the text inside using the {esc} key. Screen editing functions, such as inserting and deleting text, scrolling, and changing the size of the window, can be performed by pressing {esc} followed by another key. To use a specific function, press {esc} and re- lease it. Then press any of the following keys listed for the desired func- tion: @ Erase everything from cursor to end of screen window. A Automatic insert mode. B Set the bottom right corner of the screen window (at the current cursor location) C Cancel automatic insert mode. D Delete current line. E Set cursor to non-flashing mode. F Set cursor to flashing mode. G Enable bell (by {ctrl g}). H Disable bell. I Insert a line. J Move to the beginning of the current line. K Move to the end of the current line. L Turn on scrolling. M Turn off scrolling. N Return to normal (non-reverse video) screen display (80-column only). O Cancel insert and quote modes. P Erase everything from the beginning of the line to the cursor. Q Erase everything from the cursor to the end of the line. R Reverse screen display (80-column only). S Change to