4A TI-99 Ressources

This book is intended to help you operate your new TI-99/4A computer, get ...... you use a consultant, get one who is an independent without any connection to a ...
20MB taille 4 téléchargements 480 vues
w

w w

w w w

^

w

w

w

w

w

w w

The Elementary TI-99/4A

W

w

)

The Elementary TI-99/4A

by

William B. Sanders, Ph.D. San Diego State university

Illustrations by Martin cannon

L

IJDATAMOST 8943 Fullbnght Avenue Chatsworth, CA 91311 -2750

[213)709-1202

Siijjiijjjj/

HDATAMOST

Niaigii/

ISBN 0-88190-247-0

^/

This manual is published and copyrighted by DATAMOST Inc. Copying, duplicating, selling or otherwise distributing this product is hereby expressly forbidden except by prior written consent of DATAMOST Inc.

v*^

The word TI-99/4A and the TI logo are registered trademarks of Texas Instruments Inc.

^

Texas Instruments Inc.was not in any wayinvolved in the writing or other

^

preparation of this manual, nor were the facts presented here reviewed for accuracy by that company. Use of the term TI-99/4A should not be construed to represent an endorsement, official or otherwise, by Texas Instruments Inc. Copyright 1983 DATAMOST Inc.

VCisf"

ACKNOWLEDGEMENTS Several people helped directly or indirectly in the creation of ELEMENTARY TI-99/4A. First and foremost, I owe a great deal to Eric Goez. Eric taught me more about programming than anyone else; especially about the importance of good algorithms in programming. Having only 16K of RAM memory in the standard TI-99/4A, a good algorithm is indeed worth a thousand bytes of memory! Secondly, Bill Parker got across the point of structured programming to me better than anyone else ever has. Done correctly, structured program ming makes tasks easier, not more difficult. Finally, the folks

at Texas Instruments supplied me with all the necessary hardware and a good deal of software for preparing this book. Especially helpful was Jon Campbell of TI who took the time to make sure everything got to me on time and in the right place. Likewise, Texas Instruments was both helpful and patient in providing me with answers to several questions I asked. No one could have received better support, and I am grateful for theirs.

W

W

Dave Gordon of DATAMOST INC. provided a world of support for the book's production. Marcia Carrozzo edited the manuscript for style and consistency, making the work a good

deal clearer. She also had to learn about using the TI-99/4A to make sure that what was in the manuscript worked on the

^

computer. Also, Marcia's strong background in math was very helpful for improving many of the programs. Martin

^

Cannon did the art work in a way that communicated ideas

.

creatively and visually. He gave life to the notion that a picture is worth a thousand words. The rest of the staff at

(

t,

DATAMOST were equally helpful and friendly.

Finally, my wife Eli and sons Billy and David, and even our dog Cassiopeia, put up with the inconvenience of a writer in

^ ^ W

the house. To every one of these people I owe a debt of gratitude, but as in all such efforts, if anything goes wrong, it is only the author who is to blame. Therefore, while I happily give those who assisted credit, any of the book's shortcomings are the sole responsibility of the author.

TABLE OF CONTENTS Preface

w W

chapter 1 — introduction

9

11

Hardware

13

Software

14

Hooking Up Your TI-99/4A and Peripheral

^

Equipment

15

Power On!

23

Vj|gppf

Booting Disks LOADing and RUNning from Tape

26 30

w

TheTI-99/4A Keyboard

34

f

Summary

w i \ijSjg0/

w

Chapter 2 - Getting started Your Very First Command! Your Very First Program! Setting Up a Program Using Your Editor: Fixing Mistakes on the Run Elementary Math Operations Summary

Chapter 3 — Moving Along Variables

W W

W

Input and Output I/O Looping with FOR/NEXT Summary Chapter 4 — Branching Out Branching

37

38 38 40 41 48 54 57

59 59

67 75 80 81 82

Relational

86

W

Subroutines Computed GOTO and GOSUB

88 91

^

Arrays Summary

w

w ^

Chapter 5 — Organizing the Parts

96 103

104

Formatting Text Unraveling Strings String Formatting Setting Up Data Entry Setting Up Data Manipulation Organizing Output

104 107 107 117 119 122

Scroll Control

125

More PRINT Formatting

127

Summary

128

Chapter 6 — Some Advanced Topics

130

The ASCII Code and CHR$ Functions

131

^j

CALL Missiles and Music: CALL SOUND

134 143

w

Summary Chapter 7 — using Graphics Screen Graphics

149 151 151

w

Making Color

152

W

Bit Graphics Multiple Character Graphics Joystick Control

163 171 174

w

CALL GCHAR

179

Summary

181

Chapter 8 — Data and Text Files

182

Data Files and Your Cassette

182

OPEN, INPUT#, PRINT# and CLOSE Sequential Files and the Disk System Summary

184 191 198

Chapter 9 — You and Your Printer

200 •

w

Printing Text on Your Printer

202

CHR$ to the Rescue

204

w

Tab Stops on your Printer Printing Graphics Making Your Own Graphic Characters

209 212

^j

on the Printer

212

w

216 219 220

W

TI-99/4A User Groups

221

W

TI-99/4A Magazines

222

TI-99/4A Speaks Many Languages

223

Sort Routines

228

Printer Graphic Utilities Summary Chapter 10 — Program Hints and Help

Utility Programs

231

Word Processors

231

Data Base Programs Business Programs Graphics Packages

235 236 239

Hardware

240

Summary

241

TI-99/4A command Examples

243

index

253

^

\3gttS

PREFACE My first formal introduction to the workings of a computer was in 1966. At that time our wise mentor told us that if we

learned the lowest level operations of a computer, we would be set for life. As a result of this philosophy, we were taught how to do everything from counting in binary and conversion to octal to the essentials of FORTRAN. The problem was that we

W

never really sat down and programmed at a terminal. Sowhile we had a terrific theoretical understanding of the workings of

*w computers, we did not learn very much about actual program ming.

Since that time, both computers and the people who use them have changed. To learn how to use a computer, it is unnecessary to learn everything about how they work or the theory behind their operation. It is true that by having a detailed under standing of the theory and operation of computers one can do more with them, but it is something that does not have to be done at the outset. One can learn how to program, and at a

(^ later date learn the more technical details of a computer's operation. After all, most people learn to drive without know^/ ing the intricacies of the internal combustion engine of their automobile.

W

Another major change in computers has been in the transition from "mainframes" and "terminals" to small "individual"

W

^

computers. Your TI-99/4A is not merely a terminal; it is a whole computer. Therefore, you are not dependent on using a

piece of a larger computer, but you get the whole thing all to yourself. As a result, you are not subject to a set of policies and regulations for getting "on line" or paying for the time you use. You make your own policies and are the captain of your own computer ship. It is unnecessary to spend a lot of time dis cussing the organizational aspects of accessing the CPU (Cen tral Processing Unit), time-sharing, and so forth. We will go right to the heart of the matter, programmingYOUR computer.

The purpose of this book is primarily to teach you how to work your computer and program in the language called BASIC. It is ELEMENTAR Y. So, while you will learn a great deal, don't expect to learn everything about working with your TI-99/4A. Once you are finished with this book, you will realize how much more you can do with your computer, and the more you learn, the more you will find to learn. By following the instruc tions and keying in the examples, you will learn how to write programs with most of the instructions in the standard ver sion of BASIC on your TI-99/4A.

As a final note, don't expect to learn everything right away. Be patient with yourself and your computer and you will be amazed at how much you will learn. If you do not understand a command or a procedure, you can always come back to it later. Try different things and play with your pro grams. Think up different projects you would like your com puter to do and then try writing a program to do what you want By all means, do not be afraid to attempt anything. With each step or attempt you will make some progress. While it may be slow at times, the accumulated knowledge will even tually lead to understanding.

w

w

w w w

Vug/

w

10

w

CHAPTER 1

introduction Ni|gjft>

This book is intended to help you operate your new TI-99/4A

computer, get started programming and make life with your computer easier. It is not for professional programmers or more advanced applications. It is only the first step, and it is for BEGINNERS on the TI-99/4A computer. Everything will be kept on an introductory level but, by the time you are finished, you should be able to write and use programs.

Vims/

11 \^0

To best use ELEMENTARY TI-99/4A it is suggested that you start at the beginning and work your way through step-bystep. I have tried to arrange the book so that each part and sec tion logically follows the one preceding it. Skipping around might result in your not understanding some important aspect of the computer's operation. The only exception to this rule is the last chapter where I have put a number of suggestions for programs you might want to buy in order to help you write programs (called UTILITY PROGRAMS). Also, there are descriptions of programs for doing other things such as busi ness, word processing and so forth. When you're finished with this chapter, it would be a good idea to take a quick peek at some of the programs described in the last chapter to see if any of them fit your needs while you're learning about your TI-99/4A. You don't have to purchase any programs but, depending on your interests and needs, you will find some of them very useful.

yams/

12

Vilp/

W W

^

^

The first thing to learn about your computer is that it will not "bite" you. It requires a certain amount of care. There are ways you can destroy diskettes, tapes and information but, by following a few simple rules, you should be all right. All of us have used sophisticated electronic equipment, such as our stereos, televisions and video-tape recorders; there is a certain amount of care they require. Otherwise, there is no need to fear them. Likewise, your computer is electronic. If you pour water or other liquids on the computer while the power is on, you're likely to damage it. Using reasonable care, go ahead

andput it to use. Remember, it isvirtually impossible to write a program which will harm the hardware (or electronic cir cuits) in your machine. At worst, one of your programs might erase the information on a tape or diskette. Throughout this book there will be tips about how to do things the right and wrong way but, for the most part, treat your computer as you would your microwave oven, garage door opener or radio — with care but without fear.

W

At this stage of the game it is unnecessary to learn a lot of com puter jargon, but some of this jargon is necessary to help you understand how your computer operates. As we go on, more new terms will be introduced but in general the text will be

W plain English. Nevertheless, you should know the following just to get started:

HARDWARE

^ w W W

^

^

Hardware refers to the machine and all ofits electronicparts. Basically, everything from the keyboard to the wires and little black chips in your computer is considered "hardware." You will also hear the term, "firmware." This is another type of hardware on which programs are written. Called "proms" or "eproms," these chips have information stored in them just as tapes and disks do. Firmware is either inside your computer or in cartridges or boards you plug into your TI-99/4A. A biological analogy of hardware is the physical body, most importantly the brain, and firmware is a like inherent intelligence or

transplanted intelligence.

13 *tap/

SOFTWARE Software consists of the programs which tell the computer to do different things. Whatever goes into the computer's memory is software. It is analogous to the mind or ideas. Treating the hardware as the brain, any idea which goes into the hardware is the software. Software is to computers what records are to stereos. Software operates either in Random Access Memory (RAM) or Read Only Memory (ROM). (Firmware is hardware

Nigs/

with "burned in" software.)

w

RAM You may hear people talk about expanding their RAM. This is the part of the computer's memory into which you can enter information in the form of data and programs. The more memory you have, the larger the program and more data you can enter. Think of RAM as a warehouse. When you first turn on your computer the warehouse is just about emp ty, but as you run programs and enter information, the ware

w

house begins filling up. The larger the warehouse the more

^

information you can store there; when it is full, you have to

stop. TI-99/4A's come with 16K of RAM. The "K" for computerists refers to kilobytes or thousands-of-bytes, but the actual number is 1024 bytes. (The new disk storage systems are measured in megabytes or millions-of-bytes —1,024,000 bytes to be precise. The next time you're at a cocktail party, mention megabytes and you'll really impress everyone.) For now, all you need to know about bytes is that they are a measure of storage in computers. The more bytes, the more

room you have. Think of them in the same way you would

w ^ W W

^

gallons, inches or meters — simply a unit of measure.

RO M A second type ofcomputer memory is ROM, meaning

^

"Read Only Memory." This type of memory is "locked" into your computer's chips. Your TI-99/4A's programming Ianguage, called BASIC, is stored in ROM. The difference be tween ROM and RAM is that whenever you turn off your computer, all information in RAM evaporates, but ROM keeps all of its information. Don't worry, though, you can save whatever is in RAM on diskettes and tape and get it back.

w

We'll see how that is done later.

^

14

^

W

W

Now that you know a few terms and enough not to fear your computer, let's get it cranked up and running. If you already have your computer all hooked up and working properly, you can skip the next section and go directly to the POWER ON! section of this chapter.

•iiiiiiiiiiiiiiiiiiiiiiiiii

in •E3-

^

Hooking Up Your TI-99/4A and

w Peripheral Equipment \/

2 SOLID STATE PRINTER

3 RS232INTERFACE

^

4 OTHER

YOUR CHOICE?

W

Press 1 and your disk drive will spin and you will see the following at the top of your screen:

,

CATALOG DISK DSK1 - DISKNAME= PRACTICE-1

AVAILABLE= 358 USED= 0

28

w

\i^/

At the bottom of your screen are the COMMAND COM PLETED choices, and this time choose BEGIN and then BACK. You will now be at the "Introductory Screen." You have successfully initialized a diskette.

Once you have initialized your diskette, you NEVER have to initialize it again. If you do, you will destroy any files you have saved on your diskette. Of course you might want to remove all the files from your diskette, and initializing it is one way to do it. However, for the most part, once you initialize a diskette, you simply use it until it is filled up with files, and then initial ize a new diskette for additional files. Don't worry though, there's plenty of room on your diskette, and it will be a while before you fill it up. In Chapter 2 we will discuss saving files to your diskette.

w

29

WHAT DISKETTES TO BUY Vss&p/

When you purchase diskettes, all you need are Single Density, Single Sided, Soft Sectored diskettes. These are the least expensive 51/4 diskettes, and it is not advisable to buy double density diskettes. They will work fine, but they are more expensive and they will be formatted as single density diskettes anyway, so don't spend the extra money. In my experiences, cheap diskettes work as well as expensive ones, and I have not found more errors on the less expensive ones. However, the more expensive ones tend to be checked more thoroughly than the cheap ones; so I will leave the decision up to you. The best thing

to do is to check with other people who use the TI-99/4A with a disk system and see what their experiences

Vi&5/

V^i/

Vises/

Njjjjjijjj/

have been.

(See Chapter 9 for more details on using your disk system.) \jjjjg/

LOADing and RUNning From Tape

Vjsgs/

The procedure for loading and running programs from tape is

^

quite simple. The following steps show you how:

STEP 1 Make sure your tape recorder is connected and rewind it to the beginning. Set your tape counter to 000. If you have a tape with programs on it, use it to test loading. (A game cassette, notcartridge, will work fine.) If you do not have a tape with a program on it, enter the following program: (To get the quotation marks, press the FCTN (Function) and P keys

^ ^

\J W

simultaneously.) NEW TI BASIC READY (Appears on screen)

w

10 PRINT ""

W

20END SAVE CS1

W \^J

30 vm/

•w

At this point your computer will prompt you through the SAVE process. Do what it says. EXCEPTION:

V»,

W

When it says PRESS CASSETTE RECORD, press BOTH the PLAYandRECORD keysonyour recorder. * REWIND CASSETTE TAPE THEN PRESS ENTER

CS1

* PRESS CASSETTE RECORD

CS1

W"

THEN PRESS ENTER

^

* PRESS CASSETTE STOP

* RECORDING

CS1

THEN PRESS ENTER

* CHECK TAPE (Y OR N)? (Choose Y) * REWIND CASSETTE TAPE

CS1

THEN PRESS ENTER

* PRESS CASSETTE PLAY

CS1

THEN PRESS ENTER \JI^/

* CHECKING

Step/

* PRESS CASSETTE STOP

* DATA OK (If everything is OK) CS1

THEN PRESS ENTER

STEP 2 To make certain everything is OK, turn your computer off, and then turn it on again. This will make double sure your program is saved on tape. Get TI BASIC up and do the following: OLD CSr"

The command OLD loads your program from tape. At this point you will be prompted through the loading process. Do as prompted.

W

* REWIND CASSETTE TAPE THEN PRESS ENTER * PRESS CASSETTE PLAY THEN PRESS ENTER

W.

* DATA OK

W

CS1 CS1

♦READING

* PRESS CASSETTE STOP

w

THEN PRESS ENTER

CS1

If you did not successfully save your program to tape, you will get the following: *ERROR - NO DATA FOUND PRESS R TO READ

CS1

w

W

PRESS C TO CHECK PRESS E TO EXIT

Or * ERROR IN DATA DETECTED

PRESS R TO READ

CS1

PRESS C TO CHECK PRESS E TO EXIT

The first error means your recorder simply did not get the information on tape, and the second means that some error was in part of the program SAVEd. If one of these errors

occurs, try loading the program again with OLD. Make sure

Vagi!/

\sii>/

^

your tape has been rewound this time. Vfti/

If you keep getting errors, one of the following gremlins may have crept in:

W

1. Your sound or tone level on your recorder needs adjusting. 2. You used a recorder that is not compatible with

\&/

your computer.

3. Your cassette tape is bad. Make sure the write pro tect notches on your tape are in place.

v^

4. Your connections are bad. Check to see that every-

w

thing is connected properly. 5. Your recorder is too close to your TV set or on a metal surface. The TV or metal surface acted like a

big magnet and wiped out everything on your tape.

^

Before you go running back to the store where you bought your computer, check out these items thoroughly. If you still cannot save a program and recover it, then go back to your TI dealer and get help. (Phone first, since you might be able to solve the problem that way.)

Tape To Disk Transfer

If you have both a tape and a disk system and you don't want to wait for the longer loading time of tapes every

time you run it (especially when you start accumulating several programs on tape), why not transfer your tape files to disk? Just boot your DOS, put a formatted disk into the drive, initialize it and then load your program on

tape. Onceyour tape programis loaded, simply write in SAVE D ski ."" and now your tape pro

gram is on disk! Makes life simpler.

Cartridge Programs When you purchase cartridge programs for your computer, just insert the cartridge into the cartridge port and turn on your computer. It will automatically run the program for you. \ap/

• yS*>TI-99/4A^fc

Ftexas instruments

Computer

p a a a a H S o O a .a' (Qo Q

a

a

o

o

o

a

a

o H q o a u a a a i (ebi'b; a o a o o ffl a jplpiv

33

The TI-99/4A Keyboard Almost Like A Typewriter: The Familiar Keys If you are familiar with a typewriter keyboard, you will see most of the same keys on your TI-99/4A. For the most part, they do almost the same thing as your typewriter keys. If you type in the word COMPUTER, hitting the same keys you

W

would on a typewriter, the word COMPUTER appears on the

^

v*s/

screen just as it would appear on paper from a typewriter; however, the upper-case (capital letters) and lower-case let ters do not work exactly the same as a typewriter's. On the TI99/4A, your upper/lower-case characters are simply large and small upper case letters. When the ALPHA LOCK key is pressed, all letters are upper case, but the SHIFT key is still used to get the characters printed on top of the keys. For example, the "7" and "&" characters work the same with or

without ALPHA LOCK on. You will notice that the screen has

^

only 28 columns instead of 80 like most typewriters. Also you cannot type just anything on the screen. If you start typing away, you'll get an error message every time you press

^J

ENTER unless you put in the proper commands (e.g., *BAD NAM E, *CANT DO THAT.) Otherwise, though, think of your keyboard as you would a typewriter keyboard. NO TE: In most oftheprogramming examples, we will be using upper-case only, so

press ALPHA LOCK andleave it in upper-case.

10 REM HI I'M TI UPPER CASE 20 REM AND I'M TI LOWER CASE

W W

^

Nijjjggi/

Keys You wont see on a Typewriter While most of the keys on your TI-99/4A look like those on a

^

typewriter, many do not, and they are important to know about. The following keys are peculiar to your computer; you

will soon get used to them even though they will be a bit mys terious at first:

FCTN (Function key) This key, located in the lower right hand corner of your keyboard, is used for accessing the characters printed on the side ofthe keys.The strip along the

top of your keyboard indicates uses of the FCTN key along ,

with the other keys for editing and other special functions. Press FCTN and = simultaneously to see what happens.

W CTRL (Control) In the lower left hand corner of your key-

^

board isthe CTR Lkey, called the "control key." By pressing

the CTRLkey and one of the other keys you can get different

(w

effects. We will not be usingcontrol characters too much at

W

this stage of the game. Try holding the CTRLkey down and pressing the Gkey.This willgiveyou a graphic character. The

W

others are used for more advanced applications and will be introduced when needed. For the time being, don't worry about using it.

^

turn on a typewriter. Infact, you may see it referred to as a

ENTER The ENTER key is something like the carriage re-

Carriage Return or CR in computer articles. It works in an analogous mannerto a typewriter's carriagereturn because the cursor bounces back to the left hand side of the display

screen after you press it. There are many uses for the ENTER

w

key which will be discovered as you get into programming.

^

Arrow keys On the E, S, D and X keys are vertical and horizontal arrows. By pressing one of those keys and the

^

FCTN key, you canmove thecursor without affecting the text on the screen. These keys are used extensively in editing. For

W

example, if you key in PRUNT instead of PRINT, you can back over the word and make the correction without having to

W

start over again. Go ahead and try it. In the next chapter we

^

will discuss in more detail how these and other keys are used in editing.

^^>-

35 VlH^/

\ifiii/

Some New Meanings for Old Keys Some of the familiar keys have different meanings when used on the computer Many are math symbols you may or may not recognize. In the next chapter we will illustrate how these keys can be operated and discuss them in detail. For now let's just take a quick look at the math symbols.

^ *w

W

Symbol Meaning

w

+ —

Add Subtract

Viijjgj/

/

Divide (different from conventional)

Multiply (different from conventional) Exponentiation

s^y

V(S§»g/

In addition to some of the new representations for math symbols, other keys will be used in a manner which may be

unfamiliar to you. As we go on, we will explain the meanings

^

of these keys, but just to get used to the idea that your TI-99/4A has some special meanings for keys, we'll provide an example.

^

Symbol $

Meaning Used to indicate a string variable and

^

hexadecimal value.

For the time being, don't worry about understanding what all of these symbols do; simply be prepared to think about these symbols in "computer talk." As you become familiar with the keyboard and the uses and meanings of these symbols, you will be able to handle them easily, but the first step is to be aware that different meanings do exist.

Sjjgt/

Virgil/

Changing Keys You may have wondered what the plastic strips that came with your computer are for. One of them is labelled: DEL

REDO

INS

ERASE

BACK

CLEAR

QUIT

BEGIN

PROC'D

w

AID

w \i!^

36

The others are blank. Take the labelled strip and place it

^

above the keyboard in the tray above the keys with numbers on them. The bottom row has a gray dot corresponding to the

gray dot onthe FCTN key. If youpress the FCTN key and the key right below the label, under certain conditions your com puter willdowhat the labelonthe strip suggests. Wesaw that ifyoupress the FCTN and=keys together, your computerwill QUIT, just as the label says. Youwillreceive additional strips with different commands on the strips for different commer

cial programs. This is because the meaning of the keys can be changed and, depending on program requirements, some functions will be substituted for others. Thus, if you decide

lw W

you want to change the function of the keys, you will need a different strip to label. In Chapter6,we willexplain how this is done; in the meantime, we will just use the strip with the labels.

w

SUMMARY

^

You should now know how to hook up the different parts of

v^,

format a diskette, list the contents of a disk, and load and run a

This first chapter has been an overview of your new machine.

your TI-99/4A and get it running. You should also be able to

^

W W

program from disk or from tape. Finally, you should be familiar with the keyboard and know what the cursor means. At this point there is still much to learn, so don't feel badly if you don't understand everything. As we go along, you will pick up more and more; what may be confusing now will become clear later. Have faith in yourself and in no time you will be able to do things you never thought possible.

The next chapter will get you started in learning how to pro-

^ i

^

gram yourTI-99/4A. It isvitally important that you key inand run the sample programs. It is recommended that you make changes in the sample programs after you have first tried them out to see if you can make them do slightly different things. Both practical and fun (and crazy!) programs are

included so that you can see the purpose behind what you will be doing and enjoy it at the same time.

CHAPTER 2

w

Ladies and Gentlemen, Start Your Engines introduction

This chapter will introduce you to writing programs in the language known as BASIC. TI-99/4A BASIC is different from

some other versions of the language, and if you are already

familiar with BASIC, you will spot these differences. However,

^

if you are new to the language then you willfind programming in BASIC very simple. To get ready, turn on your computer, and when the TI BASIC READY and cursor come up on your TV, you are all set to begin programming. If something else is on your screen, key in the word NEW to clear memory.

, \0gb/

Your very First command! PRINT Vug/

Probably the most often used command in BASIC is PRINT.

Words enclosed in quotation marks following the PRINT com mand will be printed to your screen, and numbers and vari

ables will be printed if they are preceded by a P RINT command. It is used to command your computer to print output to the screen or the printer from within a program or in the Immediate

mode. You may well ask what the difference is between the

^j

Immediate and the Program mode. Let's take a look. Immediate Mode

The Immediate mode executes a com

mand as soon as you press ENTER. For example, try the following: (The notation means to press the key

marked ENTER.)

^ )

W

PRINT "THIS IS THE IMMEDIATE MODE" Signs/

If everything is working correctly, your screen should look like this:

V^l/

PRINT "THIS IS THE IMMEDIA TE MODE"

THIS IS THE IMMEDIATE MODE

(cursor)

See how easy that was? Now try PR INTing some numbers, but don't put in the quote marks. Try the following: PRINTB PRINT 54321

\^/

\gp/

As you can see, numbers can be entered without having to use quote marks, but as we will see later, the actual value of the number is placed in memory rather than a "picture" of it.

Program Mode This mode delays the execution of the commands until your program is RUN. All commands which

begin with numbers on the left sidewillbe treated as part of a \j^p/

program. Try the following: 10PRINT"THISISTHE PROGRAM MODE"

nothing happens, right? Enter the RUN command and your screen should look like this: \^^/

39 \HJg/

10 PRINT "THIS IS THE PROGRA M MODE" RUN

THIS IS THE PROGRAM MODE **DONE**

Your very First Program! Clearing the Screen and Writing Your Name Let's write a program and learn two new commands. First, the new commands are CALL CLEAR and END. The CALL

CLEAR command clears the screen and places the cursor in

\sjg»/

the lower left hand corner. The END command tells the com puter to stop executing commands. From the Immediate mode

write in the CALL CLEAR command to see what happens.

W

Now, let's write a program using CALL CLEAR, END and PR INT. From now on, press the ENTER key at the end of each

*&

line. Throughout the rest of the book, I will no longer be put ting in except in reference to entries in the Im-

^

mediate mode.

10 CALL CLEAR

^

20 PRINT ""

30 END

^

RUN



All you should see on the screen is your name, ** D0 NE**and

the blinking cursor. Now, as a rule of thumb, always begin

^

your programs with CALL CLEAR. This willhelp you get into

a habit which will pay offlater when you're running all kinds

^

butfor the most part, by beginning your programs with CALL

^

of different programs. There will be exceptions to the rule,

j

CLEAR, you will start off with a nice clear screen rather than a cluttered one. Also, we want to make liberal use of the REM

statement. After the computersees a REMstatement in a line, it goes on to the next line number, executingnothing until it

_j

comes to a command which can be executed. The REM

^

statement works as a REMark in your program lines so that

others will know what you are doing and as a reminder to yourselfwhat youhavedone. Just toseehow it works, let's put

W

it into our little program.

^

4U

\j/^

10 CALL CLEAR

20 REM THIS CLEARS THE SCREEN 30 PRINT "" 40 END

50 REM THIS MAGNIFICENT PROGRAM WAS CREATED BY

Now RUN the program and you will see that the REM statements did not affect it at all! However, it is much clearer

as to what your program is doing since you can read what the W

commands do in the program listing.

Setting up a Program ^

using Line Numbers

^"" Now that we've written a little program let's take a look at i

using line numbers. In your first program we used the line

i

numbers 10,20 and 30. We could have used line numbers 1,2 and 3 or 5,6 and 7 or even 1000,2000 and 3000. In fact, there is no need at all to have regular intervals between numbers,

^

and line numbers 1, 32 and 1543 would have worked just fine.

W

^

However, we usually want to number our programs by 10's, starting at 10. You may well ask, "Wouldn't it be easier to number them 1,2,3,4,5, etc.?" In some ways maybe it would, but overall, it definitely would not! Here's why. Type in the word LIST , and if your program is still in memory it will appear on the screen. Suppose you want to insert a line between lines 20 and 30 which prints your home address.

Rather than re-writing the entire program, all you have to do is to enter a line number with a value between 20 and 30 (such

w

as 25) andenterthe line. Let'stry it,butfirstremove the END

i

command in line 20. To do so simplyenter the line number and

W . (i.e., 20 ). SjM^j/

25 PRINT "" RUN

SUP'

Aha! You now have your name and address printed on the

^

screen, and you simply wrote in one line instead of retyping

the wholeprogram. Now,ifwe had numbered the program by

^

l's instead of 10s, you would not have been able to do that

since there would be no room between the lines numbered 2 and 3 like there was between the lines numbered 20 and 30. You would have had to rewrite the whole program. With a small program this would not be much of a problem, but when you start getting into 100 and 1000 line programs, you'll be glad you have space between line numbers!

^

W W \t^

Listing Your Program

Vijigi/1

As wejust saw, using the word LIST gives us a listing of our

^

program. To make it neat, type in (SHIFT) CALLCLEAR and

LIST , and you'll get a listing on a clear screen, Once you start writing longer programs, you won't want to list everything, only portions. Let's examine the options available

v^ w

with the LIST command

What you write what you Get LIST LIST 20

Lists entire program. Only line 20 is listed (or any line number

w

you choose).

LIST 20-30 LIST -40

LIST 40-

All lines from 20 to 30 inclusive are listed (or any other range of lines you choose). Lists from the beginning of the program to line 40 (or any other line number chosen).

Lists from line40 (or any other linenum-

w

^i^

^

ber chosen) to the end of the program.

Try listing different portions of your program with the options available to see what you get. The following commands will give you some examples of the different options:

^

LIST 25

LIST 20

W

LIST-20

LIST 25-30

w

42

N"*S^ Sjjjj$/

i

Renumbering Lines

^

Suppose you number your lines by 10, and then after working

onyourprogram, you find that you have tofill inallthe spaces W between lines 20 and30. Then you find that you have to add

W W

still more between lines 20 and 30, but there is no more room.

(This willhappen ifyou program- even when aprogram iswell planned.) With TIBASIC thisisnotaproblem. All you have to do is use the RESEQUENCE command. This command will

renumber yourprogram foryou. To useit employ the follow^

ing format: RESEQUENCE (First line number), (Increment be-

W

tween lines)

For example enter the following program: 10 REM THIS DOES NOTHING

W

11 REM EXCEPT SHOW YOU HOW

W

13 REM COMMAND

12 REM TO USE THE RESEQUENCE

^

^

Now enter

RESEQUENCE 10, 10 Now enter LIST

Your program is now numbered by increments of 10. ^VjjUjjgf/

i

w

Automatic Line Numbering To save programming time, you can have the computer automatically enter the line numbers for you. Using the

NUMBER function, you canspecify the beginning linenum ber and the increments, exactly in the same format as used

W

with RESEQUENCE.

NUMBER (First line number), (Increment between

lines)

^

To see how this works, enter A7E1T

^ W

NUMBER 10, 10

10 (Appears on screen)

^

When the 10 appears enter REM

20 (Appears on screen) You can now program without having to worry about line numbers. Every time you enter program statements and press

ENTER, the next line number will pop up. When you are

^

finished, just press ENTER when the next line number appears

and you will jump back into the Immediate Mode.

^

Saving Your Program Suppose you write a program, get it working perfectly and then turn off your computer. Since the program is stored in the RAM memory, it will go to Never-Never Land, and you will

haveto write it in again ifyouwant to use it. Fortunately, it is a

^

simple matter to SAVE a program to your diskette. Let's use our program for an example of SAVEing a program to disk. Make sure your program is still in memory by LI STing it, and if

^

it is not, re-write it. Make sure a initialized disk is in the drive

w

and write in the following: SAVE DSK1.MYPROGRAM

(If you are not certain about disk initialization, review the sec

tion covering those items in Chapter 1.) The disk will start whirling and the red light will glow on the disk drive. This means the disk drive is writing your program to disk. When the red light goes out, your program should be SAVEd on disk.

44

^

w

saving Programs on Tape

W

To save a program to tape, put a blank cassette into your tape recorder and rewind it. Press the RECORD button and the

W

PLAY button together on your tape recorder and write in SAVE CS1. The tape recorder will start spinning and will be

W w

W w

promptedthrough the SAVE sequence as described in Chap ter 1. As you SAVE more and more programs, they will become difficult to find unless you keep some record of what is on

the tape. The best way to dothis is to keep a logof the starting

position and ending position ofthe TAPE COUNTER. Enter a

descriptive name of the program you have SAVEd corres-

ponding to the tape counter values. Also, as you write more

;

and more programs, you will want to label your cassettes as well. The following shows you an example of a tape log:

^

CASSETTE NUMBER BEGINNING END DESCRIPTION SIDE 1 1

a

0

8

a

8

10

Variables

String program

1 1 2 2

a

10 0 0

a

5

a

b

15

Subroutines

20

Checkbook

5 30

Input Output

Retrieving Your Programs Thebestwayto makesure you have SAVEd aprogram to disk

orto tape is to completely turn off your TI-99/4A, and then turn it on again. Go ahead and do it. Now you know there is nothing in memory. Enter

45

OLD DSK1.MYPROGRAM

and your disk drive will whirl for a while and stop. Now enter LIST and if all went well your program will be LISTed to the screen. If you key in the name wrong or there is

some other error, the screen will show something like the

Sasi/

.

^

following: * WARNING:

W

CHECK PROGRAM IN MEMORY

*l/0 ERROR 50

To see if your program is in the disk CATALOG, QUIT (FCTN=), go to the DISK MANAGER and choose DISK COMMANDS and CATALOG DISK to SCREEN. Your pro gram should be listed under FILENAMES along with a SIZE and TYPE designation. It will say MYPROGAM under FILENAME. If it is there, you know for certain everything

^ W

has worked.

If you have a tape cassette, key in OLD CS1 and

follow the prompts through the loading process. Since there is

^

no file name designation for programs stored on tape, you

have to use the FFWD (Fast Forward) key on your recorder to

^

move the tape up to the location where the desired program begins. This is where your tape log becomes crucial! A SAFETY NET

As you begin writing longer programs, every so many lines you should SAVE your program to disk or tape. In this way, if your dog accidentally trips over your cord and turns off your computer, you won't lose your pro gram and have to shoot the offending pooch. Saves both

Njgjg/

programs and dogs.

Now that you have SAVEd and loaded programs, let's look at

another neat trick. Remembering you SAVEdyour file under

^

the name MYPROGRAM, let's change the contents of that file. First, add the following line and then LIST your program:

W

27 PRINT ""

4b

W

v^y

Yourprogram is nowdifferentfrom the programyouSAVEd inthefileMY PROGRAM since you have added line 27. Now write in

SAVE DISK1.MYPROGRAM

Clear memory with NEW, OLD the file MYPROGRAM and LISTit.Asyoucansee,line27isnowpartofMYPROGRAM. Allyou have to do to update a program is to 0 LD it, make any

changes you want, and then SAVE it under the same file W

name; howeverBE CAREFUL. Nomatter what program is in memory, that program will be SAVEd when you enter the

^

SAVE command; therefore, if your disk has PROGRAM A and

you write PROGRAM B, and then SAVE it under the title PROGRAM A, it will destroy PROGRAM A and the SAVEd

program will actually be PROGRAM B. Also, if you have a really important program, it is a goodidea to make a back-up file.For example, ifyou saved your current program under the file names, MYPROGRAM and MYPROGRAM2 it would have two files with exactly the same program. To really play it safe, save the program on two different diskettes. ITOLDYOUSODEPT.

Sooner or later the following will happen to you: You will have several disks or tapes, one of which you want to initialize and one on which to save programs. You will

pick up the wrong diskette or cassette, one with valuable programs on it. There will be no write protect tab on the diskette or cassette, and after you initialize it or over

write programs on it and blow away everything you wanted to keep, you will realize your mistake and say, "!&$#"!%&", and kick your dog. You cannot prevent

that from happening at least once, believe me. Therefore, to insure that such a mistake is not irreversible, do the

following: MAKE BACK-UPs. Take your ORGINAL and put it somewhere out of reach, and when you ac cidentally erase a disk or tape, you can make another copy. Remember, if you fail to follow this advice, your dog will have sore ribs. Be kind to your dog.

Using Your Editor: Fixing Mistakes on the Run Error Messages and Repairing Them By now you probably entered something and got a * IN CORRECT STATEMENT,* INCORRECT STATEMENT IN

30 (referring to line 30 or any other line where an error is detected) or some other kind of error message, such as RED0 FROM START, which told you something was amiss. This occurs in the Immediate mode as soon as you hit ENTER and in the Program mode as soon as you RUN your program. Depending on the error, you will get a different type of message. As we go along, we will see different messages depending on the operation. For now, we will concentrate on how to fix errors in program lines rather than the nature of the

errors themselves. This process is referred to as editing pro grams. (See III-8 to 111-12 of your User's Reference Guide for a complete list of error messages.)

48

S^gl/

Deleting Lines

The simplest type of editing involves inserting and deleting lines. Let's write a program with an errorin it and fix it up. NEW 10 CALL CLEAR

20 PRINT "AS LONG AS SOMETHING CAN" 30 PRINT "GO WRONG" 40PTINT"ITWILL"

50 REM LINE 40 HAS AN ERROR 60 END RUN

If the program is written exactly as depicted above, the pro gram will BOMB. On your screen you will see the message •INCORRECT STATEMENT (or BAD NAME) IN 40

.^fS^-'A

la

49

Now key in 40 LIST

What happened to line 40 ?! You just learned about deleting a

line. Whenever you enteraline number and nothing else, you

^

delete the line. We already learned how to insert a line, so all you have to do to fix the program is enter the following:

Vagi*/

40 PRINT "IT WILL"

Now run the program. It should work fine. The error was in the misspelling of PR INT. Another way you could have fixed the program was simply to re-enter line 40 correctly without first deleting it, but I wanted to show you how to delete a line

by enteringthe linenumber. Whenyoumakemost otherkinds

"VSjjgjjij/

' ,

^

of errors, your TI-99/4A will let you know immediately. If this

occurs, the line you attempted to enter will be deleted

^j

automatically.

Using the TI-99/4A Editor Within your.TI-99/4A is a trusty editor. To see how to work with your editor, we'll write another bad program and fix it. OK, write the following program and RUN it. NEW 10 CALL CLEAR

20 PRINT "IF I CAN GOOF UP A PROGRAM "

^j

30 PRINT "I CAN FOX IT"

40 REM LINE 30 ISN'T QUITE RIGHT

'^j

50 END

RUN

AH right, you want to FIX your FOX in line 30. To repair it, instead of rewriting line 30 do the following:

W

STEP1. LIST your program

w

STEP 2. Key in EDIT 30

Nag/

STEP 3. Now using the right ARROW key (FCTN-D) "walk" the cursor to the right until it is over the "0" in "FOX".

STEP 4. Key in an "I" and press {ENTER}.

^

STEP 5. LIST your program to make sure the correction has been made.

RUN the program, and you should see the statement, IF I CAN GOOF UP A PROGRAM ICAN FIX IT. Let's learn more about the editor. Put in the following program: 10 CALL CLEAR

20 PRINT "SOMETIMES I LIKE TO WRITE LONG W

LONG LINES"

W

30 WHEW 40 PRINT "AND SHORT ONES TOO" 50 END

W

LIST RUN

^

OK, after you ran the program itwent"ElBombo." The prob-

,

lem was that we stuck in that WH EW in line 30 without a

W \$JHtfp/

Stjksg/

^

REM statement. Torepairit, LIST theprogram, and EDIT 30 . The cursor will be right over the"W" in WHEW.

Press the FCTN and 2 keyssimultaneously. NOTE: On thestrip

above the keyboard there is the label "INS" right above the "2" key That standsfor INSERT. Key in REM (SPACE). You have just used the insert function of your editor! See how easy that was. Press ENTER. Now RUN the program. Everything

W

Now let's take a look at a feature of the TI-99/4A editor that

will help you fix programs. Key in N EW < ENTER> and we'll W

start a new program. 10 CALL CLEAR

20 PRINT "I LIKE TO COMPUUUUUUTE"

Whoops! There's a mistake, but no sweat. Just EDIT 20

j

the cursor over to the first of the multiple "U's." Next, press

^j

the FCTN and 1 keys simultaneously until there is only a single "U" in COMPUTE. Afate: The DEL labelabove the1 keystands for DELETE, butI betyoufiguredthat outfor yourself

^j

, and usingthe RIGHT ARROWfFCTN-DJ "walk"

More Editing

w

Let's do a few more things with your editor before going on. We'll practice some more with inserting characters and numbers, but we will also see how to edit groups of characters. So,

let's see how we can use the editor to do more with "inser-

^

tions." Try the following little program: Nanus/

10 CALL CLEAR 20 PRINT "NOW IS THE TIME FOR ALL GOOD" 30 PRINT "MEN TO COME TO"

40 PRINT "THE AID OF THEIR COUNTRY!" 50 PRINT "AND HAVE A GOOD TIME"

NiSSyi/

V^/

Ns$ga/

So far so good, but you meant to include women as well as men in line 30. You could retype the entire line, but all you really need to addis AND WOMEN after MEN. Also, it's really bor ing to have everything in upper case. Let's change the line to include women and make it both upper and lower case. Final ly, we want line 50 to be EN D instead of that other stuff.

w

STEP 1. Press the ALPHA LOCK key so that it is in the "up" position.

w*

^

W

STEP 2. EDIT 20 . Walk the cursor to the 0

in NOW and key in everything in lower case over the original text.

W

STEP 3. EDIT 30 and insert 'and women'. Make sure that

w

'and women' is inside the original pair of quotation marks. Press ENTER when the changes in line 30 are complete.

•)

52

, ,

W

STEP 4. EDIT 40 . Press the FCTN and 3 keys

simultaneously. Everything but the line number dis appeared! NOTE: That's whatthe ERASE labelabove the 3 key means!Now keyin END. After these repairs, you now have upper and lower case in line 20, and when you RUN your program it should read: Now is the time for all good men and women to come to the aid of their country. **DONE**

You will save yourself a great deal of time if you use the editor rather than retyping every mistake you make. Therefore, to

practice with it, there are a several pairs of lines below to

^

repair. Thefirst lineshows the wrongway and the secondline

W

in the pair shows the correct way. Since "little" things can make a big difference, there are a number of changes to be

W

made. However, as you will soon see, those little mistakes are the ones we are most likely to get snagged on. Practice on these examples until you feel comfortable with the editor -

^

time spent now will save you efforts later.

Editor Practice W

50 PRINT "I LICK MY Tl" 50 PRINT "I LIKE MY Tl" 10 PRINT CLEAR

^

10 CALL CLEAR

w

80 PRINT "A GOOD MAN IS HARD TO FIND" 80 PRINT "A GOOD PERSON IS HARD TO FIND" 40 PRINT CALL CLEAR 40 CALL CLEAR 50 "WE'RE OFF!"

w

50 PRINT"WE'RE OFF!"

\jgj/

If you fixed all of those lines, you can repair just about any

thing. Once you get the hang of it, it's quite simple.

^

ELEMENTARY MATH OPERATIONS

w

So far all we've done is to P RI NT out a lot of text, but that isn't too different from having a fancy typewriter. Now, let's do some simple math operations to show you your computer can compute! Enter the following:

^ w

CALL CLEAR

PRINT2 + 2

^

This is what your screen should look like now: PRINT2 + 2

Big deal, so the computer can add - so can my $5 calculator and my 8 year old kid. Who said computers are smart? The programmer (you) is who is smart. OK, so let's give it a little

W

tougher problem.

^

CALL CLEAR

PRINT 7.87* 123.65

Still nothing your calculator can't do, but it'd be a little rough on the 8 year old.

As we progress, we can include more and more aspects of mathematical problems. In the next chapter, we will see how we can store values in variables and a lot of things that would

^ \j[j$0jr

choke your calculator. For now, though, all we'll do is to introduce the format of mathematical manipulations. The "+"

and"-" signs work just as they do in regular math, and the "x" is replaced by the "*" (asterisk) for multiplication and the "-*-" is replaced by the "/" (slash) for division.

\i^y

As we begin dealing with more and more complex math, we will need to observe a certain order in which problems are executed. This is called precedence. Depending on the oper ations we use, and the results we are attempting to obtain, we will use one order or another. For example, let's suppose we

want to multiply the sum of two numbers by a third number say the sum of 15 and 20 multiplied by 3. If you entered PRINT 3* 15 4-20

W

W

you would get 3 multiplied by 15 with 20 added on (3 X15 = 45 and 45 + 20 = 65). That's not what you wanted. You wanted to get 3 times 15 plus 20 (3 X 35 = 105). The reason for that is precedence - multiplication precedes addition. To help you

^

remember the precedence, let's write a little program you can

w .

run and then play with some math problems in the Immediate mode to see the results and refer to your "Precedence Chart" on the screen. (This little program is quite handy; so save it to

^

disk or tape to be used later.) 10 CALL CLEAR

w

20 PRINT "1. - [MINUS SIGNS FOR NEGATIVE

W

30 PRINT "-NOT SUBTRACTION}"

NUMBERS"

Vjt^/

l \MjtefS

40 PRINT "2. (EXPONENTIATION)" 50 PRINT "3. */ (MULTIPLICATION AND DIVISION)" 60 PRINT "4. + - (ADDITIONS AND SUBTRACTIONS)" SUBTRACTIONS)" 70 PRINT "NOTE: ALL OTHER PRECEDENCE"

74 PRINT "BEING EQUAL, PRECEDENCE"

w

78 PRINT "IS FROM LEFTTO RIGHT"

W

THE NUMBERS IN PARENTHESES,"

W

90 PRINT "WORKING ITS WAY FROM THE INSIDE OUT IN MULTIPLE PARENTHESES."

80 PRINT "YOUR COMPUTER FIRST EXECUTES

Njjjjg^/

Try some different problems and see if you can get what you want.

v^ip

Re-ordering Precedence Once you get the knack of the order in which math operations work, there is a way to simplify the organization of math prob

Nasi/

lems. By placing two or more numbers in PARENTHESES, it

^j

is possible to move them up in priority. Let's go back to our example of adding 15 and 20 and then multiplying by 3, but this time we will use parentheses.

w

PRINT 3* (15+ 20)

w

Now since the multiplication sign has precedence over the addition sign, without the parentheses, we would have gotten 3 times 15 plus 20. However, since all operations inside parentheses are executed first, your computer FIRST added 15 and 20 and then multiplied the sum by 3. If more than a single set of parentheses is used in an equation, then the innermost is executed first, working its way out.

^ W W

THE PARENTHESES DUNGEON

To help you remember the order in which math operations are executed within parentheses, think of the operations as being locked up in a multi-layer dungeon. Each cell represents the innermost operation, and the cells are lined up from left to right. Each "prisoner" is an opera tion surrounded by walls of parentheses. To escape the dungeon, the prisoner must first get out of the innermost cell, then go to his right and release any other prisoners in their cells. Then they break out of the "cell-block" and finally out into the open. Unfortunately, since operations are "executed," this is a lethal analogy for our poor escaping "prisoners." Do some of the examples and see if you can come up with a better analogy.

Ou

Sugg/

"Vmp/

The following examples show you some operations with parentheses.

PRINT 20 +10*(8-4) PRINT (12.43 + 92) / 3 (11-3) PRINT (22 - 3.1415) * (22 + 3.1415) PRINT ((16+ 4)-(3+ 5))/18 PRINT 19 + 2 * (51 / 3) - (100/14)

Now try some of these problems in the proper format expected W

W \^0/

,

^ W W

w

\^nt/

^ W W

by your computer:

Multiply the sum of 4, 9 and 20 by 15. Multiply 35 by 35 and the result by pi (3.14159265). (You realize that this will compute the area of a circle with a radius of 35; to find the area of any other circle, just change 35 to another value.) Pretty neat, huh? Add up the charges on your long distance calls and divide the sum by the number of calls you made. This will give you the average expense of your calls. Re member, though, you have to do this in one set of statements in a single line. Do the same thing with your checkbook for a month to see the average (mean) amount for your check. Add up the total amount you spent on your computer and peripherals and subtract from that sum the amount you would have spent at video arcades. (If your results are negative, you can claim that amount saved by buying a computer!)

SUMMARY This chapter has covered the most basic aspects of program ming. At this point you should be able to use the editor in your TI-99/4A and write commands in the Immediate and Program

(deferred) modes. Also, you should be able to manipulate basic math operations. However, we have only just begun to uncover the power of your computer, and at this stage, we are treating it more as a glorified calculator than a computer. Nevertheless, what we have covered in this chapter is ex-

tremely important tounderstand, for itisthefoundation upon

^

which your understanding of programming is to be built. If

there are parts you do not understand, review them before continuing. If you still do not understand certain operations after a review, don't worry. You will be able to pick them up later, but it is still important that you try to get everything to do what is is supposed to do and what you want it to do.

^ w W

The nextchapter will takeus into therealm ofcomputer pro gramming and increase your understanding ofyour TI-99/4A considerably. If you take it one step at a time, you will be

amazed at thepower you have at your fingertips andhow easy it istoprogram. Also, wewill beleaving therealm ofcalculator

VtHigi/

like commands and getting down tosome honest-to-goodness computer work. This is where the fun really begins.

W

vug!!,/

^

CHAPTER 3

Moving Along introduction

w ,

In the last chapter, we saw how to get started in executing commands in both the Immediate and Program modes. From now on we will concentrate our efforts on building from the

^

foundation set in Chapter 2 in the Program mode, tying various commands together in a program. We will, however, use the Immediate mode to provide simple examples and to give you an idea of how a certain command works. As we learn more and more commands, it .would be a good idea if you started

w

saving the exampleprograms on your disk or cassette so that

\jjjj^/

they can be used for review and a quick "look-up" of examples. Use file names that you can recognize, such as VARIABLE EXAMPLE or HOW TO SUBROUTINES, and remembereach

W

file has to have a different name; so be sure to number exam

W

ple file names (e.g., ARRAYS 1, ARRAYS 2, etc.). In your cassette log, you can have more descriptive names and even comments about the programs.

w

VARIABLES

VjjjjH/

Perhaps the single most important computer function is in variable commands. Basically, a variable is a symbol that can have more than a single value. If we say, for example, X = 10, we assign the value of 10 to the variable we call "X". Try the following: X = 10 PRINT X

Your computer responded 10

Now type in X=55.7

PRINT X

This time you got

w

bo./

Each time you assign a value to a variable, it will respond with the last assigned value when you PRINT that variable. Now

^

try the following:

w1

X=10

W

Y=15

PRINT X + Y

^

And your TI-99/4A responded with 25

As you can see, variables with numbers can be treated in the same way as math problems. However, instead of the num bers, you use the variables. Now let's try a little program using variables to calculate the area of a circle.

^J W

10 CALL CLEAR

20 PI = 3.14159265

J

30 REM THE VALUE OF PI RECALLED

FROM GEOMETRY

W

40 R = 15

50 REM "R' IS THE RADIUS OF OUR CIRCLE

W

60PRINTPI*(R*R] 70 REM THIS GIVES US PI TIMES THE SQUARE OF

W

THE RADIUS

80 END When you RUN the program, you will get the area of a circle with a radius of 15. If you change the value of R in line 30, it is a simple matter to quickly calculate the area of any circle you

^

want! Since our example "squares" a number, why don't we

^

Vjjjgjp/

use our exponential sign " * ". Change line 60 to read:

60 PRINT PI * (R a 2)

60

.

w

RUN the program again and see if you get the same results. You should. Also, change the value of R to see the areas of dif ferent circles.

variable Names

At this point you might wonder why not use variables. First, in programs where a value will change, it is very difficult to keep entering new numbers. Secondly, as we saw above, we can use descriptive names for variables so that we know what to expect. (PI in our program.) For example, the following pro gram uses MEAN as a descriptive variable name: 10 CALL CLEAR 20 A = 15

30 B = 23 40 C = 38

50MEAN = (A + B + C)/3 60 PRINT MEAN

W \^ff/

70 END

If the above program were a hundred or more lines long, you would know what the variable MEAN does - it calculates a

*s^gp/

mean.

Other considerations in naming variables include reserved words. These are words set aside for programming com mands, functions and statements. Let's look at some exam ples of what is and what is not a valid variable name:

S^^/

Vjjllgji/

PRINT = 987 (Invalid name since PRINT is a reserved word.) R1 =321 (Valid name since first character is a letter.) 1 R = 55 (Invalid since first character is not a letter.)

^

PR = 99 (Valid name, even though reserved word

W

served word is used in variable name.) TO = 983 (Invalid name since TO is a reserved twocharacter word.) ADFETDCVRRWRDAAF = 10 (Valid name, but really dumb.)

PRINT begins with PR, because only part of the re-

W

^

W

61

V^§/

It is also possible to give values to variables with other variables or a combination of variables and numbers. In our

example with the variable MEAN we defined it with other variables. Here are some more examples:

T = A*(B + C) N = N + 1

SUM = X + Y + Z

Types of variables Real variables

Sofar we'veused only"real" or "floatingpoint" variables in

our examples. Any variable which begins with acapital letter and does not end with a dollar sign ($) is a real variable. The value for a real variable can be from+or -9.9999999999999E127.

The "E" is the scientific notation for very big numbers. For the

_.

w

\sy

s^gy/

time being, don't worry about it, but if you get a result with such a letter in a numeric result, get in touch with a math instructor. At this juncture, figure you can enter numbers in

^

their standard format from 0.01 to 999,999,999. (If your check-

^

book debit or income tax payments have a scientific notation in them, leave the country.) Think of real variables as being

W

able to holdjust about any number youwouldneed along with the decimal fractions.

^

String variables

\^/

String variables are extremely useful in formatting what you will see on the screen, and like real variables, they are sent to the screen by the PRINT statement. However, rather than

printing only numbers, string variables send all kinds of

,

^

characters, called "strings", to the screen. String variables

are indicated by a dollar sign ($) on the end of a variable. For example, A$, BAD$, G$, and PU LL$ are all legitimate string variables. (In computer parlance, we use the term "string" for the dollar sign. Thus, our examples would be called "A string", "BAD string", etc.) String variables are defined by placing the "string" in quotation marks, just as we did with other messages we PR INTed out.

(52

^ ^

w

W

v«^

^

Let's try out a few examples from the Immediate mode:

W

ABCS = "ABC" PRINT ABCS

W

G$ = "BURLESQUE" PRINT G$ KAT$ ="CAT" PRINT KAT$ NUMBERS = "123456789" PRINT NUMBERS B1 $="5 + 10 + 20"

PRINT B1$

W

PRINTS = "PRINT" PRINT PRINTS

^

Like realvariables, stringvariables mustbegin with a letter;

^

portantly, you probably noticed in our examples that numbers

however, string variables can use reserved words. More im-

W

in string variables are not treated as numbers, but rather as "words" or "messages." For example, you may have noticed that when you P RINTed B1$, instead of printing out 3 5 (the sum of 5,10 and 20), B1 $ printed out exactly what you put in

W

quotes, 5 + 10 + 20. Do not attempt to do math with string variables. (In later chapters, we'll see some tricks to convert

W

as messages.)

W

Now let's put all of our accumulated knowledge together and write a program that uses variables. We will start a little pro gram which will allow you to subtract a check from your

W

checkbook and print the amount. This program will be the

^

handy little program to do checkbook balancing.

^

string variables to numeric ones, but for now just treat them

beginning of something we will later develop to give you a

10 CALL CLEAR

^J

20 BALANCE = 571.88

30 REM ANY FIGURE WILL DO.

^J

40 REM BALANCE IS A REAL VARIABLE

50 CHECK = 29.95

W

60 REM WHAT YOU LAST SPENT IN THE

COMPUTER STORE.

W

70 REM CHECK IS A REAL VARIABLE.

80 B$ = "BEGINNING BALANCE=$"

^

90 C$ = "YOUR CHECK IS $"

100 NB$ = "NEW BALANCE IS $" 110 REM B$. C$ AND NBS ARE STRING VARIABLES 120 PRINT B$;BALANCE 130 PRINT C$;CHECK

w

vm§/

140 N = BALANCE - CHECK

150 PRINT NBS; N 160 END

Since this is a fairly long program for this stage of the game, make sure you put in everything correctly. For the computer, it is critical that you distinguish between commas, semi

colons, periods, etc. Also, save it to disk. To play with it, change the values in lines 20 and 30. Let's quickly review what we have done.

w

Vane/

W

STEP 1. First we defined the real variables BALANCE and CHECK.

\$gy

STEP 2. Then we defined string variables B$, C$

^

and NBS to use as labels in screen

formatting. STEP 3. Finally, we printed out all of our information using our variables, with one new variable, N, defined as the difference between BALANCE and CHECK.

Vasts/

^j W

Note how we formatted the OUTPUT (what you see on your

screen) ofour PRI NT statements. The semi-colon ";"between the variables accomplished two things: (1) it told the com

puter where one variable ended and the next began, and (2) it told the computer to PRINT the second variable right after the first one. Thus, it took the string variable N B$ NEW BALANCE IS $#

64

w Vg|^/

^

W W W

and stuck the value of the real variable N right after the dollar sign (exactly where we placed the hatch #). Later we will go more into the formatting of OUTPUT, but for now let's take a quick look at using punctuation in formatting text. We will use the comma "," and semi-colon ";" and "new line" to illustrate

basic formatting. Put in the following little program: \i(ji$(jg/

NEW 10 CALL CLEAR

Vi$y/

20 AS = "HERE" 30 B$ = "THERE" 40 C$ = "WHERE"

W

50 PRINT AS;

W

60 PRINT B$; 70 PRINT C$; 80 REM SEMI COLONS

W

90 PRINT

^

110 PRINT B$,

100 PRINT AS, 120 REM COMMAS 130 PRINT

140 REM A 'PRINT' BY ITSELF GIVES A 150 REM VERTICAL'SPACE' IN FORMATTING 160 PRINT AS

170 PRINT B$ 180 PRINT C$ 190 REM "NEW LINES' 200 END

W

Now RUN the program. As you should see, the little differ

*w

ences in lines 30,40 and 50 made big differences on the screen. The first set is all crammed together, the second set is spaced

W

evenly across the screen in two columns and the third set is stacked one on top of the other. As we saw in the previous program, semi-colons put numbers and strings right next to

^

one another. However, using commas after a PR INTed vari

^

usingnewlinesin the form ofcolons or newlinenumberswill

.

make the output start on a new line. A PR INT statement all by itself will put a vertical linefeed between statements. Try the following little program to see how PRINT statements all by

able will space output in groups of two across the screen, and

themselves can be used.

\%/

Vjjggj/

V«fii/

Vjjgi/

Vums/

\%>/

Vis&j>/

\Our proaraft proqra/n MB* /vac* Aaoe. Jour Sim/

NEW 10 CALL CLEAR

20 PRINT "WHENEVER YOU PUT IN A

s«g$/

PRINT STATEMENT"; 30 REM NOTE PLACEMENT OF SEMI-COLON

V^j/

40 PRINT " ALL BY ITSELF," 50 PRINT "IT GIVES A 'LINEFEED'."

Njj^gj/

60 PRINT

Siifcy

70 PRINT "SEE WHAT I MEAN?" 80 END

Vjjjyjj/

Play with commas, semi-colons and new lines with variables and string variables until you get the hang of it. They are very important and are the source of program "bugs." If your line is too long after a semi-colon, instead of having the next line of printed text where you expect it, it will "linefeed." To see this effect, combine lines 40 and 50 into a single line with one

Sjjjjjjg/

V^j/

Siijjij^/

PRINT statement.

Sssfc/

66

\gg/ S^ggs/

BUGS and BOMBS

\i]^/

Vjigjjg/

VjUjjg/

We've mentioned "bugs" and "bombs" in programs but never really explained what they meant. "Bugs" are sim ply errors in programs that either create 9SYNTAX ER R O Fts or prevent your program from doing what you want it to do. "Debugging" is the process of removing "bugs." "Bombing" is what your program does when it encounters a "bug." This is all computer lingo; if you use it in your conversations, people will think you really know a lot about computers or have a bug in your personality.

INPUT and OUTPUT (I/O)

Input and output, often referred to as I/O, are ways ofputting things into your computer and getting them out. Usually we put IN information from the keyboard, save it to disk or tape, and then later put it in from the disk drive or cassette recorder.

When we want information OUTofthe computer, we want it to go to our screen or printer. This is what I/O means. So far, we V%^/'

\i^jg/

Prvyans CM &3Z& \^jg/

67 \$0/

have entered information IN the computer from the keyboard either in the Program or in the Immediate mode. Using the

.

PRINT statement, we have sent information OUT to the

^J

screen. However, there are other ways we can INPUT infor

mation with a combination of programming and keyboard

^

commands. Let's look at some of these ways and make our CHECKBOOK program a lot simpler to use.

W

INPUT

w

The INPUT command is placed in a program and expects some kind of response from the keyboard and then an ENTER.

W

(An ENTER alonewill alsowork, but the responseis read as

^

"".) It must be part of a program and cannot be used from the

Immediate mode. (If attempted from the Immediate mode, there will be a *CANT DO THAT message.) Let's look at a simple example: NEW

^ v^/

W

10 CALL CLEAR

20 INPUT X

^

30 REM *X' IS A NUMERIC VARIABLE SO ENTER

A NUMBER

w

40 PRINT X

50 END

w

RUN the program and your screen will go blank and a ? along with a blinking cursor will sit there until you enter a number

\^)

and then the computer will PRINT the number you just

w^

entered. Really interesting, huh?

Let's try INP UTting the same information but using a slightly

different format. The nice thing about INPUT statements is that they have some of the same features as PR INT statements

for getting messages on the screen. Look at the following

^

^

program:

. .

NEW

10 CALL CLEAR 20 PRINT "WHAT IS YOUR AGE";

*J

30 INPUT X

W

40 CALL CLEAR

50 PRINT "YOUR AGE IS "; X

68

^

vsgp/

^ W W ^

Now RUN the program; you will see that the presentation is a little more interesting. Also notice we did not put an END command at the end of the program. In TI-99/4A it is not necessary to enter an EN D command, but it is usually a good idea to do so. As we get into more advanced topics, we will see that our program can jump around, and the place we want it to END will be in the middle. We will need an EN D statement so that it will not crash into an area we don't want it to go. So, while an EN D command really has not been necessary up to now, it is nevertheless a good habit to develop. Let's soup up our program a little more with the INPUT state

ment. NOTE: To makethingssimple, enter NUMBER10, 10

before you begin thisprogram where indicated after K^ NEW . When you have finished entering yourpro gram, just hit when the next line number appears. NEW

NUMBER 10,10 10 CALL CLEAR

20 PRINT "ENTER YOUR NAME ->"; 30 INPUT NAMES 40 PRINT "ENTER YOUR AGE ->"; 50 INPUT AGE

^

60 PRINT " TO CONTINUE"; 70 INPUT ENTERS

W W

80 CALL CLEAR 90 PRINT NAMES; " IS"; AGE ; "YEARS OLD." 100 REM BE CAREFUL WHERE YOU PUT YOUR QUOTE MARKS AND SEMI-COLONS IN THIS LINE

W \^0/

110END

Now we're getting somewhere. You can enter information as numeric or string variables and the OUTPUT is formatted so you know what's going on. As your programs become larger and more complicated, it is very important to connect your

string variables and numericvariables in such a way that it is easy to see what the numbers on the screen mean. Let's face it, a computer wouldn't be very helpful if it filled the screen with numbers and you did not know what they meant! Lines 60 and 70 contain the format for a pause in your program. ENTERS doesn't hold any information, but since INPUT statements

expect somethingfrom the keyboard and avariable, ENTERS (for ENTER) is as good as any.

69

\j(gji/

READIng in DATA A second way to enter data into a program is with READ and DATA statements. However, instead of entering the data through the keyboard, DATA in one part of the program is

W

W

READ in from another part. Each READ statement looks at

elements in DATA statements sequentially. The READ com-

^

mand is associated with a variable which looks at the next

DATA statementand places thenumeric value orstringinthe variable. Let's look at the following example: NOTE: I'm not going to remind you to use NUMBER 10,10 this

^ Vj^p/

time! NEW

Sj^j/

10 CALL CLEAR

20 READ NAMES

^

30 REM READS NAME

40 READ JOBS

w

50 REM READS OCCUPATION

60 READ ADDRESS

W

70 REM READS STREET NUMBER 80 READ STREETS 90 REM READS STREET NAME

W

100 READ CITYS

W

110 REM READS CITY %a/

120 READ STATES 130 140 150 160

REM READS STATE READ ZIP

REM READS ZIP CODE PRINT

Vs^p/

170 PRINT

;

180 PRINT

190 REM BEGIN PRINTING OUT WHAT 'READ*

w

READ IN.

200 REM (BE CAREFUL TO PUT IN EVERYTHING 210 REM EXACTLY AS IT IS LISTED.)

^)

220 PRINT NAMES

W

230 PRINT JOBS

240 PRINT ADDRESS; STREETS

W

250 PRINT CITYS; "."; STATESS ; ZIP 260 END

W ^ss^

70 \^/

Sjjjjgnj?'

1000 DATA DAVID GORDON, PUBLISHING TYCOON, 8943, FULLBRIGHTAVE 1010 DATA CHATSWORTH, CALIFORNIA, 91311

In the DATA statements there is a comma separating the various elements, unless the DATA statement is at the end of a line. If you have one of the elements out of place or omit a com

ma, strange things can happen. For example if the READ statement is expecting a numeric variable (such as the street address) and runs into a string (such as the street name) you will get an error message. Think of the DATA statements as a stack of strings and numbers. Each time a R EAD statement is encountered in the program the first element of the DATA is removed from the stack. The next READ statement looks at

the element on top of the stack, moving from left to right. Go ahead and SAVE this program and let's put an error in it. (SAVE it first, though, so you will have a correct listing of how READ and DATA statements work.)

Siijp/'

Vlipi'

S^ij^i/

Sjijjjifc/

%^

w&

mmm



Sjjjj^/

71 %$)/

Vugjjjjijj/

LIST the program to make sure you have it in memory and

enter the following line:

w \a^0f

145 READEXS

Now RUN the program and you should get a * DATA ERROR IN 145. The error occurred because you have a READ statement without enough DATA statements (or elements); so, be sure that 1) there are enough elements in your DATA statements to take care of your READ statements, and 2) the variables in your READ statements are compatible with the elements of the DATA statements. (i.e., Your numeric vari

W

W W

ables read numbers and string variables read strings.) To ^ repair your program, simply type in 1020 DATA WORD

This will give it something to READ.(Of course you could have DELETEd line 145).

s^jy

If an element is a DATA statement (and is enclosed in quota

tion marks), all the characters inside the quotes are con- ^ sidered to be a single string element. For example, make the following changes in your program and RUN it.

^

255 PRINT EX$ 1020 DATA "10 DOWNING ST,

W

LONDON, 45, ENGLAND"

W

Both numbers and commas were happily accepted by a READ statement with a string variable since they were all enclosed

^

inquotation marks. Now remove the quote marks and RUNit ^ again. This time it printed only up to the first comma, '10

,

DOWNING ST but the stringvariable EX$ hadnoproblem w accepting a numeric character! (However, since it read the

>

'10' as a string, it cannot be used in a mathematical opera

tion.) Experiment with different elements inthe DATA state- ^ ments to see what happens. Also, just for fun, put the DATA

statements at different places in the program. Youwillquickly

^

find that they can go anywhere and are R EAD in the order of placement in the program.

^ Vjjjgji/

72

Vij^/ S^giS/

i

130 REM VARIABLE FOR CHECK 140 BALANCE - BALANCE - CHECK

w

150 REM KEEPS A RUNNING BALANCE

W

170 REM TOP OF LOOP

160 NEXT I

180 CALL CLEAR

W

190 REM CLEAR SCREEN WHEN ALL CHECKS ARE ENTERED

W

200 PRINT "YOU NOW HAVE $"; BALANCE ; "IN YOUR ACCOUNT"

W

210 PRINT

w

220 PRINT "THANK YOU AND COME AGAIN" 230 END

W W

^

Our checkbook program is coming along, making it easier to use, and that is the purpose of computers. Notice what we did with formatting in line 30. To get the space between CHECKBOOK and the rest of the program we put in four commas. This worked like entering an extra line and a PRINT statement. It saved some programming and did what we wanted. Now let's look at something else with loops.

NESTED LOOPS

^

With certain applications, it is going to be necessary to have one or more FOR/NEXT loops working inside one another. Let's look at a simple application. Suppose you had two teams

w

with 10 members on each team. You want to make a team

W

roster indicating the team number (#1 or #2) and member number (# 1 through #10). Using a nested loop, we can do this in the following program:

'Siiijgt/

NEW 10 CALL CLEAR

w

20 FOR TEAM = 1 TO 2

Vjflflffitt/

30 REM TEAM FOR TEAM # 40 FOR PLAYER =1 TO 10 50 REM PLAYER FOR MEMBER #

W

60 PRINT "TEAM #" ; TEAM ; "PLAYER #"; PLAYER

W'

73

VSSgji/

70 NEXT PLAYER 80 PRINT

90 NEXT TEAM Vi^p/

100 END Vjjjjgj/

In using nested loops, it is important to keep the loops straight. The innermost loop (the PLAYER loop in our example) must not have any other FO R or N EXT statement inside of it. Think of nested loops as a series of fish eating one another, the largest fish's mouth encompassing the next largest and so

Ss&fe^

forth on down to the smallest fish.

V*jgii/

I /

Look at the following structure of nested loops: FORA=1 TON

FORB-1 TON FORC=1 TON

FOR D = 1 TO N NEXTD NEXTC NEXTB NEXT A

74

w

Looping With FOR/NEXT

W

The FOR/N EXT loop is one of the most useful operations in BASIC programming. It allows the user to instruct the confl

ow puter to gothrough a determinednumberofsteps, at variable increments if desired, and execute them until the total number

w

of steps is completed. Let's look at a simple example to get started.

W

NEW 10 CALL CLEAR

^

20 NAMES = "" 30 FOR 1 = 1 TO 10 40 REM BEGINNING OF LOOP

50 PRINT NAMES 60 NEXT I 70 REM LOOP TERMINAL 80 END

Now RUN the program and you will see your name printed 10 times along the left side of the screen. That's nice, but so what? OK, not too impressive, but we will see how useful this can be in a bit. First let's look at another simple illustration to show

what's happening to "I" as the loop is being executed.

,

NEW

10 CALL CLEAR

t

20 FOR 1 = 1 TO 10

w

40 NEXT I

30 PRINT I

W W Sung/

\Hjj/

Wag/

As we can see when the program is RUN, the value of "I" changes each time the program proceeds through the loop. Think of a loop as a child on a merry-go-round. Each time the merry-go-round completes a revolution, the child gets a gold ring, beginning with one and ending, in our example, with 10.

7h

\jg|BJ|/

TRIVIA

As you begin looking at more and more programs, you will see that the variable I is used in FO R/N EXT loops a lot. Actually, you can use any variable you want, but the I keeps cropping up. Like yourself, I was most curious as to why programmers kept using the letter I, and after several moments of exhaustive research I found out. The

Iwas the "integer" variable in FORTRAN (an early com puter language), and it was used in "DO loops" since it was faster. The I also can be interpreted to stand for "increment." I told you it was trivia.

Having seen how loops function, let's do something practical with a loop. We'll fix up our CHECKBOOK program we've been playing with.

\^j/

w

In our souped up CHECKBOOK program, we are going to use

variables inmany ways. First, ourFOR/NEXT loop will usea

W

variable. We'll stick with tradition and use I. Second, we will

use a variable to indicate the number of loops to be executed. We will use N as our "counter" variable. Third, we will use variables for the balance, the amount of the check and the new

,

balance. This program is going to be a little longer; so be sure

j

to SAVE it to disk every five lines or so. For cassette, SAVE it about every 10 lines.

,

NEW

W

10 CALL CLEAR

20 CBS = "CHECKBOOK"

W

30 PRINT CB$,,,, 40 PRINT "HOW MANY CHECKS->";

W

50 INPUT N

60 PRINT "YOUR CURRENT BALANCE ->" ;

W

70 INPUT BALANCE

80 REM BEGIN LOOP

^

90 FOR I = 1 TO N

100 PRINT "BALANCE NOW=$";BALANCE

W

110 PRINT "AMOUNT OF CHECK #";l; "->";

120 INPUT CHECK

W

76

,

w

Note how each loop begins (a FO R statement is executed) and is terminated (encounters a NEXT statement) in a "nested"

sequence. If you have ever stacked a set of different sized cooking bowls, each one fits inside the other; that is because the outer edge of one is larger than the next one. Likewise, in nested loops, the "edge" of each loop is "larger" than the one inside it and "smaller" than the one it is inside.

Stepping Forward and Backwards Loops can go one step at a time, as we have been using, or they can step at different increments. For example the following program "steps" by 10. NEW

10 CALL CLEAR

20 FOR I = 10 TO 100 STEP 10 30 PRINT I 40 NEXT I

W W W

This allows you to increment your count by whatever you want. You can even use variables or anything else that has a numeric value. For example NEW

10 CALL CLEAR

W'

20 K = 5

w

40 FOR I = K TO N STEP K

30 N = 25

\^0/

50 PRINT I 60 NEXT I

Go ahead and RUN the program.

It is also possible to go backwards. Try this program: NEW

W

10 FOR I = 4 TO 1 STEP-1

W

30 NEXT I

20 PRINT I

Sjj^/

Vsgg/

Vans/

Nana/

As we get into more and more sophisticated (and useful) pro grams, we will begin to see how all of these different features of TI-99/4A BASIC are very useful. Often, you may not see the practicality of a command initially, but when you need it later on, you will wonder how you could program without it!

IN CASE YOU WONDERED

You may have noticed that the lines inside the loops were indented. If you tried that on your TI-99/4A you prob ably found that as soon as you LISTed your program, all the indentations were gone. Unfortunately, that will happen, and without special utilities, there's nothing you can do about it. However, don't worry about it. It is a pro gramming convention for clarity to indent or tab loops to make it easier to understand what the program is doing. It does not affect your program at all.

78 Sjgp/

Counters

Often you will want to count the number of times a loop is executed and keep a record of it in your program for later use. For example, if you run a program that loops with a ST EP of 3, you may not know exactly how many times the loop will execute. To find out, programmers use "counters", variables which are incremented, usually by +1, each time a loop is executed. The following program illustrates the use of a counter: NEW 10 CALL CLEAR

20 FOR I = 3 TO 99 STEP 3 30 PRINT I 40 N = N + 1

50 REM LINE 40 IS THE COUNTER 60 NEXT I

70 PRINT

80 PRINT "LOOP EXECUTED"; N; "TIMES." 90 END

tin %~& &§®

\asjjgay'

79

The first time the loop was entered, the value of N was 0, but when the program got to line 40, the value of 1 was added to N to make it 1 (i.e., 0 = 1 = 1). The second time through the loop, the value of N began at 1, then 1 was added, and at the top of the loop, line 50, the value of N was 2. This went on until the program exited the loop. Then, after all the looping was finished, presto! Your N told you how many times the loop was executed. Of course, counters are not restricted to counting

W W

Sijjjgjjs'

'

loops, and they can be incremented by any value you need,

including other variables. For example, change line 40 to

^

read: Vials/

40N = N + (I*2)

RUN your program again and your "counter total" will be a good deal higher.

SUMMARY This chapter has begun to show you the power of your com puter, and we have really begun programming. One of the most important concepts we have covered is that of the "vari able." The significant feature of variables is that they vary (change depending on what your program does). This is true not only with numeric variables, but also with string variables.

\s^/

The various input commands show how we enter values or

^

strings into variables depending on what we want the com puter to compute for us. Finally, we have learned how to loop.

\#§g?

i

This allows us, with a minimal amount of effort, to tell the com

puter to go through a process several times with a single set of instructions. With loops, we can set the parameters of an operation at any increment we want and then sit back and let our TI-99A/4A's go to work for us.

W

^)

However, our programming has just begun! In the next chap

ter we willbegin getting into morecommands and operations

^

which allow us to delve deeper into the TI-99A/4A's capabili

ties and make our programming jobs easier. The more commands we know the less work it is to write a program.

^ \jigii>/

80 v^gj/

CHAPTER 4

Vane/

Branching Out introduction

^ w

W

In this chapter we will begin exploring new programming con structs that will geometrically increase your programming ability. We will be examining some more sophisticated techniques but, by taking each one step at a time, you will begin using them with ease. Later, when you are developing your own programs, be bold and try out new commands. One prob lem new programmers have is a tendency to stick with the sim-

pie commands they have learned to get a job done. After all, why use "complicated" commands to do what simpler ones can do. Well, the answer to that has to do with simplicity. If one "complicated" command can do the work of 10 "simple" commands, which one is actually simpler? As you get into more and more sophisticated programming applications, your programs become longer and subject to more bugs. The more commands you have to sift through, the more difficult it is to

find the bugs; therefore, while it is perfectly OKto write a long

i^,

program using a lot of simple commands while you're learn

^

more advanced commands.

^

Related to this issue of maximizing your knowledge of different commands is that of letting the computer perform the

ing, begin thinking about short-cuts through the use of the

W W

W

computing. This may sound strange at first, but often novices will figure everything out for the computer and use it as a glorified calculator. In the last chapter you may remember we set up a counter to count the times a loop was executed when we used a STEP 3 loop. We could have figured out how many loops were executed instead of letting the computer do it with the counter, but that would have defeated the purpose of pro-

^

gramming! So, asyou learn new commands, see how they can

w

yourself.

be used to perform the calculations you had to work out

81

BRANCHING

w

So far all of our programs have gone straight from the top to

^

the bottom with the exception of loops. However, if our TI-

99A/4Aisto dosome real decision making, wemusthavesome way of giving it options. When a program leaves a straight path, it is referred to as either "looping" or "branching." We already know the purpose of a loop, but what is a branch? Well, using the IF/TH EN commands, we will see. Consider the following program: NOTE: By now you shouldknow enough to

clear memory with a NEW command, so I won't keep on insulting your intelligence byputting them at the beginning ofeachprogram.

^ \i^y

\^gr

^

10 CALL CLEAR

20 PRINT "CHOOSE ONE OF THE" 30 PRINT "FOLLOWING BY NUMBER:" 40 PRINT

\^y

50 PRINT "1. BANANAS"

60 PRINT "2. ORANGES" 70 PRINT "3. PEACHES"

80 PRINT "4. WATERMELONS"

^

90 PRINT,.,, "WHICH";

100 INPUT X

^

110 CALL CLEAR

120 IF X=1 THEN 200

vj

130 IF X = 2 THEN 300

140 IF X = 3 THEN 400

W

150 IF X = 4 THEN 500

160 GOTO 10

***

170 REM LINE 160 IS A TRAP" TO MAKE SURE THE

USER CHOOSES 1, 2, 3, OR 4

^

200 PRINT "BANANAS" Vjjjjjgj/

210 END

300 PRINT "ORANGES" 310 END

400 PRINT "PEACHES" 410 END

500 PRINT "WATERMELONS" 510END

w

W W w

As you can see, your computer "branched" to the appropriate place, did what it was told and ENDed. Not very inspiring I admit, but it is a clear example. Now let's try something a little more practical for your kids to play with in their math homework.

10 CALL CLEAR

w

20 AG$="ADDITION GAME" 30 PRINT AGS 40 PRINT 50 PRINT

60 PRINT "FIRST NUMBER -->" ; 70 INPUT A

80 PRINT "SECOND NUMBER->" ;

^

90 INPUT B

W

100 PRINT "WHAT IS"; A ; "+" ; B ; 110INPUTC 120IFC = A+BTHEN200

W

130 PRINT 140 PRINT "THAT'S NOT QUITE IT."

W

150 PR INT "TRY AGAIN." 160 PRINT

****

170 GOTO 100 200 PRINT "THAT'S RIGHT!" 210 PRINT "VERY GOOD" 220 PRINT

230 PRINT "MORE (Y/N)"; 240 INPUT AN$ 250 IF AN$="N" THEN 300 260 IF AN$ = "Y" THEN 270 300 CALL CLEAR

^

310 PRINT,,,, 320 PRINT "HOPE TO SEE YOU AGAIN SOON"

W

330 END

As you can see, the more commands we learn, the more fun we can have. Just for fun, change the program so that it will han dle multiplication, division, and subtraction.

WHAT'S IN A NAME?

Kids (of all ages) like to have their names displayed. See if you can change the above program so that it asks the child's name; then when the program responds with either a correction or affirmation command, it mentions

the child's name. (e.g. THAT'S RIGHT! VERY GOOD, SAM ). Use NA$ as the name variable. \^[/

IF/THEN/ELSE Another aspect of TI BASIC is in choosing between two branches. This can be done by adding the ELSE statement to our IF/THEN statements. For example, let's look at the following simple program to see how this works: 10 CALL CLEAR

w

20 PRINT "PRESS TO CONTINUE"

30 INPUT "OR'Q'TO QUIT" :AN$

W

40 IF AN$ = "Q" THEN 100 ELSE 200

50 PRINT "YOU CAN'T GET HERE!!!" 100 REM****

,

W • \

110 REM QUIT

120 REM****

w

130 PRINT "YOU CHOSE TO END IT ALL"

140 END

W

200 REM ********

210 REM CONTINUE

^

220 REM ********

230 PRINT "YOU CHOSE TO CONTINUE"

W

240 PRINT

250 GOTO 20

^

Obviously there are easier ways to do that, but it is important that you see how IF/TH EN/E LSE works. You might note that no matter what you do, you will not get to Line 50. (Well, you can change the program, but that's not cricket.)

\0 PRINT*DO WV UJ/MT TO COmitJuB THE

PATH Of SltJ fyhiD PERDITION?" ip INPUT AN4 F

;;

AN* - N THEM

85

RELATIONALS

w

So far we have used only "=" to determine whether or not our

^

program should branch. However, there are other states,

referred to as "relationals," that we can also query. The

^

following is a complete list of the relationals we can employ: MBOL =




>= BTHEN 100 70IFA= 21 THEN 200 50 CALL CLEAR 60 PRINT

70 PRINT "SORRY, YOU'VE GOT" 80 PRINT "TO BE 21 OR OLDER 90 PRINT "TO COME IN HERE!" 100 END 200 CALL CLEAR 210 PRINT 220 PRINT "WHAT WOULD YOU LIKE?"

yam/

OK, you have the idea how relationals can be used with IF/ THEN statements; note they work with strings as well as numeric variables. However, there is another way to use relationals. Try the following from the Immediate mode: A=10 B = 20 PRINT A=B

87

Your computer responded with a 0, right? This is a logical operation. If a condition is false, your TI-99A/4A responds with a 0, but if it is true, it responds with a -1. Now try the following little program.

^

W

10 CALL CLEAR

20 A =10

^

30B=20

40 C = A > B

w

50 PRINT C

When you RUN the program, you again get a 0. This is because the variable C was defined as A being greater than B. Since A was less than B, the variable C was 0 or "false." Now,

let's take it a step further: 10 CALL CLEAR

20 A = 10

W

30 B = 20

40 C = A > B

W

50IFC = 0THEN100

50 PRINT "A IS GREATER THAN B"

W

60 END

100 PRINT "A IS LESS THAN B"

^

Later, we will seefurther applications ofthese logical opera- ^ tions of the TI-99A/4A. For now though, it is important to understand that a true condition is represented by a -1 and a false condition by a 0. Subroutines

Often in programming there is some operation you will want your computer to perform at several different places in the program. You can either repeat the instructions again and again or use GOTOs all over the place to return to your original spot after branching to the operation. On the other hand, you can set up "subroutines" and jump to them using G0 S UB and get back to your starting point using the RETURN statement. Up to a point the G0 S U B statement works pretty much like the GOTO statement since it sends your program

gg

^ ^ w W

W

\HHs/

bouncing off to a line out of sequence. Also, the RETURN statement is something like GOTO since it also sends your

program to an out-of-sequence line. However, the GOSUB/ RETURN pair is unique in what it does. Let's take a look at a simple example to see how it works: 10 CALL CLEAR 20 A$ = "HELLO" 30 GOSUB 100

40 A$ = "HOW ARE YOU TODAY?" 50 GOSUB 100

60A$ = TM FINE" 70 GOSUB 100

80 END

100 PRINT A$ 110 RETURN

vjnmr-'-.

89

Our example shows that a GOSUB statement works exactly like a statement on the line itself except that it is executed elsewhere in the program. The R ETU R N statement brings it back to the next statement after the GOSUB statement.

Using the GOSUB/RETURN pair, it is much easier to weave in and out of a program than using GOTO since the R ETU R N automatically takes you back to the jump-off point. To better illustrate the usefulness of GOSUB, let's change line 100 to something more elaborate. Try the following.

NO TE: We will begettingahead ofourselves a bit withthisexam

ple, but thefollowing is meant to illustrate something very useful in GOSUBj.

100L=LEN(A$]/2 110 PRINT TAB(11 - L);A$ 120 RETURN

Now when you R UN the program, all of your strings are cen tered. As you can see, a single routine handled all of the cen tering and, instead of having to rewrite the routine every time you want a string centered, you just used a GOS UBto line 100. NEATNESS COUNTS

We really have not discussed the structure of programs too much up to this point. In part, this is because we have not really had the need to do so. As our instruction set grows, so too does the possibility for errors, and by now if you haven't made an error you haven't been keying in these programs! One way to minimize errors, especially using GOSU Bs, is to organize them into coherent blocks. Basically, a "block" is a subroutine within a range of lines. For example, you might block your subroutines by 100 s or 1000s, depending on how long the subroutines are; thus, you might have subroutines beginning at lines 50 0,60 0 and 70 0. It doesn't matter if the subroutine is 1 line or 10 lines; as long as it is confined to the block, it is easier to debug, easier for others and easier for you to understand what is happening in the program. In general it is just a good programming practice.

90

Sjljjjjg/

Nags!/

w

Computed GOTO and GOSUB

W

Now we're going to get a little fancier, but in the long run, it

W

will result in clearer and simpler programming. As we have seen, we can branch on a "conditional" (e.g., IF A = 1 THEN 200). The easier way to make a conditional jump is to use

"computed" branches using the 0 N statement. While we're at it, why not save some time INPUT ing values.We can have our prompt on the same line as our INPUT statement. Look at ,

lines 20 and 60 in the next program. The IN PUT variable is

separated from the prompt message by a colon.Using this for mat, we can save the extra line every time we use INPUT. Now

w

let's look at an example usingboth computed GOSUBs and

l

our new INPUT format.

\^>

\m^S

10 CALL CLEAR 20 INPUT "A NO. FROM 1 -5":A 30 IF A < 1 THEN 20 40 IF A> 5 THEN 20

\i|^/

50 ON A GOSUB 100,200,300,400,500

60 INPUT "CONTINUE? (Y/N)" : AN$ \jgpt

^^/

\$§&/

70 IF AN$ = "" THEN 60 80 IF AN$ < > "Y" THEN 1000 90 GOTO 10 100 PRINT "ONE" 110 PRINT

120 RETURN Njjta^

200 PRINT "TWO" %$p/

210 PRINT

220 RETURN \^gg/

300 PRINT "THREE" 310 PRINT

= 100 THEN 200

W W

50 ON B GOSUB 1000, 2000, 3000

60 REM COMPUTED GOSUB ON 'B' VARIABLE IN

w

LINE 50

70 INPUT "PRESS TO CONTINUE":

"**'

ENTERS

80 IF ENTERS = "QUIT" THEN 5000

^

90 GOTO 10 NiiJSjjjjj/

100 B=1

110 GOTO 50THAN 200 " 200 IF A >= 200 THEN 300 210B = 2

\jgj/

\ai«^i/

220 GOTO 50

300 B = 3

^

310 GOTO 50

1000 PRINT "LITTLE"

W

1010 RETURN

2000 PRINT "MEDIUM"

W

2010 RETURN

3000 PRINT "BIG"

"^

3010 RETURN

5000 END

w

92 \^/

RUN the program and enter any number you want. Since the program is branching on the variable B and not on A (the INPUT variable), you will not get an error since the greatest value of B can only be 3.

Now let's get back to relationals and see how they can be used with computed GOSU Bs. Remember, in using relationals, the only numbers we get are 0's and 1 's for false and true respec tively. However, we can use these 0's and 1 's just like regular numbers. Try the following: W

10 CALL CLEAR 20X=1

^

30 Y = 2 40 Z = 3

W

50 A = XZ

W

70 C = Z>X

,

SOPRINV'A + A^A + A

W

90 PRINT

,

100PRINT"A+B=n ; A+B 110 PRINT

^

120PRINT"A + B + C="; A+B + C 130 END

Now, before you RUN the program, see if you can determine what will be printed by lines 60, 70 and 80. Once you have made a determination, RUN the program and see what hap pens. Go ahead and do it. How'd you do? Let's go over it step by step.

*w

1. Since X is less than Z, A will be "true" with a value of one (-1). Therefore A + A (-1 + -1) will equal -2. 2. Since Y is not less than Z, (Y = 2 and Z = 3, remem-

W

W

W W

^m/

ber) B will be "false" with a value of 0. Therefore, A + B (-1 + 0) will total -1.

3. Since Z is greater than X, C will be "true" with a value of -1. Therefore A + B + C (-1 + 0 + -1) will equal -2. If you got it right, congratulations! If not, go over it again. Remember, very simple things are happening, and so don't look for a complicated explanation!

93

Now that we see how we can get numbers by manipulating relationals, let's use them in computed GOSUBs. The follow ing program shows how: 10 CALL CLEAR

20 INPUT "HOW BIG WAS THE CROWD":SIZE

30 R = 1 + (SIZE>=500) + (SIZE>=1000) 40 IF $=0 THEN 1000 50 IF R = -1 THEN 2000

60 ON R GOSUB 100,200,300 70 INPUT "PRESS OR 'Q' ":AN$

80 IF AN$ "Q" THEN 20 90 END 100 PRINT "SMALL" 110 RETURN

200 PRINT "MEDIUM" 210 RETURN

300 PRINT "HUGE" 310 RETURN 1000 R = 2

1010 GOTO 60 2000 R = 3 2010 GOTO 60

This program is hinged on line 30's formula or algorithm. Let's see how it works:

1. There are three conditions:

^

w'

a. SIZE is less than 500

b. SIZE is 500 or more but less than 1000

w

c. SIZE is 1000 or greater.

,

2. If the first condition exists, both SIZE >= 500 and SIZE >= 1000 would be false. Thus 1 + 0+0 = 1.

Therefore R-l. 3. If SIZE is >= 500 but less than 1000 then SIZE >=

_, ^

500 would be true but SIZE >= 1000 would be false.

Thus we would have 1 + (-1) + 0 = 0. Convert the

^

value of R to 2.

Vaigs/

4. Finally if SIZE is both >=500 and >=1000 then our formula would result in 1 + (-1) + (-1) = -1. Convert the value of R to 3.

REST AREA

At this point let's take a little rest and reflection. In pro

gramming, there is no such thing as the right way and the wrong way. Certain programs are more efficient, faster or take less code and memory than others, but the computer makes no moral judgments. If a program does what you want it to do, no matter how slowly it does it or how long

it took you to write it, it is right. In the above example we used an algorithm with relationals to do something we could have done with more code. Don't expect to use such

formulas right off the bat unless you have a strong back ground in math. If you're not used to using algorithms, don't expect to understand their full potential right away. The one we used is relatively simple, and you will find far more elaborate ones as you begin looking at more pro grams. The main point is to keep plugging ahead. With practice you will learn all kinds of little shortcuts and for mulas, but if you get stuck along the way, just keep on going. Remember, as long as you can get your program running the way you want it to, you're doing the right thing.

Strings and Relationals Vijjjji^

Before we leave our discussion of computed GOTOs and GOSUBs with relationals, let's take a look at how relationals

handle strings. Try the following : A$ = "A" B$ = "B" PRINT B$>A$

95

Surprised? In addition to comparing numeric variables, relationals can compare alphabetic string variables with "A"

^J

being the lowest and "Z" the highest. (Actually, any string

W

variables can be compared, but we will look at just the alpha

betic ones here.) So if we ask is B$ greater than A$, we get a

^

"-1" (true) since B$ was a B and A$ was an A. Now you might

be wondering what on earth you could possibly want to do

^

with this knowledge. Well, in sorting strings (like putting names in alphabetical order) such an operation is crucial. Later on we will show you a routine for sorting strings, but for now let's make a simple string sorter for sorting two strings. 10 CALL CLEAR

20 INPUT "WORD #1 -->": A$

w

30 INPUT "WORD #2 --> " : B$

40 PRINT,,,,

w

50IFA$< B$THEN 100 60 IF AS > B$ THEN 200

W

100 PRINT A$,,B$ 110END

^

200 PRINT B$,,A$ V^j§fi/

Just what you needed! A program that will arrange two words into alphabetical order! \Sgjg/

ARRAYS

The best way to think about arrays is as a kindofvariable. As

^

we have seen, we can name variables A, D$ , KK, Xl$ and so

forth. An array uses a single name with a number to differentiate different variables. Consider the following two lists, one using regular string variables and the other using a string

^

W

array:

STRING VARIABLES

STRING ARRAY

P$ = "PIG"

AM$(1) = "PIG"

C$ = "CHICKEN"

AM$(2) = "CHICKEN"

D$ = "DOG"

AM$(3) = "DOG"

H$ = "HORSE"

AM$(4) = "HORSE"

w ^ Viiiljljji/

\&0r

l^ Now if we PRINT H$ we'd get HORSE and if we PRINT

AM$(4] we'd also get H0 RSE. Likewise, we could use arrays

^

for numeric variables such as:

\jjjljjj/

A(1} = 1 \^/

Af21 = 2

A(3) = 3

W

A(4)= 4 etc.

Again, you may well ask, "So what? Why notuse justregular numeric or string variablesinstead of arrays?" Well, for one

thing itcan bealot easier tokeep track ofwhat you're doing in a program using arrays, and for another, it can save alot of time. Consider the following program for IN PUTtinga list of 10 names using a string array.

\l^f

10 CALL CLEAR

v|^/

20 FOR 1= 1 TO 10 30 PRINT "NAME*

40 INPUT NA$(I] ^in^/

50 NEXT I

60 FOR 1= 1 TO 10 \jigjj/

70 PRINT NA$(I] 80 NEXT I

\a^y

Now write a program that does the same thing using nonarray variables. It would take alotmore code to do so, but go aheadandtry it. Use the variables N0$ through N9$ forthe names just to see what it would take.

If you re-wrote the program, you would see how muchtime you saved using arrays, butbefore going onlet'stake acloser look at how the program worked with the FOR/NEXT loop W

and array variable:

Sugg/

1. The FOR/NEXT loop generated the numbers se-

,

quentially sothat the arraywould be the following: FOR 1= 1 TO 10

NA$(1) ":RA

80 INPUT "ROW #->":RO

W

90 INPUT "COL #->":CO

100 INPUT "NAME OF WINE:":WINE$

W

110WI$(RA,RO,CO) = WINE$

'.

120 NEXT I

200 REM *** ROUTINE FOR CHECKING CONTENTS

W

OF WINE CELLAR***

210 CALL CLEAR

^

220 INPUT "WHICH RACK # TO CHECK?":RR 230 FOR I = 1 TO 5

W

240 FOR J = 1 TO 5

250 IF WI$(RR,I,J] = "" THEN 400

260 PRINT"RACK #";RR;"ROW#";l;"COLUMN #";J

270 PRINT "CONTAINS";WI$(RR,l,J)

W

^

280 NEXT J

290 NEXT I

^

300 END

400 REM *** EMPTY SUBROUTINE ***

***

410 WI$(RR,I,J) = "EMPTY"

420 GOTO 260

,

W Vjjgjiii/

\^/

102

Nsafe^

Nowthatwas aprettylongprogram, butgo overitcarefullyto make sure you understand what it is doing. Again, let me

remind you thatall athree-dimensional array is, isavariable with a lot of numbers in parentheses.

SUMMARY

We covered a good deal in this chapter; if you understood everything, excellent! If you did not, don't worry; for with

W practice it will all become very clear. Whatever yourunder standing of the material, though, experiment with all the ^

statements. Be bold and daring with your computer's com

mands.Aslongas youhavea diskor cassette onwhichyoucan

w practice your skills, theworst thatcan happen isthatyou will \^^/

\ii^i/

erase a few programs!

Welearned that your TI-99/4A computer can compute! Using the IF/TH EN commands and relational we can give the com-

(^ puter the power of"decision making." Using subroutines itis

possible to branchat decision points to anywhere wewant in W ourprogram. Computed GOTOs and GOSU Bsallow the exe cution to move appropriately with a minimal amount of

W

programming.

W Finally, we examined array variables. Arrays allow us to enter values into sequentially arranged variables (or eleW ments). Using FO R/N EXT loops it is possible to quickly pro

^

gram multiple variables up to the limits of our DIMensions. Notonly do arraysassistusinkeeping variables orderly, they save a good deal of work as well.

In the next chapter we will begin working with commands that help arrange everythingfor us. As our programs become moreand moresophisticated, wewillneedto keep better track of what we're doing. By organizing our programs into small, manageable chunks, we can create clear, useful programs.

'\^/

103

CHAPTER 5

Organizing the Parts Introduction

Unless we organize, as we accumulate more and more infor-

W

mation, work, or just about anything else, things get confus-

-

ing. Good organization allows us to do more and to handle

W

more complex and larger problems. These principles hold with programming. As we learn more commands, we can do

^

more things; but the more wedo, themore likely weare to get tangled up and lost.

^

One oftheareasthat islikely tobethefirsttosufferfrom overflow is that of formatting output. Variables get mixed up,

W ,

arrays are misnumbered and the screen is a mess. In order to

handle thiskind ofproblem, we will deal extensively with text and stringformatting. Notonly will webe able to put things where we want them, but we will do it with style! The second major area of disorganization is I/O (INPUT/ OUTPUT). Part oftheproblem hastodo with formatting, but even moreelementaryis the problem oforganizingthe input and output so that data is properly analyzed. Data has to be connected to the propervariables and be subject to the correct computations. Thus, in addition to examining string format ting, we will also look at organizingdata manipulation.

r,

^ ^ W W

w

FORMATTING TEXT Sijgg/

In Chapter 1 we said that the TI-99/4A keyboard works in many ways likea typewriter. Onefeature of a typewriter is its abilityto set tabs sothat the usercanautomatically placetext a given number of spaces from the left margin. With your TI-

";

.-

99/4A, you can TAB almost like atypewriter. Before examin-

w

program uses everyvertical and horizontal position available:

^

ingthe TAB statement, let's look atyour screen. The following

10 CALL CLEAR 20H$="r \hujj/

30 FOR I = 1 TO 28 40 PRINT H$; 50 NEXT I

60 FOR I = 2 to 23 70 PRINT I 80 NEXT I 90 PRINT 24;

100 FOR l = 1 TO 2000 110 NEXT I

There are 28 horizontal positions and 24 vertical positions

where you canplace your text. Everything begins at the botW torn ofyourscreenand moves upward. Examine the program carefully to see what has been done to place the numbers w

where we did. First we used a string variable, H$, to lay out

^

Why not justhave PR INT 1; in line 40? Well, change thepro gram sothat line 40 is PRINT 1; and see what happens. Okay,

our horizontal positions. Why did we have to use a string?

w if you did so, you found that the number 1 takes up three i positions, since all numbers and numeric variables are pre-

^

cededand followed by a space.Strings,however, havenolead-

ing or following spaces, so they can be positioned directly adjacent to one another.

A second item to note in the program is in line 90. Instead of

W

having our loopin line 60 run up to 24,we ran it onlyto 23 and then added the 24 in line 90. This was done so that there was

W

not a "linefeed" after 24. We could not put a semi-colon after the PR INT I in line 70 or we would have horizontal placement

^

ofour text. Thus we ran our loopup to 23, PRI NTed24 with a

w

on the screen we had a "pause loop" in line 100. (This avoids the ** DONE ** message.)

semi-colon and avoided a line feed. Finally, to hold everything

TAB (N] is used within a PR INTstatement to place the next character N spaces from left margin. We are able to produce a vfpt/

^

vertical tab by using empty PRINT statements in loops. To see how this works, the following program will put an "X" right smack dab in the middle of your screen:

105 i

10 CALL CLEAR

20 INPUT "ENTER MESSAGE": MS$

W

30 PRINT

40 PRINT "HORIZONTAL POS."- H 50 PRINT

60 INPUT "VERTICAL POS.": V

70 NEXT PAUSE

v" ,

Now let's have a somefun with our commands. Here's a little program that willgive you an idea of how to place text within

W

your program.

v^

10 CALL CLEAR

W

20 INPUT "ENTER MESSAGE ": MS$ 30 PRINT

W

40 INPUT "HORIZONTAL POS. ": H

50 PRINT

^

60 INPUT "VERTICAL POS. ": V

70 CALL CLEAR 80 PRINT TAB(H); MS$;

W

90 FOR VER = 1 TO V

W

100 PRINT 110 NEXT VER

"

120 PRINT " TO CONTINUE"

W

130 INPUT"": A$

140 IF A$="" THEN 10

W

150 IF A$"Q" THEN 120 160 END

W

As youcan see, variablescan be used with formattingstatements. Thus, TAB(H) is read in the same way as TAB(10) or

^

TAB(15) or anyother number between 1 and28. (TAB (0) is

^

the same as TAB(l)). Using the above program, what do you think would happen if you entered "THIS IS A LONG

W

STRIN G", a HORIZONTAL placement of27 and a VERTICAL placement of23? Since themaximum TAB is 28 andthe

, W

maximum vertical placement is 24, the string (MS$) will go

overthe boundaries. Go ahead and try it to seewhat happens.

w

Infact, it would be a good idea to testthe limits ofTAB and

^

vertical placement with this program to get a clear under standing of their parameters.

^j

106

\^

Unraveling Strings

Ourdiscussion ofstringsuptothispointhas involved "whole" strings. That is,whatever wedefine a stringto be, nomatter

how long or short, can be considered a "whole" string. For example, if we define R$ as WALK then we can consider

^

WALK to be the whole of R$. Likewise, if we defined R$ as A VERY LONG AND WORDY MESSAGE , then A VERY LONG AND WORDY MESSAGE wouldbe the whole string of R$. There will be certain occasions when we want to use

w only part ofa stringortieseveral strings together. (When we getinto databaseprograms, we will find thistobevery impor

\^i^/

tant.) Also, there are applications wherewewill needto know

the length ofstrings, find the numeric values ofstrings and even change strings into numeric variables and back again. TRUST ME!

I hate to admit it, but when I first learned about the sub

string commands we are about to discuss I thought, "Boy, what a waste of time!" It was enough to get the simple material straight, but why in the world would anyone want to chop up strings and put them back together again? If you want onlya certain segment of a string, whynot simplydefineit interms ofthat segment? And if you want a longer string, then just define it to be longer! Those were my thoughts on the matter of string formatting. However,I havenowcometo the point where I find it very difficult to even conceive of programming without these powerful commands. So, trust me! String formatting commands are terrificlittle devices to have.If you do not see their applicability right away,you willas you begin writing more programs.

String Formatting We will divide our discussion of string formatting into four

parts: 1) Calculatingthe length of a string, 2) Locating parts ofstrings, 3) Changing strings to numeric variables and back again and 4) Tying strings together (concatenation).

\^/

JLU i

Calculating the LENgth of Strings

^

Sometimes itis necessary to calculatethe length ofastringfor ^J formatting output. Happily, your TI-99/4A is very good at -

telling you the length ofa particular string. By the command V PRINTLEN (A$), you will be given the number ofcharacters,

including spaces, your string has. Try the following little pro- ^ gram to see how this works:

10 CALL CLEAR 20 INPUT "NAME OF STRING " :A$

30 PRINT A$; " HAS "; LEN(A$); "CHARACTERS"

^

W

40 PRINT

50 INPUT "MORE?(Y/N)"; AN$

W

60IFAN$ = ""THEN50

.

70IFAN$ = "Y"THEN20 W Now to seea more practical application, wewill look at a mod- ^j ified version of the centering routine we used in the last chapter. w 10 CALL CLEAR

20 PRINT "ENTER A STRING LESS

W

THAN 28 CHARACTERS" 30 INPUT "->":S$

W

40 CALL CLEAR

50 L= 14 - LEN(S$)/2

^

60 PRINT TAB(L);S$

70 FOR 1= 1 TO 18

^

80 PRINT

90 NEXT I

100 PRINT "PRESS TO CONTINUE"

w

",

I^INPUT-'OR'a-TOQUIT'iAS 120 IF A$="" THEN 10

'",

130 IF A$ "Q" THEN 100 Sags/

Now that we can see how to compute the LENgth of a string and then use that LENgth to compute our tabbing, let's see how we can control the input with the LEN command. Sup

pose you want towrite aprogram that will print out mailing

labels butyour labels will hold only 15 characters. You wantto make sure all of yourentries are 15 or fewer characters long,

including spaces. To do this we will write a program that checksthe LENgth of a string before it is accepted. 10 CALL CLEAR

20 30 40 50

PRINT "ENTER A NAME LESS THAN 15" PRINT "CHARACTERS INCLUDING SPACES" INPUT "DO NOT USE COMMAS ": NAMES REM THE FOLLOWING LINE IS A TRAP

60 IF LEN (NAMES) > 15 THEN 200 70 PRINT

80 INPUT NAMES,,,,

90 INPUT "ANOTHER NAME?(Y/N)": ANS W W

100 IF ANS = "" THEN 90 110 IF ANS < > "Y" THEN 130 120 GOTO 10 130 END

^

^

200 REM 210 REM **ERROR ROUTINE** 220 REM 230 CALL CLEAR

w

240 PRINT "PLEASE USE 15" 250 PRINT "CHARACTERS OR LESS" ,,,,

W ^

^

260 GOTO 20 Break the rule!!! Goahead and enter a string of more than 15 charactersto see what happens. (If your computer gets snotty

with you, you can always re-program it. Ithelpstoremind itof thatfact periodically.) Iftheprogram was entered properly, it is impossible to enter a string of more than 15 characters.

From the above examples, youcan beginto seehowthe LEN command canbe useful in several ways.Therearemany other

ways that such commands can be employed to reduce pro

gramming time, clarify output and compute information. The key to understanding its usefulness is to experiment with it and see how other programmers use the samecommand.

109

Finding the SECSments of a String

,

Suppose you want touse a single string variable to describe W

three different conditions, such as POOR FAIR GOOD, but you want to use only part of that string to describe an out-

W

come. Using SEG$, it is possible to PRINT only that part of the string you want. For example, the following program lets W you use a single string to describe three different conditions: 10 CALL CLEAR

20 X$ ="POOR FAIR GOOD"

^

30 PRINT "HOW DO YOU FEEL?"

40 INPUT "

OOR AIR OOD" : F$

^

50 IF F$ = "" THEN 40

B0IFF$="P" THEN 100

^

70IFF$ = "F"THEN200

80IFF$ ="G"THEN300 100 PRINT SEG$[X$,1,41

,

W "',

110 GOTO 500

W

200 PRINT SEG$[X$,6,4)

w

210 GOTO 500

300 PRINT SEG$[X$,11,4)

W

500 REM

510 REM** CHOICE SUBROUTINE**

W

520 REM

530 PRINT,..,

540 INPUT "ANOTHER GO?(Y/N)" : CHOICES 550 IF CHOICES$="Y" THEN 10 60 IF CHOICES "N" THEN 530

grams there have been different ways tochoose tocontinue. This has

NOTE: You may havenoticedthatin the lastseveralexampleprobeen done to give you an idea ofvarious ways to "trap" branches.

^ W

Let's face it, it would have been easierand no less efficient to simply branch to a PRINT'GOOD' 'FAIR' or'POOR'. But no

W

matter, it was for purposes ofillustration and notoptimizing

W

program organization. Let's see what the new commands do.

To give you some immediate experience with these com

mands, try the following:

110

W

\%g/

,

W$ = "WHAT A MESS"

i

G$ = "BURLESQUE"

W

X$="A PLACE IN SPACEPRINT SEG$(X$,12.5); " "; SEG${X$.5,3)

W

PRINT SEG${W$.8.4) PRINT SEG$(G$.4.3)

\$0f

\^j/

w

Another trick with partial strings is to assign parts of one string to another string. For example: 10 CALL CLEAR 20 BIGS = "LONG LONG AGO AND FAR FAR AWAY"

W

30 LITTLES = SEG$(BIG$,11,3)

W

40 AWYS = SEG$[BIG$,27.4) 50 LGS = SEG$(BIG$,1.4) 60 PRINT,,,,

W

70 PRINT AWYS;" ";LG$;" ";LITTLE$ 80 REM BEFORE YOU RUN IT, SEE IF YOU

^

CAN GUESS THE MESSAGE.

\^g»-

For an interesting effect, try the following little program: W W

10 CALL CLEAR 20 INPUT "YOUR NAME-> ": NAS 30 CALL CLEAR

40 FOR I= LEN(NAS) TO 1 STEP -1

W

50 PRINT SEG$(NA$,I,1); 60 NEXT I

^

70 REM DELAY LOOP IN LINES 70-80 80 FOR 1= 1 TO 1000 90 NEXT I

100FORV=1 TO 11 110 PRINT 120 NEXT V

200 REM ** IN LINES 230-250 THE "K LOOP'

W

Vj^jjlip/

SLOWS IT DOWN FOR SLOW MOTION EFFECT ** 210 FOR I= 1 TO LEN(NAS) 220 PRINT SEG$(NAS, 1.1);

111

Vygjggj/

230 FOR K = 1 TO 50

240 NEXT K

,

W

250 NEXT I

,

300 FOR VT=1 TO 5 310 PRINT 320 NEXT VT

i

330 PRINT TAB(5); "AGAIN?(Y/N)";

W

340 INPUT ANS

350 IF ANS = "" THEN 330 360 IF ANS = "Y" THEN 10

Now you have probably been wondering ever since you got

your computer how to make it print your name backwards.

Well, now you know! (If yournameis BOB you probablydidn't notice itwas printed backwards-tryROBERT.) Actually, the above exercisedid acoupleofthings besides goofingoff. First itisademonstration ofhow loops and partial strings (or sub-

stnnp) can be used together for formatting output Second,

we showed how output could be slowed down for either an interesting effect or simply to give the user time to see

what s happening.

W

W

', j

J w

Changing strings to Numbers and Back Again Vagi/

Now we're going to learn about changing strings tonumbers

and numbers to strings. If you're like me, when I first found

out about these statements, I thought they were pretty use less. After all, ifyou want astringuse astringvariable, and if you want a number use a numeric variable. Simple enough,

^

^

butagain, once you understand their value, you wonder how you could do without them. To get started let's RUN the following program:

10 CALL CLEAR 20 FOR 1= 1 TO 5

,

30 READ NAS(I)

W

40 NEXT I

j

Sag/

50 FOR I = 1 TO 5

60L=LEN(NA$(I))

W

70 X(l) =VAL(SEG$(NA$(I).L,1)) 80 NEXT I

^ \$gy

112 \^p/

Vising

90 FOR I = 1 TO 5

w

100 PRINT "OVERTIME PAY= $"; X(l) * (1.5 * 7) 110 NEXT I 200 DATA SMITH 7. JONES 8. MCKNAP 6.

W

JOHNSON 2. KELLY 3

\g)gp/

Using DATA which were originally in a string format, we \^jg/

were ableto changea portion ofthat string arrayto a numeric array. By making such a conversion, we were ableto use our mathematical operations on line 100 to figure out the over timepayfor someone receivingtimeand ahalfat seven dollars ($7) anhour. Well, that's prettyinteresting, but we don'thave a list of who gotwhat andthe totalovertime paid! Why don't

you try it yourself. Change the program so that everyone's name appears withthe amount ofovertime each received and atotal overtimepaid. (Hint: You arelooking forthe substring SEG$ (NA$(I), LEN (NA$(l)-2)) since you wantto drop the numberandspaceaftereach name.) When youget it, write me a letter to show me how you figured it out. \$p/

^

It always helps to do a few immediate exercises with a new command to get the right feel, sotry these: AS = "123"

PRINT VAL(A$) + 11 Q$ = "99.5"

PRINT VAL(Q$) * 7 SALES - "44.95"

i

PRINT "ON SALE AT HALF PRICE ->$";

w

VAL(SALES) /2 DOS = "$103.88" DNS = "$18.34"

W

PRINT VAL (SEG$(D0$,2,4)) + VAL (SEG$(DN$,2,3))

\&&tojffi/

Note: Since you may want to SAVE the above examples on tape or disk, allyou have to do is to addline numbersand SAVEthem as lit tle programs.

'%mr'

113

Siijijjj/

From Numbers to Strings

All right, now let's go the other way.We saw why we might W want to change strings to numbers, but we may also want to change numbers to strings. To make the conversion we use the **>

STR$ command. For example, look at the following program: 10 CALL CLEAR

'**>

20 PRINT "ENTER A NUMBER"

30 PRINT "WITH 5 DIGITS AFTER"

^

40 INPUT "THE DECIMAL POINT': A V^/

50 A$=STR$(A) 60 PRINT

70 L = LEN(A$)

80 PRINT SEG$ (A$,1,L-3) As you can see, you have truncated the number to two decimal

points. Using substrings we can varythe sizeof strings, and byconvertingnumbers into stringvariables wecan effectively

v^

use the same commands on numbers and numeric variables.

W

Nowlet'sdo some inthe Immediate mode togettheideafirmly intoyourmind. A littlelaterwewill do something very practi-

W

cal with these commands.

A = 5.00

^W

A$ = STR$(A) PRINT A$ V=2345

W

V$ = STR$(V]

^

PRINT V$

BUCKS= 22.36

^

BUCKS$ = STR$(BUCKS)

PRINT "$"; SEG$[BUCKS$,4,2]

W

(Now the last example is a way to increase your bucks!) Remember these commands, and when you are dealing with

^

decimal points you will often find them handy.

w \qgjlj/

114 Vj^j/

\jgp/

Tying strings Together: concatenation

W

We haveseenhowwecantake aportion of astringand PRINT it to the screen. Now we will tie strings together. This is called CONCATENATION and is accomplished by using the "&" sign with strings. For example: 10 CALL CLEAR

w

20 INPUT "FIRST NAME ->": NFS 30 INPUT "LAST NAME ->": NL$ 40NA$ = NF$&NL$ 50 PRINT NA$

A little messy, huh? However, you can see how NF$ and NL$ weretied together into a singlelargerstring.Now changeline 40 to read

W

40 NA$=NF$ & " " & NL$

This time when you RUN the program, your name will turn out fine. Not only did we concatenate string variables, we also concatenated strings themselves. For example, it is perfectly all right to do the following: PRINT "ONE" & "ONE"

V§§»/

W

Now there isn't much you can do with ONEONE, but we can

see the principle of operation with concatenating strings. One of the problems with the way your TI-99/4 A formats num bers is that it drops 0's off the end. For example, try the following: Wigs/

PRINT 19.84 PRINT 5.00

In dealingwith dollars and cents, this canbe a real pain in the W

neck, and it doesn't look very good. So, using concatenation

^•^

that.

and our VAL and STR$ commands, let's see if we can fix

>^^/

115

10 CALL CLEAR

20 PRINT "BE SURE TO INCLUDE ALL CENTS"

^

30 PRINT

40 INPUT "AMOUNT SPENT?-> $" :S 50T=T + S

60T$ =STR$(T)

W

W

70 T$ = "000" & T$

,

80 REM THIS IS TO INSURE THAT LEN(TS) IS LONG ENOUGH 90L=LEN(T$)

;

100 IF SEG$ (T$, L- 1,1) = "." THEN 300

w

110 IF SEG$ (T$, L -2,1) < > 'V THEN 400 120 PRINT

^

130 PRINT"YOU HAVE SPENT $"; SEG$(T$, 4, L) 140 PRINT " TO CONTINUE" 150 INPUT "OR 'Q' TO QUIT" : R$ 1B0IFR$ = ,mTHEN 10

W

W

170IFR$ = "Q"THEN 190

180 GOTO 140

^

190 END

300 REM ***********

W

310 REM ADD A ZERO

320 REM ***********

330 T$ = T$ & "0" 340 GOTO 130 400 REM ************************

>*^ Vjgg/

410 REM ADD DECIMAL AND 2 ZEROS 420 REM ************************

SsSJi/

430 T$ = T$ & ".00" 440 GOTO 130

This may look pretty complicated, but let's break it down to see what has been done.

1. We entered numeric variables in line 40 and com puted their sum in line 50.

2. The sum represented by T was then converted to a string variable T$ in line 60.

3. In line 70 we "padded" T$ with three 0's to give it a minimum length we will need in lines 100 and 110.

116

" "." THEN 900

880 BA$ = SEG$ (BAS.1 .PLACE + 2)

^j

890 RETURN

900 PLACE = PLACE + 1

W

910 GOTO 870

920 BA$ = "0.00" 930 GOTO 890

W

^ W

W

Now we'll change a few lines in our program so that when there is anoutput of ourbalance, it willjump to the subroutine between lines 800 and 930 and then RETU R N to output BA$. The following lines in our COMPUTER CHECKBOOK program should be changed and/or added:

W

375 GOSUB 800

W

380 PRINT "YOU NOW HAVE $";BA$,,, 390 INPUT "MORE DEPOSITS? [Y/N]": AN$ 580 PRINT "YOU NOW HAVE $"; BA$ 780 PRINT "BALANCE OF $"; BA$ 790 END

VjjJUj^

Now, if you put everything together properly, you shouldhave a handy little program forworking with your checkbook.Just to make sure you got everything, here's the complete program with all the subroutines and changes we made: 10 CALL CLEAR

W

20 REM #################### 30 REM HEADER & INPUT BLOCK

W

40 REM ####################

*"•"

60L=14-LEN(CB$)/2

50 CBS = "=COMPUTER CHECKBOOK="

70 PRINTTAB(L); CBS

km>*

80 FOR V = 1 TO 4 90 PRINT

100 NEXT V

,

110 INPUT "CURRENT BALANCE=> $":BA 120 PRINT "1. ENTER DEPOSITS" 130 PRINT"2. DEDUCT CHECKS"

W

140 PRINT "3. EXIT"

w

150 FOR V=1 TO 7 160 PRINT 170 NEXT V

\jjjjjmjj/

180 INPUT" CHOOSE BY NUMBER :A 190 REM ## TRAP IN LINES 200-210 ##

W

200 IF A> 3 THEN 180 210 IF A < 1 THEN 180 220 ON A GOTO 300,500,700

^

300 REM #######

W

123

310 REM DEPOSITS 320 REM #######

Vsggiir

330 CALL CLEAR

^J

340 INPUT "AMOUNT OF DEPOSIT $":DP 350 REM RUNNING BALANCE IN 360

\*J

360BA=BA+DP 370 PRINT 375 GOSUB 800

W

380 PRINT "YOU NOW HAVE $"; BA$ 390 INPUT "MORE DEPOSITS? (Y/N) : AN$

^

400 IF AN$ = "Y" THEN 340

w

410 PRINT



420 INPUT "DEDUCT CHECKS? (Y/N) :AN$

W

430 IF ANS = "N" THEN 700 440 IF ANS = "Y" THEN 500 450 CALL CLEAR 460 GOTO 390

500 REM ######

^j

510 REM CHECKS

520 REM ######

w

530 CALL CLEAR

540 INPUT "AMOUNT OF CHECK $":CK 550 REM ## RUNNING BALANCE IN 560 ## 560BA=BA-CK 570 PRINT,,,,

W

575 GOSUB 800

^

W

580 PRINT "YOU NOW HAVE $"; BA$

590 PRINT 600 PRINT "MORE CHECKS? (Y/N)"

w

610 INPUT " 'Q* TO QUIT": ANS 620 IF ANS = "Y" THEN 540 630 IF ANS = "Q" THEN 700 640 PRINT

650 INPUT "ANY DEPOSITS? (Y/N)": ADS 660 IF ADS = "Y" THEN 300

^

670 GOTO 600

700 REM #################

^

710 REM TERMINATION BLOCK 720 REM #################

w

730 CALL CLEAR

740 FOR T = 1 TO (10 * 28)

1 QA

W

\^/

750 PRINT "$"; 760 NEXT T

770 PRINT "YOU NOW HAVE A" 780 PRINT "BALANCE OF $"; BA$ 790 END

800 REM ###########

810 REM FORMAT OUTPUT 820 REM ########### 830 BA = BA + .001 840 PLACE = 1

850 BA$ = STR$ (BA) 860 IF BA < .01 THEN 920

870 IF SEG$ (BA$,PLACE,1 ]< > "." THEN 900 880 BA$ = SEG$ (BA$,1 .PLACE + 2] 890 900 910 920 930

RETURN PLACE = PLACE + 1 GOTO 870 BA$ = "0.00" GOTO 890

N||g^

Scroll Control!

^

Oneof the big problemsin output occurswhen you have long

*w

lists that will scroll right off the screen. For example, the output of the following program will kick the output right out the top of the screen: 10 CALL CLEAR

W

20 FOR 1= 1 TO 100

^

40 NEXT I

30 PRINT I

Instead ofnumbers, supposeyouhave a list ofnames you have sorted or someother output youwanted to see beforeit zipped off the top of the screen. Depending on the desired output, screen format and so forth there are several different ways to control the scroll. Consider the following:

\j^0

10 CALL CLEAR

20 FOR S = 1 TO 100

30 IF S = 21 THEN 100 40 IF S = 41 THEN 100 50 IF S = 61 THEN 100 60 IF S = 81 THEN 100 70 PRINTS 80 NEXTS 90 END

100 PRINT,, 110 INPUT " TO CONTINUE": ANS 120 CALL CLEAR 130 GOTO 70

Mai/

Viator

REMEMBER!! You, not the computer, are in CONTROL! You can have your output any way you want it. To use more of the screen, you could have the output sectioned to different parts of the screen. For example: 10 CALL CLEAR

20 FOR I = 1 TO 20

30 PRINT I; TABf5l; I+20; TAB(10); I+40; TAB(15); I+60; TAB(20); I+80 40 NEXT I

126

v^„

You get the idea. Format your ouput in a manner that best uses the screen and your needs and get that scroll under

W

control!

More print Formatting Up to now, we've used the comma (,), semi-colon (;), TAB and

^

PRINT statement in formatting out PRINTed strings and variables. Now we will see a very handy TI BASIC way of for

\J

Vftp/

introduction

The topics of this chapter are more "code like" and contain the kinds of commands that look frightening. At least that's how I

Vgjjg^

interpreted them whenI first sawthem. Manyofthe functions

^j

can be done with commands we already know, but others can

not. Still others, as we will see, can be accomplished better using these new commands. Like so much else you have seen in this book, what at first may appear to be impossible is really quite simple once you get the idea. More importantly, by play ing with the commands, you can quickly learn their uses.

^

^J W

The first thing we will learn about is the ASCII code. ASCII (pronounced ASS-KEY) stands for the AMERICAN STAN

w

DARD CODE for INFORMATION INTERCHANGE. Essen-

^

tially, this is a set of numbers that have been standardized to

represent certain characters. InTI-99/4A BASIC theCH R$ (character string) command ties into ASCII and can be used to

w

directly output ASCII. As we will see, the CHR$ command is

w

very useful foroutputting special characters; however, there

^

are six "keyboards" on your TI-99/4A (0-5) that can be linked

through the CALL KEY command. We will look at the dif-

^

ferent keyboards in a separate section of this chapter. The next commands have to do with accessing subroutines in

your computer's memory. These use CALL. We have already been using CALL CLEAR to call up the subroutine in your

^

computer that clears the screen. Some of the ones we willdiscuss will allow you to do a lot more with screen formatting and

w1

other tricks you cannot do using standard BASIC program

130

commands. A number of the CALL commands will be left until

the next chapter when we discuss computer graphics, but by then you will be an old hand with CALL

The ASCII Code and CHR$ Functions A way to access any characters we want, including control characters, is to use CHR$ commands and the ASCII code. Whenever we want to access a character, we simply enter the CH R$ and the decimal value of the character we want. For

example enter the following: PRINT CHR$(B5]

You got an A.That's simple enough and not too interesting. On W

the other hand, try the following little program, and I'll bet you couldn't do it without using the CHR$ function:

,

10 CALL CLEAR

W

20 REM 34ISTHE ASCII VALUE FOR QUOTE MARKS

,

30QU$ = CHR$(34) 40 PRINT "HIT TO CONTINUE OR"

^

50 PRINT "PRESS "; QU$ ;"Q" ; QU$ ; " TO QUIT" ::::::::

w

60 INPUT "=CHOOSE=" : ANS 70 IF ANS = "" THEN 10

W

80 IF ANS = "Q" THEN 100 90 GOTO 60

W

i,

w

100 END

RUN the program and look carefully. Note the quotes around the Q.If we tried to PRI NTa quote mark, the computer would think it got a command to begin printing a string. However, by

defining QU$ as CH R$(34] wewereableto slipin the quote marks and not confuse the output! (Just for fun, see if you can

W

do that without using the CHR$ command.) To see what dif ferent characters you have available, RUN the following

W

\^>

program:

lol

\£0

VD@ff^ Ss$

Njjpa?'

Stums/

Now, although not as simple as coloring the screen, it is not too difficult to determine which character set is needed for the

various text characters. To get several different letters from different sets requires planning, BUT there's a shortcut so

that you do not have to worry about figuring out a lot of code. All of the capital letters are in Sets 5-8 inclusive. If you CALL COLOR to this set, then your output will be in the desired colors. Try the following program to see how this works: 10 CALL CLEAR

20 30 40 50

CALL CALL CALL CALL

COLOR COLOR COLOR COLOR

(5.16,5] (6,16,5) (7,16,5) (8,16,5)

60 PRINT "THIS IS WHITE ON BLUE"

70 CALL KEY (0,K,C) 80 IF C=0 THEN 70

That was easier than using several CALL HCHAR or CALL VCHAR commands, and if you want you can have each letter in a different foreground/background scheme depending on the CALL C 0 LO R commands for the different character sets.

Experiment with different color combinations to find ones that are useful. Try fixing up your menu programs from the last chapter. \Ul(ij/

Vjjjjljjljj/

Since you may want only certain parts of your program in daz zling color and the rest in the default mode, you will need a way to get everything back to "normal." To do this requires CALL COLOR to black letters and light green background. Add the following lines to the previous program to see how this is done:

155

90 CALL COLOR (5,2,4) 1 •» 100 CALL COLOR (6,2,4)

Sag/

„ ..

110 CALL COLOR (7,2,4)

^

120 CALL COLOR (8,2,4) 130 PRINT ::: "HOW ABOUT THIS?"

W

140 CALL KEY(0,K,C) 150 IF C=0 THEN 140

W

At this point you should be able to handle colors and text easily. But we really have not done much with graphics; so let's

^

continue with some more tricks.

^

If the foreground and background color of a letter are the

^

same, you will get a block of color. Your letter is there but, since the background and foreground are the same, it is invis

ible. A line ofblocks would produce a bar. Try thefollowing

>

^

program to see the effect: 10 CALL CLEAR

20 REM ** RED SCREEN **

Sissy/

30CALLSCREEN(11]

40 REM** COLOR SET #5**

^

50 REM ** YELLOW FOREGROUND & BACKGROUND**

w

60 CALL COLOR (5,7,7) 70 REM** VERTICAL REPEAT'A'**

W

80 REM ** THE 'A' IS INVISIBLE **

90 CALL VCHAR (5,10,65,15)

W

100 CALL KEY[0,K,C) 110 IF C=0 THEN 100

^

Now, if we can make a single bar, I'll bet we can make a bar graph. Also, we will want to label our graph, so we will use something other than the letter "A" to make our bars. In fact, we will make our label outside the character code range of the alphabet We will use the =, equal sign, in Set 4 with an ASCII code of 61.

j Nfljjjfljir

\sgg/

10 REM ***************

20 REM BAR GRAPH 1

W

30 REM ***************

40 CALL CLEAR

w Sijjjjjgj/

156

>ii^ \jg0

.

50 INPUT "TITLE OF GRAPH" : TITLES

60 INPUT "HOW MANY PLOTS (1 -5) " : PLOTS .

70 IF PLOTS > 5 THEN 60 80 FOR X = 1 TO PLOTS

^

90 INPUT "VALUE (1-20) " : PV(X)

W

110 CALL CLEAR

W

200 REM ********************

W

220 REM *******************

100 NEXT X

120 REM *** END OF INPUT BLOCK *** 210 REM MAKE THE GRAPH

230 CALL SCREEN(11) 240 CALL C0L0R{4,7,7) 250FORX=1 TO PLOTS

260 ROW = 24 - PV(X] 270COLUMN = X*5

280 SCALE = PV(X) 290 CALL VCHAR(ROW,COLUMN,61 .SCALE] 300 NEXT X /\C7U7I DPIV/I

♦♦'I'*****'!''!''!'*****

410 REM LABEL GRAPH \.

4P(7I RFM ****************

430 FOR I = 1 TO 28

W

440 PRINT "_";

W

460 L = LEN(TITLE$)/2 470 PRINT TAB(14-L); TITLES

W

480 CALL KEY(0,K,C)

450 NEXT I

490IFC = 0THEN480

\^y

\j$^/

RUN the program and see how nicely you can present data graphically. The program is severely limited in that it only does a maximum of five plots and values from 0 to 20. It is sim ple to change the number of plots above five. Just change the trap value to a higher number and change the offset in line 270

Vw

to less than 5 (e.g., X * 2) to set the bars closer together. Changing the values to above 20 requires more sophisticated

W

manipulations, however. This is because 20 represents the maximum length of a vertical plot and still puts in the material

W

at the bottom of the screen. Using our editor and RESE

^

make sure your graph program is in memory and enter RESE-

QUENCE command, let's fix up our graph program. First N^jjigp/

157 Vi^p/

QUENCE . This should renumber your lines by10

^

beginning at line 100. Now enter the following lines: 10 CALL CLEAR

20 INPUT "MAX VALUE->" : MV

^

30N = 1

40 NN = MV

W

50IFNN

^

mented by 1 and NN is re-defined to be the value of

MV divided by N and looped back to line 50 for another comparison. As soon as the value of N increases to a point where the maximum value, MV, divided by N is not greater than 20, the loop exits to the main program. Whatever the value of N is at

w ^

^

that time will be used in the rest of the program to

divide any value entered.

W

FOR EXAMPLE: The value of MV is established to be 100. Since

^J

100 is greater than 20,1 is added to N and 100 is divided by 2 resulting in the value of NN equaling 50. Since 50 is still larger than 20, N is incre-

W

158

W

W W W

^

Vjjgjj^jj/

mented to 3. When MV is divided by 3, the result is 33.33. Again it is larger than 20, so there is another loop. The program loops two more times. When N is equal to 5, MV divided by N equals 20. This time, when the comparison to 20 is made, it is found that NN is not larger than 20 and so the

line is exited and the value of N is established at 5. No matter what value is entered, as long as it does not exceed the maximum value, there will be no errors since all plot values PV (1), etc., will be divided by 5. Since 100 is the maximum value to be entered, 20 is the maximum value which will be charted.

W

3. Two values for PV (X) are entered in lines 180 and 185. First, the raw value is entered in line 180. Then in line 185 PV(X) is changed to be an integer value using the formula, INT(PV(X)/N). The INT com mand is introduced to provide an integer (whole) number for charting.

^

4. The remaining program is the same as it was

W

before.

Just to make sure you have all the correct changes, here is the

w ,

complete program. (The RESEQUENCE messed up our "blocking", but it's better doing that than having to start over from scratch!) 10 CALL CLEAR

l

20 INPUT "MAX VALUE->" : MV

w

40 NN = MV

30N = 1

50IFNN 5 THEN 150 170 FOR X= 1 TO PLOTS

W

180 INPUT "VALUE " : PV(X]

185 PV(X) = INT(PV(X)/N]

W

190 NEXT X

200 CALL CLEAR

^

210 REM *** END OF INPUT BLOCK *** nnn\ RFM ********************

W^

230 REM MAKE THE GRAPH n/\n\ RFM ********************

vw

250 CALL SCREEN[11] 260 CALL C0L0R(4,7,7)

270 FOR X-1 TO PLOTS

,

w

280 ROW = 24 - PV(X)

290COLUMN = X*5

^j

300 SCALE = PV(X)

310 CALL VCHAR[R0W,C0LUMN,61 .SCALE)

^

320 NEXT X

330 REM ****************

W

340 REM LABEL GRAPH

250 REM ****************

W

360 FOR I = 1 TO 28

370 PRINT"_";

^

380 NEXT I

390 L= LEN(TITLE$)/2

W

400 PRINT TAB(14-L); TITLES

410 CALL KEY(0.K.C)

W

420IFC = 0THEN410

160

.

W

FOR THE PERFECTIONIST WITH SOMETIME

w

W

We incremented N by 1 each time we passed through our test loop in line 50. If we wanted to get a finer value, we could have incremented N by .1 or .01 or even .00001! This would give us a nearer minimum value by which to divide PV(X) and still keep

it proportional; however, it would take longer for the loop to find the minimum value of N. Change the program to see the different results in the charts. The smaller the increment, the closer to the top of the chart the maximum value will appear, but the longer the program will take to execute.

We have spent a good deal of time working on charts in screen graphics, but it is important to see the practical applications of such graphics. Often users see screen graphics simply as something to draw mosaic pictures on and nothing else; but, as we have seen, it is possible to make very good practical use of them as well. Now let's have a little fun with animation

before going on to bit graphics. W W

W ^

Animation in screen graphics can be used in games and for special effects. We will only touch upon some elementary examples to provide you with the concepts of how animation works. Basically, by placing a figure on the screen, covering it

up and then putting it in a new position; you can create the illusion of moving figures. It works in exactly the same way as animated cartoons. A series of frames are flashed on the screen sequentially. Even though each individual frame has a stationary figure, by rapidly flashing a series of such frames, the figures appear to move. Your computer does the same thing. For example, the following little program appears to bounce a ball in the upper left hand corner: 1(71 REM ****************

20 REM ANIMATION 1 Q|T| ppiV/l ****************

40 CALL CLEAR

W

50 CALL VCHAR(2,3,79) 60 FOR PAUSE =1 TO 20

W

%im/

70 NEXT PAUSE

161

80 CALL VCHAR(2,3,32) 90 CALL VCHAR(3,3,79) 100 FOR PAUSE = 1 TO 20 110 NEXT PAUSE

120 CALL VCHAR(3,3,32) 130 GOTO 50

What appeared to be a moving "ball," was actually a figure being placed on the screen, erased and then replaced in a dif ferent location. Now let's do the same thing using the entire screen, and, just for fun, let's add some sound and special effects. (Remember to turn up your sound for this one.)

10 REM *************** 20 REM ANIMATION 2 on npjui ***************

40 CALL CLEAR

50 FOR FALL=1 TO 23

60 CALL VCHAR(FALL,16,79) 70 CALL SOUND( 1,800,2} 80 CALL VCHAR(FALL,16,32] 90 NEXT FALL 100 REM ******************* 110 REM HIT THE GROUND 120 REM *******************

130 CALL SOUND(70,-4,0.120,1) 140 REM ******************

150 REM AND SPLATTERS 160 REM ******************

170 FOR SPLAT = 23 TO 20 STEP -1 180 FLY = 24-SPLAT

190 CALL VCHAR(SPLAT,16.42] 200 CALL VCHAR(SPLAT,16+FLY.39) 210 CALL VCHAR(SPLAT,16-FLY.39] 220 CALL VCHAR(SPLAT,16,32) 230 NEXT SPLAT

240 CALL VCHAR(SPLAT,16,42) 250 CALL KEY(0,K,C) 260IFC = 0THEN250

162

By experimenting with different algorithms you can create a wide range of effects. If you have played arcade games with movement and sound, you now have an igea of how they were created. Now go ahead and start working on that SUPER SPACE BLASTER ALIEN EATER game.

BIT GRAPHICS All right, gang, weVe seen just about all there is to see with screen graphics, and let's face it, most of what we did was not "graphic" but rather color and text manipulation. That's all

right though, for the same principles apply to the next step,

Bit Graphics. In order to use Bit Graphics it is necessary to understand something about binary and hexadecimal num bers. There is nothing difficult or unusual about these number systems, but since we're used to the decimal system, these new systems may appear strange at first To get started, let's

take a look at how numbers are ordered in decimal, binary and hexadecimal:

163

THREE NUMBER SYSTEMS 5IMAL

0 1 2 3 4 5 6 7

8 9

10 11 12

13 14 15

BINARY

HEXADECIMAL

0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110

$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $A $B $C $D $E $F

1111

(Hex is conventionally prefaced by a dollar sign.)

Above we have three different counting systems. The first is base 10 (decimal), the second, base 2 (binary) and the third, base 16 (hexadecimal). Each system is similar in that all follow the same counting rules. In decimal, we count from 0 to 9, run out of unique characters, add on another digit and start all over again. In the binary system, where there are only 2 digits (0 and 1) we run out ofunique digits much sooner than in the decimal system. With the hexadecimal system, with 16

Suggs/

Vims/

164

unique characters, it is possible to count farther than decimal before having to repeat digits. Let's take a look: Vang/

Binary

Decimal

Add digit and start over.

Ran out of unique digits

10

2 3

11

Add digit and start over.

Ran out of unique digits

100 101

4 5

etc.

Hexadecimal

Decimal

$9

9

$A $B $C

Ran out of unique digits 10 Add digit and start over. 11 12

etc.

Decimal

Hexadecimal

14

$E $F

15

16 17

Ran out of unique digits. $10 Add digit and start over. $11

You may well be wondering why in the world even bother with

binary and hexadecimal numbers. Well, to make a longstory short, it has to do with the structure of microprocessors. Basically, the computer reads a bit of information in terms of

its being ON (1) or OFF (0), and the binary system can "read" the state of ONs and OFFs with zeros and ones better than

decimal. That's somewhat of an oversimplification, but essen tially that is why we bother with binary. Since binary tran slates into hexadecimal in 8 and 16 bit chunks, and the microprocessors are also in similar chunks, hexadecimal is more quickly translated than decimal.

165

However, let us not spend all our time trying to understand the design of computers. Rather, let's see how we can do some thing with graphics! To begin, it is important to understand that all of the text characters you see on your screen are made

up of dots or pixels of light on your screen. Allof the charac-

^ W

W

ters are arranged in 8 by 8 matrixes giving 64 spots to shoot

light to make a character. The basic unit of each matrix is a

^

four cell block that has 16 different combinations of filled cells.

The following shows a four-cell block:

^

Basic Graphic Block

(1)

(2)

(3)

^

(4)

Suppose we wanted tofill inCells 1and 3and leave Cells 2and

^

^

4 empty. Our block would appear as follows:

•,

Basic Graphic Block

(X)

(2)

(X)

(4)

With paperandpencil that would bea simple enough matter,

\$$y

^

but how do we do that with the computer? Instead of filling in

the cells with a pencil, we would do it by turning on a dot or

^

pixel. To do that, we could use a "1" to indicate the light is on and a "0 " to indicate the light is off. Now our block would look

^j

like this:

Basic Graphic Block

(1)

(0)

(1)

W

(0) Vagi/

So far so good. We now have a way of representing a pattern on our computer with zeros and ones, but how do we translate that so that we can get it on our screen? Okay, go back to the

v*^

chart that shows the decimal, binary and hexadecimal count-

W

ingsystems. Lookatthe binary systemforthenumber"1010".

Indecimal thevalue is10 andinhexadecimal it is$A orsimply

^

A. Your TI-99/4A uses the hexadecimal code, in capital letters

and numbers, torepresent different patterns. By entering the hexadecimal value A, it is possible to get the pattern in a basic block we designed above. However, to get that we need to

166

^ ,

enter it as part of an 8 by 8 matrix, and all we have so far is a 1

W

by 4 matrix. Let's put the rest of the matrix together:

w

Full Graphics Block

W

w

ODD

EVEN

(1)

(2)

(3)

(4)

(1)

(2)

(3)

(4)

Blocks land 2

(1)

(2)

(3)

(4)

(1)

(2)

(3)

(4)

Blocks 3 and 4

(1)

(2)

(3)

(4)

(1)

(2)

(3)

(4)

Blocks 5 and 6

(1)

(2)

(3)

(4)

(1)

(2)

(3)

(4)

Blocks 7 and 8

(1)

(2)

(3)

(4)

(1)

(2)

(3)

(4)

Blocks 9 and 10

(1)

(2)

(3)

(4)

(1)

(2)

(3)

(4)

Blocks 11 and 12

W

(1) (1)

(2) (3) (3) (4) (2)

(1) (1)

(2) (2)

(3) (3)

(4) (4)

Blocks 13 and 14

W

(1)

(1) (2) (2) (3) (3) (4) (4) (1) (1) (2) (2) (3) (3) (4) (4)

Blocks 15 and 16

Now we're just about ready to make our graphics! First,

[^

though, we have to have a new command that willallowus to make our own characters. That command is CALL CHAR

v^

with the format

,

CALL CHAR(ASCII,"HEX-PATTERN")

^

replace with our custom designed character. The HEX-

The value for ASCII is the ASCII character we choose to

PATTERN is the hexadecimal value that makes up our 64 cell block. Each single hexadecimal value is based on the four-cell basic block. On the Full Graphic Block, there are 16 Basic Blocks numbered from 1 to 16. The left side has odd numbered

blocks (1-15), and the right side has even numbered blocks

(2-16). By assigning a hexadecimal value, beginning with Basic Block 1 and working our way sequentially to Basic Block 16, we can fill our Full Graphic Block with a replacement \^s

cnaraccer.

To get started you will need:

^

1. A pencil

2. Graph paper (or a hand-drawn 8 by 8 matrix.) 3. An eraser

^ ',

4. Lots of creativity

(Go get those things, and I'll wait here.)

^

Now we're all set to create a replacement character. On the graph paper, block off an 8 by 8 area and draw a vertical line down the middle of it. On the left hand side write ODD and on the right hand side, EVEN. Now all you have to do is to fill in the little squares to make a graphic character. Once you are

finished, indicatewith 0's and l's which squares are filled in

>

,

^

and which are blank. Once that is done, translate each Basic

Block into a hexadecimal number. When you have 16 hex-

^J

adecimal values, you are all finished! The following shows how this can be arranged on graph paper:

W

Tl SPACE FIGHTER \jj|gi/

Hook

(1)

•W B

w (•) (11)

.ISI

ODD 1000 1001 1011 1110 1111 1011 1001

1000



£V!N



dL i HBB_H

•• ^mm •B iflH

P1

Block 0001

1001 1101 0111 1111 1101 1001 0001

(2) (4) (6) (8)

•snug/

\«SSi/ -~

\jjgg/

(10) V^jy/

\t^y

Assuming everything went according to plan, you should have

comeup with the following set of hexadecimal numbers:

^

8199BDE7FFBD9981

^j

So now let's see if everything worked. Enter the following program. Note: We will be replacing the letter "A" with our new

W

character.

W Njjjgj/

168 Vjj^/

W

10 REM ******************** 20 REM Tl SPACE FIGHTER

w

30 REM ******************** 40 CALL CLEAR

W

50 CALL CHAR(65,"8199BDE7FFBD9981")

W

60 CALL VHAR(12,12,65) 70 CALL KEY(0,K,C) 80 IF C=0 THEN 70

\iigW

We did it! Instead of an "A", our little "Space Fighter" was in the middle of the screen. As soon as you hit a key, the "Space Fighter" went back to the letter "A." Using CALL HCHAR and CALL VCHAR, we can position our replacement charac ters anywhere we want on the screen. Since it is really a pain in the neck to make all of those binary to hexadecimal trans lations, let's write a program that will do it for us. An pCIUI ***************

20 REM BINARY-HEX

W

30 REM ***************** 40 CALL CLEAR

W

50 FOR X = 1 TO 16

w

60 PRINT "BLOCK";X; 70 INPUT"" :BL$ 80 FOR Y = 1 TO 4

90B$ = SEG$[BL$,Y,1) 100L(Y) = VAL(B$] 110 NEXT Y

120 TL = (L(1 )*8) + (L(2]*4) + (L(3)*2) + L(4) 130 IF TL>9 THEN 200

,

140T$ = STR$(TL) 150 CALL VCHAR(23,20,ASC(T$]] 160 NEXT X

170 CALL KEY(0,K,C) 180 IF C=0 THEN 170 190 END

200 REM *********

******

210 REM TRANSLATE 10-15

W

220 REM ****

*****

230IFTL=10THEN290

W

240 IF TL= 11 THEN 310

250 IFTL= 12 THEN 330 260 IF TL= 13 THEN 350

270 IF TL= 14 THEN 370

',

w

280 IF TL= 15 THEN 390

290T$="A"

w

300 GOTO 150 3 i io T9>= B

\^

320 GOTO 150

330 T$="C"

W

340 GOTO 150

350 T$="D"

W

360 GOTO 150

370 T$="E"

>^

380 GOTO 150

390 T$="F"

^

400 GOTO 150

,

At this point you should be able to create anything that will fit into the 8 by 8 matrix. Using the Binary-Hex conversion pro

_j

gram, you can quickly convert your 4-digit binary numbers

^

into single-digit hexadecimal numbers, block by block. The final 16-digit hexadecimal number is then entered into the CALL CHAR command. Before going on to making multiple character graphics, let's take a quick look at animation with our replacement character. We'll make a galaxy of stars for our "Space Fighter" and fly through the stars. 10 REM ******************

^ W

W W

20 REM MAKE A GALAXY

30 REM ******************

hi^

40 CALL CLEAR

50CALLSCREEN(11) 60 CALL COLOR (2,2,11) 70 RANDOMIZE 12 80 FOR 1 = 1 TO 20

i

90 R = INT((24-1 +1) * RND] +1

100C = INT((32-1+1)* RNDJ+1

^

110 CALL VCHAR[R,C,42) 120 REM ##42 = ASTERISK ##

^

130 NEXT I Pf7I(7I RFM *************************

170

y^w

'^b^

w

210 REM MOVE SPACE FIGHTER 220 REM *************************

W

230 CALL COLOR(5,2,11)

240 call CHAR(65,"8i99BDE7FFBD998in) W

250 FOR M = 1 TO 24

W

260 CALL VCHAR(M,M,65) 270 CALL VCHAR(M,Mf32)

W

290 CALL KEY(0,K,C)

w

310 END

280 NEXT M

300 IF C < > 0THEN 310 ELSE 250

w

Let's look at the program step bystep: STEP 1. Using the random number generator we

w

created random (R)ow and (C)olumn values in lines 90 and 100.

W W

STEP 2. Using the asterisk (*) character as stars, we plotted them on the screen using CALL VCH AR with the random R and C variables. NO TE: Wedid not allow our random values to exceed24 Rows or 32 Columns.

STEP3. Usingour TI SPACEFIGHTER character, we plotted a (M)ove loop from 1 to 24.

STEP 4. We alternatively plotted our replacement character (65) with a space (32).

STEP 5. The movement continues until a key is pressed.

w

\-ifjp/

MULTIPLE CHARACTER GRAPHICS

Multiple character graphics is simply a matter ofpositioning characters next to oneanother sothat a larger graphic can be made from two or more single characters. For example, if we use an 8 by 16 matrix, we can have half the image on the left half of the matrix and the other half on the right side.

171

Double Character Matrix 1

8

16

Second Half

First Half

Vjjjgp/

Row 8

If we want larger images, it is simply a matter of adding more

\^/

blocks. Let's make another space rocket to go with our first one. First we'll make the right half and then we'll make the left half. V$§jj/

DOUBLE Tl SPACE ROCKET

EVEN

ODD

0 1110 1111 0001 1111 1111 1110 0

0 0 0011 1111 1111 0011 0 0

1 3 5 7 9 11

13 16

"000E3FF1

2 4 6 8 10 12 14 16

FRONT

Vqjgjj/

ODD 1

3 5 7 9 11

13 15

EVEN

0011

0 0

1111

1111 1100 1100

1111 1111 1111 1111

1111 1111 0011

0

0

2 4 6 8 10 12 14

"030FFFFCFCFF0F03*

16

BACK

172 Vi^r

Using our Binary-Hex conversion program we generate the hexadecimal code and use the following program to put it on

w

the screen. NOTE: What do you think the label "DOUBLE

^

CHARA CTER "in line110 isgoing tolook likeon thescreen? We are replacing the characters B (Code 66) and C (Code 67) with ourgraphics.

1(71 RFM ************************

W

20 REM DOUBLE CHARACTER 30 REM ************************

W

W

40 CALL CLEAR

50CALLCOLOR(5,2,11) 60CALLSCREEN(11] 70 CALL CHAR(66,"000E3FF1 FF3F0E00") 80 CALL CHAR(67,"030FFFFCFCFF0F03") 90 CALL HCHAR[12,14,66) 100 CALL HCHAR(12,15,66) 110 PRINT "DOUBLE CHARACTER"

120 CALL KEY(0,K,C) \j^y

^

130IFC = 0THEN 120

To move a multiple character, we do the same thing we did with a single character except we have to be more careful. In

^

horizontal movement, all we have to do is erase the trailing

W

half of the image since the second half will replace it. Add/ change the following lines to make your double character image move:

'%$j&/

\^m/

Move Double Character 85 FOR M= 31 TO 2 STEP -1

90 CALL HCHAR(12.M.66)

w

100CALLHCHAR[12.M+1,67)

w

105 CALL HCHAR(12,M+1,32) 107 NEXT M

\u^s

173

You will notice the movement is not as smooth as our single character graphic, and as we add more blocks to our graphics, movement is very rough looking. However, you can plan your programs so that the larger multiple character graphics are stationary and the moving ones are single character. NOTE:

There areenhancementpackagesfor theTI-99/4Ayoucan getthat willyou theability todo more with moving andcreating graphics. See Chapter 10. Joystick Control If you do not have joysticks, skip to the next section, but if you do then we will examine how to use them to move graphics. Turn off the power and plug the joysticks into the LEFT side of the computer. To get started let's look at the CALL J OYST format.

CALL J OYST (STICK#, HORIZONTAL, VERTICAL)

The STICK# is either 1 or 2. The horizontal axis is commonly called the "X-axis" and the vertical, the "Y-axis". In general terms an X,Y Axis can be seen as follows:

+Y

-X,+Y

-X

+X,+Y

0

-X,-Y

+X

X,-Y

-Y

174

The center value on an X,Y Axis is always zero (0). As you move away from the center, horizontally, the X value increases or decreases. Up or down movement causes the Y value to

increase or decrease. With joysticks, any vertical or horizontal movement of the stick causes a value of+/- 4, and substituting the joystick values for our X,Y Axis, we get the following:

0,4 Sjjjjjgjj/

-4,4

w

_4y0

4,4

0

-4,-4

4?0

4,-4

0,-4

w

W W

The value is stored in the CALL J OYST variable set up for horizontal and vertical value. Since we are using the concept of the X,Y Axis, we might as well use the value X and Y to rep resent horizontal and vertical positions of the joystick. Therefore, we will define:

CALLJOYST(1 or2,X,Y] %^B^

If thefirstvalue is "1" then it will affect Joystick # 1 and if "2" then Joystick #2.

Finally, at the top of your joysticks is afire button. This button is read with CALL KEY. It is the same format as we have been

W

using to read the keyboard, but the first value is either "1" or "2" indicating the fire button of Joystick #1 or Joystick #2. If the fire button is pressed, then the (K)ey value is 18, and the (C)ondition value is non-zero. Okay, we're all set to see how joysticks work. The following program reads the X and Y

\lHjgD/

1 I5

values of both joysticks and prints them to the screen. While the joystick is in the neutral (center) position, the values will be "0", and as you move them, the values will change to +/- 4. When you press the fire button on Joystick #1, the program will stop. Until then, it will scroll the values up the screen.

NOTE: Before you RUN thisprogram, make sure the ALPHA

LOCKkey is in the UPor OFF position. A O DCIV A ***********

^ w W

^ N^§


Viajjjijti/

and make the following additions or changes in the program. (Good grief! Don't rewrite the whole thing!) 695 INPUT "SEND TO PRINTER(Y/N)? " : PRINTERS 725 IF PRINTERS = "N" THEN 730 727 GOSUB 2000

W

2000 REM ************************* 2010 REM PRINTER SUBROUTINE

w

2020 REM ************************* 2030 EOPN #5:"RS232"

W

2040 PRINT #5: NS: AS: C$: " ", S$; " "; Z$

2050 PRINT #5 : CHR$(10) ^

2060 CLOSE #5 2070 RETURN

w

Tab Stops on Your Printer

W

Sometimes you do not want your printout to begin at the left hand side of your paper or label. To position the starting point

^

ofyour text, you use CHR$(9] in conjunction with CHR$(27) and CHR$(68). The format is fairly convoluted, but once you

^ w

get used to it, itisn't too difficult. Try to think of the sequence asfirst setting thetabstops and then tabbing tothenext tab position whenever CHR$(9) is encountered. When the tab

^

sequence ends, it is delineated with CHR$(10). The general format is as follows:

W

PRINT #5: CHR$(27); CHR$(68); CHR$(TAB 1); CHR$(TAB 2);... CHR$(TAB N); CHR$(0) CHRS(tab-n); CHR$(0)

To tab to a given column after the tabs have been established simply insert CHR$[9) before the string to be printed. PRINT #5: CHR$(9); "STRING-A"; CHR$(9);

w ^ W

"STRING-B"; CHR$(9J; "STRING-C" It is important to remember how many tabs you have since each CHR$(9) jumps one tab regardless of whether or not you print a string. For example, if you printed

209 \s^/

PRINT #5: CHR$(9);CHR$(9); "STRING"

the string would be printed at the second tab stop. For exam ple, try the following: 1(71 RFM ********************

20 REM HORIZONTAL TAB o#T| pCIUI ********************

40T1$ = "TABr 50 T2S = "TAB 2" 60 T3S = "TAB 3" 70 OPEN #5:"RS232"

80PRINT#5:CHR$(27);CHR$(68); CHR$(10]; CHR$(20]; CHR$(30); CHR$(0) 90 REM TABS OF 10, 20 AND 30

100 PRINT #5: CHR$(9); T1$; CHR$(9); T2$;CHR$(9);T3$ 110 CLOSE #5

In the above example, your printer will print your output

evenly across thepage; however, ifyou change line 100to read 100 PRINT #5: CHR$(9); CHR$(9); T1$, CHR$(9); T2$; CHR$(9);T3$

the first string, TAB 1 will be at the second tab stop, and TAB 2 and TAB 3 will be jammed up against one another since all three tab stops were used before the third string was printed.

Before going on to printer graphics we will examine how to use positioning in a program. This is useful in making lists where columns are important. For example, we can make a list ofitems for a garage sale. The first columnwillbe the item for sale, the second column the asking price for the item and the third column the actual price for which the item was sold. We will use INPUT statements so that all items can be entered

from the keyboard and used with an actual garage sale. (Who knows when you will want to use it? So why not make it useful!)

210

\jgj||jg^

.

10 CALL CLEAR

20 INPUT "HOW MANY ITEMS TO SELL ": N

W

30 DIM IT$(50), AP(50), SP(50) 40 PRINT::

W

50 FOR I = 1 TO N 60 PRINT "ITEM #"; I;

W

70 INPUT IT${I) 80 INPUT "ASKING PRICE $": AP(I)

W

90 INPUT "SELLING PRICE $": SP(I)

K%**"

110 NEXT I

100 PRINT onupi RFM ******************************

210 REM PRINTER FORMAT ROUTINE PPfTI RFM ******************************

230 OPEN #5:"RS232" 240 ITEM$= "ITEM" 250 ASKS = "ASKING PRICE"

260 SELL$= "SELLING PRICE"

W

270 PRINT #5: CHR$(27); CHR${68]; CHR$(10); CHR$(30); CHR$(50); CHR$(0) 280 PRINT #5: CHR$(9);ITEM$;CHR$(9); ASK$; CHR$(9); SELLS

W

300 FOR LINE =1 TO 65

w

290 REM ** PRINT A LINE ** 310 PRINT #5:"-";

W

320 NEXT LINE

^

340 FOR I= 1 TO N 350 PRINT #5 : CHR$(9);IT$(I); CHR$(9); AS(I);

330PRINT#5:CHR$(10)

%ii$gsf

CHR$(9];SP(I);CHR$(10) 360 NEXT I 370 CLOSE #5

^

There area couple of things to notein this program. First of all, notice how we employed CHR$ code to set up our tab

W

positionsin line270. The tabs were set for10,30 and 50.Then in line 280 we printed the heading using the tab stops we

W

created. In lines 340 to 360 we read in our arrays and instead

W

of having the output printed to the screen, we printed it to the printer. Using those tab stops, we could not have done a very

ViHig/

Ol "I

\^0/

good job of printing the output to our screen since it used only 28 columns. Our second tab stop was beyond the parameters of the screen.

To improve the program, figure out how to have the program compute the totals of the asking price and selling price of the items. It might be an interesting addition to have a fourth column which keeps a tally of the differences between the ask

ing and selling prices. This is something that you should be able to work out on your own! (Hint: Create a fourth array and tab stop.)

Printing Graphics Now that we have seen how to print text, we will look at graphics printing.

Making Your Own Graphic Characters on the Printer In Chapter 7 we showed how to create graphic characters using a binary coding translation to hexadecimal. Now we will do the same thing with printer graphics except we will trans late binary to decimal. First of all, we will be using a 7 by 7 matrix instead of an 8 by 8 matrix. (With dual density graphics, we can use an 8 by 8 matrix, but to use the dual density graphics we have to change one of the dip switches in the printer. Your printer manual tells you how to do this, but we will stick with the 7 by 7 matrix to keep it simple. We could have up to a 7 by 480 matrix!) To get started, instead of sending you off for some graph paper we will make our own graph for our matrix on the printer, explaining the process as we go along.

To begin, we use the following format to initiate the graphics mode. OPEN #5: "RS232.CR.DA=7"

212

\Sggg/

This format is different from our regular text format. The CR turns off the carriage return/linefeed, and the DA tells the

w

printer to expect 7 DAta bits. Since the carriage return is

i^,

turned off, we have to insert a CR with CHR$(10) when we want a linefeed. Depending on what we are printing, we may or may not want C R, and since DA defaults to 7, we usually do not need it either.

Once we 0 P EN the printer channel for graphics, we must then set up the normal density Graphics Mode with the following: PRINT #5: CHR$[27];"K"; CHR$(LON); CHR$(HON]

iw W W

*w

w

The CH R$(27];"K" tells the computer to turn on normal density graphics. That's simple enough. The next part might be a bit strange, though. LON stands for "Low Order Number" and H0 N for "High Order Number." As long as your number of graphic points is below 128, you simply enter that number in LO N and a value of "0" for H 0 N. However, with normal den sity graphics, you can have up to 480 dot positions; so you may

need numbers greater than 127. To make this conversion, you use the "modulo" of your data number divided by 128 for LON

and theINTeger ofyour datanumber divided by128forH0 N.

{

(Use 256 if you use dual density graphics.) Getting the HON

^

number is really easy since all we have to do is to PRINT INT(N/1 28) with N being the number of Graphic Mode data. Getting the modulo (the remainder after division) of a number takes either some pencil and paper work or a program. Since we've got a computer in front of us, let's do it with a program that will tell us the values of LON and HON. 10 REM **********************

20 REM GR. NO. CONVERTER 30 REM ********************** 40 CALL CLEAR

50 INPUT "GRAPHIC DATA NUMBER " :X 60 Y= 128

W

70Z=INT[X/Y] 80M1=Z*Y

^

90 MOD=X-M1

Vv

100 PRINT "LOW ORDER NUMBER=";MOD 110 PRINT"HI ORDER NUMBER=";Z

W/

213

So far so good, but what the heck is the graphic data number? To understand that, let's examine how the "dots" of graphics

are set up. The following matrix shows the work area we are using — a 7 x matrix. 128

{-For 8 bits

64 32

16 8 4

2 1

By inserting"dots" into the blanks, we can create a figure and this is translated to a way in which the TI-99/4A can under stand by a vertical total of the positions containing dots. For

example, if we draw a square, we would have the first and last columns filled and the top and bottom rows filled. Beginning with the first column, the value would be 64 + 32 +16 + 8 + 4 +

2+1 equaling 127. The next five columns would have a dot at the top and bottom. A dot in the top row would be 64, a dot in the bottom row would be 1, and adding them together we get 65. The last column would be the same as the first, 127. There

fore, we would want to create a CHR$ with the following values:

127

65

65

65

65

65

127

for our box figure. To do this we could have a line which reads as follows:

PRINT #5: CHR$(127] ; CHR$(65) ; CHR$(65) ; CHR$(65) ; CHR$(65) ; CHR$(65) ; CHR$(127)

but that (whew!) would take a lot of time. Instead it would be a lot simpler to READ in the values as DATA statements and PRINT # the CHRS we need for our figure, such as,

214

w

10FORI = 1TO7 20 READ GRAPHICS

w

30 PRINT #5: CHR$(GRAPHICS); 40 NEXT

W Signs'

Vy

50 DATA 127, 65, 65, 65, 65, 65,127

Now let's put it all together into a program. >j/t| pciui **************** 20 REM GRAPHIC BOX

30 REM **************** 40 CALL CLEAR

50 OPEN #5: "RS232"

w

60 PRINT #5: CHR$(27);"K"; CHR$(7); CHR$(0)

\i^/

80 READ A

50 FOR G = 1 TO 7

90 PRINT #5:CHR$(A); W

100 NEXT G 110 CLOSE #5

W

200 REM ***************** 210 REM GRAPHIC DATA

W

220 REM ***************** 230 REM DATA 127. 65, 65, 65, 65, 65,127

When you RUN this program, a little box will be printed.

^

Nothing very exciting, I admit, but now let's seehow we can use that little box to make a matrix to create new characters.

i w,

The following program will make a 7 by 7 matrix for you and requires making only a few changes in the above program:

10 REM ************* 20 REM BIT MATRIX

W

30 REM ************* 40 CALL CLEAR

W

50 FOR K = 1 TO 7 60 OPEN #5:"RS232"

w

70 FOR J=1 TO 7

80 PRINT #5: CHR$(27);"K"; CHR$(7); CHR$(0); ^

90 RESTORE 100 FOR 1=1 TO 7

^

110 READ A

215

120PRINT#5:CHR$(A); 130 NEXT I

140 NEXT J 200 REM *****************

210 REM GRAPHIC DATA 220 RFM *****************

230 DATA 127,65,65.65,65,65,127 300 REM *************** 310 REM END OF ROW 320 REM *************** 330 CLOSE #5

340 NEXT K 350 END

Now that you have a better idea of what can be created, print up a batch of matrixes and design some original printer graphics! You always wanted your own logo; now you can doit!

Printer Graphic utilities Since it is not much fun figuring out the LO N and H 0 N for our printer graphics and converting binary numbers to decimal, let's write a program that will do it for us. The following two utilities will automatically figure out 1) The Low Order Num ber and High Order Number for you if you supply the Graphic Data Number and 2) convert binary to decimal for you. The graphic data number is determined simply by counting the number of DATA entries you have to make up a graphic figure. For converting binary to decimal the program uses eight binary numbers so that you can use both normal and dual den sity graphics if you wish. Since we have been using normal density graphics, always enter "0" for the first value when converting binary to decimal with 7 bit graphics. GRAPHIC NUMBER CONVERTER 10 REM **********************

20 REM GR. NO. CONVERTER 30 RFM **********************

216

^

40 CALL CLEAR

\^g/

60 Y = 128

50 INPUT "GRAPHIC DATA NUMBER " : X 70 REM CHANGE THE VALUE OF Y TO 256

W

FOR DUAL DENSITY GRAPHICS

80Z=INT(X/Y) *m?

90M1=Z*Y 100MOD=X-M1

110 PRINT "LOW ORDER NUMBER=";MOD 120 PRINT "HI ORDER NUMBER=";Z Viiigl/

EIGHT BIT BINARY-DECIMAL CONVERTER 1(71 RFM ********************

20 REM BINARY-DECIMAL ^fTI RFM ********************

40 CALL CLEAR

w

50 INPUT "BINARY VALUE (8 DIGITS]": BINS 60 IF LEN(BINS) 8 THEN 50

W

70 FOR X=1 TO 8

80Y$=SEG$(BIN$,X,1]

W

90 P(X]=VAL(Y$)

w

200 REM ************

100 NEXT X 210 REM CONVERT

[^sm/

PP0 RFM ************ 230TOP=128 240 FOR C=1 TO 8

Vjjjjjjijj/

\jjjjpp/

250 DEC=P(C)*TOP 260 DTOTAL=DTOTAL+DEC 270TOP=TOP/2 280 NEXT C

^

290 PRINT "DECIMAL=";DTOTAL

W

300 PRINT :::"ANOTHER(Y/N)? "; 310 CALL KEY(0,K,C] 320 IF C=0 THEN 310

W

330 DTOTAL=0

340 IF CHR$(K)="Y"THEN 10 Now let's see if we can make our TI SPACE FIGHTER into a

^•"

printer character. Since we'reusinga 7by7matrix, it will be a

little different than the one we made for the screen. Using our

two printer utility program and our program to print out a matrix to create our own graphic, it should be easy.

TI Space Fighter Graphic J__0_J_J_1_J_J_ __l __L __L __L __L i. jl _*____ i_ __L __L i. jl __l __L __l __l __l i_ ___. A A JL A A A A __L i_ __L __L A i_ __L _>L i_ i_ ___. -_L i. JL jl_0_JLJL_0_JLjl

8