Programming for the Utter Beginner Who has an MS-DOS Computer Copyright (c) 1991,1992 by Michael Ham Table of Contents Introduction 1. How to Read This Book Part I: First steps 2. Your First Program 3. Polishing the Program 4. Saving Your Program Part II: Controlling the screen and basic structures 5. A Title Screen and Other Display Magic 6. Loops Within Loops: An Example Part III: Building a menu (and learning a lot) 7. Moving Toward a Menu 8. Characters from the Keyboard 9. Making a Choice 10. Return to Loops 11. Closer to the Menu 12. Making the Menu At Last Part IV: Your own database of mailing addresses 13. The Printer and the Disk 14. Collecting Strings 15. Building the Record: the Plan 16. Building the Record: the Program 17. Making a Real Live Program Part V: Some useful tools 18. Out of Sorts? Here's One You'll Like 19. Double the Precision, Double the Fun 20. Converting Numbers into Strings 21. Double-Precision at Work 22. Collecting Numbers from the Keyboard Part VI: Harnessing the powers of DOS 23. DOS Filenames: Correction versus Prevention 24. DOS and Forth 25. From BLOCK to File Part VII: The special powers of Forth 26. Inside Forth 27. Defining Words Part VIII: Floating point, graphics, and final remarks 28. Just When You Thought You Were Safe from Numbers 29. Return to the Screen 30. Remarks on Design Bibliography and List of Organizations Introduction This book teaches you how to write programs for your IBM PC-compatible computer. You don't need to know anything about programming or computers: the book either teaches you what you need to know or tells you where to find it (for example, in your DOS manual). Why would anyone want to learn programming? Several reasons: Control: Our world increasingly depends on--and is controlled by--technology, which finds its fullest expression and most useful tool in the computer. Some people feel a loss of control, a sense that somewhere a computer is using a flawed program to make decisions about their lives. The popularity of stories about erroneous computer-prepared bills attests to our fears. When you learn to program, you learn how to control a computer, a role reversal simultaneously satisfying and healthy. Apart from technology--perhaps *especially* apart from technology--the world works according to rules unstated and ambiguous. Games and sports are popular in part because they provide a microcosm of endeavor defined by explicit and unambiguous rules, allowing players for a while the comfort of having a specified goal and knowing the precise means (and limitations) available for achieving the goal. Programming's microcosm also is based on clear rules, but the computer provides an open-ended environment in which you set the goal and can in fact go beyond a game to create useful things. Craft: Programming thus gives you the satisfactions of a craft. Your work produces artifacts that embody your ideas, though since the artifacts are made of symbols and not materials, programming is more akin to writing than to woodworking. As you work, you search for the right words, the balanced phrase, the logical progression (all in accordance with the rules) to attain the goal you have in mind. With one, you make a sonnet; with the other, a program. Beauty: Programming provides also the pleasures of an aesthetic experience. When you find the minimal set of words (actions) that produces a desired effect, you enjoy a profound satisfaction, a pride in your work, that is the recognition of the rightness of the approach. When you watch in operation the final version of your program--well-crafted to its purpose--you delight in the movements of a complex (though abstract) mechanism, all its myriad parts interacting appropriately. You have created a kind of abstract kinetic sculpture that follows your instructions to fulfill your objective. Practicality: Since your objective in programming is typically some practical purpose, we find a final answer to the question of why learn programming: the practical answer. Some people make their living as programmers; others need a particular program to support their work or hobby and find nothing on the market that exactly meets their need. Programming offers them the means to reach practical goals. You can't learn programming without learning a programming language. The programming language used in this book is Forth. Why did I choose Forth? The particular programming language clearly doesn't make any difference to the person who USES the program--she or he doesn't care whether the program was written in Assembler, FORTRAN, COBOL, ALGOL, PL/1, RPG, APL, LISP, PROLOG, LOGO, SNOBOL, JOVIAL, Pascal, Ada, Modula-2, Actor, SAIL, STOIC, BASIC, BASICA, QUICK- BASIC, TRUE BASIC, Visual BASIC, or B, or C, or C++. The user really doesn't care whether the work is done by a program or by a team of tiny trained bees inside the computer case. So user preference is no help in determining the language to use. And as you see, many languages are available, each with its special characteristics, mission, and proponents. Forth certainly is not heavily promoted: no major hardware or software company proclaims it as the latest language, the one that at last will prevent errors, improve productivity, and fight tooth decay. Forth isn't taught in high schools or colleges as the ideal "introductory" language. It hasn't the imprimatur of science, though it saw first light in scientific applications for instrument control and data acquisition and analysis. Yet Forth continues to be widely used. As computers shrink to take up residence inside our automobiles, appliances, and toys, Forth is frequently picked for the programs embedded in these machines. And some software sold commercially is written in Forth. Forth is not packaged with new computers; instead, as each new processor is released, Forth is promptly ported to it, generally by the volunteered labor of some programmer eager to try out the new computer. Forth is used because it is easy to develop, well within the reach of the average programmer, and the resulting language is powerful, fast, and compact. Forth is the people's movement in computing, the unruly outsider that can't be left behind because it is simply too useful, too good, too powerful, too easy--and so the programmers bring it. For themselves. I wanted to use a good programming language for this book, so I took the language that programmers created for themselves and that they determinedly carry with them as they move from machine to machine. That language is Forth. Forth proves to be an excellent choice for a beginning programmer for various reasons, the primary one being that Forth offers fewer impediments than most programming languages. Because practicing programmers developed and refined Forth in the field (as it were), its design was shaped by experience and it has evolved into a powerful programming tool. * Forth allows you to develop programs incrementally, through a series of short routines that can be run by themselves. By writing the program piecemeal, you avoid having to tackle the whole thing at once. By keeping each piece small, you can completely understand it. This procedure is not only easier, it results in fewer program errors ("bugs"). * Forth is fast; in particular, it is much faster than interpreted BASIC, a language commonly used by beginners. * Forth is fully interactive, which means that as soon as you write a part of your program, you can run it and test it. This allows you to revise and refine the program on the spot, as you go. * Forth allows you to build on your own experience. You can extend it to include new commands and data structures and objects that you create to address the kind of programming problems you most often encounter. * Forth can be used to produce programs that you can save on disk and that run by themselves. The Forth supplied with this book is FIRST/FORTH, based on (and derived from) a professional product, UR/FORTH, published by Laboratory Microsystems, Inc. (LMI) of Los Angeles, California. LMI is a leading Forth vendor, with a long history and excellent products, which now include WinForth for Microsoft Windows. LMI's Forth conforms to the most recent Forth standard, the 83 Standard. Although FIRST/FORTH does not include all the features of UR/FORTH, it includes the essentials; what you learn here will enable you to write real programs, and your programs will run equally well (and somewhat faster) in UR/FORTH. FIRST/FORTH, specifically tailored for the beginning programmer, does not include source code for the editor, the electives, and the binary overlays. It lacks the assembly language package, the special memory management commands, and the hardware floating point instruction sets. All of these are included with LMI's professional Forths. As with all LMI products, you can sell or share the programs you write without paying any royalties or license fees, provided that you distribute only program files created by the TURNKEY command described in this book. You can, of course, distribute your source code files with no restrictions. By the end of this book you will have written a respectable program. You will be familiar with the Forth language and its conventions, and (more important) you will also understand the nature of the programming activity and the issues that it must address. The goal of the book is not to teach a programming language, but to teach programming--the language is but the means to the end. Chapter 1 How to Use This Book This book will teach you how to design, write, and debug simple programs. You'll learn programming commands and program development as you write programs. The emphasis is on programming, not on the programming language. Some of the programs are simple exercises; some are basic tools or structures you can extend and use in your own programs. To get the most out of this book, heed a few basic rules: 1. Read the book with a pen or highlighter in your hand. Underline or circle new terms. Write questions and notes in the margin. Record discoveries you have made. Make your own index in the back of the book, noting terms and ideas important to you and the pages on which they are discussed. Restate explanations in your own terms. Draw diagrams to make concepts and relationships clearer. Make this your book. 2. Read the book at the computer and do each example. Have Forth loaded and enter the examples as you read them. Doing the examples teaches a part of you that reading the examples doesn't reach--and that's the part of you that writes programs. Of course, you should also do the exercises in the book, but do the examples as well. 3. Experiment. If some point is unclear or you wonder what would happen to an example under different circumstances, TRY IT OUT. Sometimes what you try will work the way you expect, sometimes not. The worst that can happen is that: * you don't get the result you want; or * you get an information message on why it won't work; or * you suddenly find yourself back in the operating system (DOS), with the A> (or C>) prompt; or * the computer gets the blind staggers: the screen shows only a flickering display of random garbage and nothing happens when you press the keys; or * the computer goes into a catatonic trance and does nothing, and nothing happens when you press the keys. Yes, the computer will occasionally sulk and become totally unresponsive as the result of an experiment. This corresponds to what happens when you learn tennis: you knock the ball over the fence, and then must run after it. But because you're using a computer, recovery is much easier: a. First, try pressing Ctrl-Break. Then press the return key a few times to see if the "ok" comes back. b. If that doesn't work, try pressing Ctrl-Alt-Del to reboot the system (that is, reload the operating system and start over). You then can return to Forth and try some other approach. c. If that doesn't work, turn off the computer, wait a few seconds, and turn it back on. This complete resurrection will always work (unless your program has gone so far awry that it has written over the system files). You don't have to fear a system crash. It's a normal part of learning; beginning musicians hit wrong notes, beginning tennis players hit the ball over the fence, and beginning (and even experienced!) programmers occasionally crash the system. 4. Look at the answers. When you learn how to read the file ANSWERS.SCR, compare your answers to the exercises to the answers in the file. If your answers are different, determine both the cause and the effect of the difference--"different" doesn't necessarily mean "wrong." Experiment with variations, seek improvements. But always attempt to work out the answer yourself before you look. 5. Don't jump ahead Some readers have a habit of jumping ahead several chapters and reading around. In a book such as this, where you are learning new terms and new techniques on almost every page, jumping ahead shows you gobbledygook, which can be discouraging. If you work your way through the book, one page at a time, you will understand the later material when you get to it. This is not to say that you should stay stuck on some particular word on concept. If you have worked your way up to some point in the book and feel stuck, flow around that difficulty and keeping going. Later material often illuminates earlier difficulties. But avoid simply leaping ahead without working through the intervening material. 6. Speak up. If you don't understand some example or you find some section confusing, let me know. I am happy to help you, and your questions and comments will help me improve this book. You can write to me in care of Laboratory Microsystems, Inc. (12555 West Jefferson Boulevard, Suite 202, Los Angeles, CA 90066), or leave a message to MICHAEL HAM on the LMI bulletin board system (213/365-3530; 1200/2400/9600 bps; 8 bits, no parity), or send an email message to mham on BIX. Up the slippery learning curve Those who begin to learn something completely new often experience a strange phenomenon that I call "Teflon memory." Each new fact that enters the mind slides away as soon as the mind turns to a new thought. The most elementary facts must be learned and relearned repeatedly before one finally sticks and is available for recall. As soon as one fact is retained, it offers a toehold for the next. The two link to catch a third, and soon the facts you have accumulated form a net that readily captures new facts about the topic from your reading and experience. By this time you are puzzled that you didn't grasp instantly such simple and self-evident things as those early facts. The strange awkwardness of the early stages of learning something new would be familiar if we routinely and habitually ventured into totally new territory. Naturally enough, however, we seldom take up something completely new; the familiar not only is comfortable, it allows us to enjoy the skills already developed from our earlier experience. Experienced card players, for example, generally prefer to learn a new card game (which they can learn quickly by relating it to card games they already know) than a completely different kind of game. Those who try to learn bridge without any previous experience with cards find facts sliding away on the Teflon memory of the novice. Only with patience and persistence do they see the first fragments of knowledge stay long enough to begin building the structure of learning. Unless our commitment to the goal is strong enough to keep us involved, we retreat to the familiar and abandon the awkwardness of the new. Because we generally stick to the territory we already know, the feelings that arise in the initial stages of new learning are strange and uncomfortable. We want a royal road to knowledge, a road that takes us quickly from the discomfort of our ignorance and uncertainty into the power and security of mastery. And a royal road exists. To find an efficient way to learn, look to efficient learners. The most efficient learners are small children: they have the most to learn, and they learn the quickest. How do they do it? They wrap themselves around their experience and observe everything that happens without being blinded by expectations. They multiply the number of experiences by taking everything within their grasp and playing vigorously with it in every way. They don't fear mistakes because mistakes are not possible: everything that happens is information, grist for the mill of their curiosity. The toddler who tries to eat a block finds a fact, not a failure: this particular block seems inedible. The toddler who throws a glass to the floor discovers that glass shatters and makes an interesting sound, a lesson to be verified immediately if another glass is within reach. Experience is not one big thing, it is a thousand little things. That is why it takes so long to acquire: like panning for gold, tiny grains are added to the hoard one by one, and as the grains accumulate, the value grows. The best route to mastery is to exploit experience: work with every word and idea, push them this way and that. Observe whatever happens. When you think you've found a pattern, test it. In a word, play with the computer and the commands. See what they do. Become a programming toddler, and delight in the sense of discovery. And in the early stages, when facts slide quickly from memory, go back and reread the manual when you have to--everyone does. The Road Ahead This book winds its way through various experiences. You learn commands by using them, playing with them, and making them move, not by memorizing them. Many commands are used in the programming examples, others you can play with on your own. Be patient with yourself, be inquisitive, enjoy the process, and before the end of the book you will be programming. The early examples in the book are simple because you don't yet have the commands and concepts for complex examples. Chapters 2 and 3 work on a simple program to display a single phrase on the screen. In chapter 4 you are introduced to the editor, which allows you to save your programs to disk. With this capability, you can begin to build more complex programs. Chapters 5 and 6 complete the early work of screen display, teaching you along the way about an important programming technique, the loop. Chapters 7 through 12 have as their overall goal the development of an on-screen menu from which the user of a program can select the options he or she wants. The menu is a basic element in many programs, and to construct it you learn a wide range of essential computer information: how to make sounds, collect input from the keyboard, make choices, and so on. The next step after making a menu is to develop a program to put behind it. I use an address book program: you develop a program that allows you to create a database of mailing addresses and print them as needed. This enterprise takes five chapters, 13 through 17, and through the rest of the book we periodically revisit this program to augment or refine it. Chapter 18 shows you how to sort data. Chapters 19 and 20 show you how to use larger numbers and how to display numbers in various formats (with commas, decimal points, dashes, and the like). Chapters 21 and 22 use these larger numbers to show you some useful techniques for application programs, including a general-purpose word that collects numeric data. DOS provides you, as a programmer, with some powerful tools. These are discussed in chapters 23 through 25. The address book program is revisited to put these new capabilities to work. Chapters 26 and 27 show you Forth's special powers and how to use those powers in your programs. In particular, Forth's ability to let you define entirely new data structures is explained with examples. Chapter 28 introduces the floating-point operations and shows their use and limitations, and chapter 29 takes you into the world of graphic displays. Chapter 30 ends the book with a collection of general principles and rules of thumb for applications programming. REGISTRATION OF FIRST/FORTH Complete this form and mail it with payment (see below) to: FIRST/FORTH Registration Laboratory Microsystems, Inc. 12555 West Jefferson Boulevard Suite 202 Los Angeles, CA 90066 FAX 310/301-0761 When your payment is received, you will be shipped a copy of *Programming for the Utter Beginner*. Your registration will be recorded so that you will receive information on any upgrades to FIRST/FORTH and on other LMI products. In addition, you will receive a credit of $20 toward the purchase of UR/FORTH or WinForth. UR/FORTH is a professional development system for DOS. It includes graphics, hardware and software floating point, DOS extensions, and full documentation. It is available in 16-bit and 32-bit versions. FIRST/FORTH source code will run directly in UR/FORTH. WinForth is a complete professional Forth development system for the Microsoft Windows environment. Please print. California residents: Please include sales tax. Name: _______________________________________________________ Address: _______________________________________________________ _______________________________________________________ City: ___________________________ State: ______ ZIP: _______ Daytime telephone: (_______) ___________________ If you wish to buy additional copies of *Programming for the Utter Beginner* (each with a diskette containing FIRST/FORTH and all associated files), please indicate below: Registration fee for software = $ 49.95 Additional copies: ____ x $54.95 = _________ Subtotal = _________ California residents: sales tax = _________ Shipping/handling registration copy = 5.00 Shipping/handling addln copies @ $5 = _________ Total = _________ For additional copies, indicate diskette size: [] 3.5" [] 5.25" Indicate method of payment: [] check [] money order [] VISA* [] MasterCard* *Card number: ____________________________ Exp date:________ Signature: _____________________________ Date: ___________