P. 1
Learn to Programme

Learn to Programme

|Views: 31|Likes:
Published by jesussesi

More info:

Published by: jesussesi on Dec 07, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

07/26/2012

pdf

text

original

Sections

  • Chapter One
  • You Should Learn To Program
  • The Mystique of Programming
  • Two Wrong Reasons for Learning to Program
  • Some Good Reasons for Learning to Program
  • Chapter Two
  • How to Talk to a Computer
  • Chapter Three
  • Chapter Four
  • Decisions, Decisions
  • Chapter Five
  • Over and over again
  • Chapter Six
  • Chapter Seven
  • From Data to Information
  • Chapter Eight
  • Conclusions
  • Appendix
  • How Computers Work
  • Goal of this Appendix
  • Level One: Transistors
  • Level Two: Gates (Assemblies of Transistors)
  • Level Three: Decoders, Latches, Adders (Assemblies of gates)
  • Level Four: Breadth
  • Level Five: Assembling RAM
  • Level Six: The Central Processing Unit (CPU)

Chapter One You Should Learn To Program The Mystique of Programming One of the oddities of the ongoing personal

computer revolution has been its failure to dispel the myth of the programmer as genius. Most people regard programming to be some black magic accessible only to the high practitioners, the "real" programmers. We commonly lump programmers into the same category with neurosurgeons, nuclear physicists, and astronauts. Each of the latter three professions is immensely difficult, requiring long and careful training. Those who master such jobs merit a respect bordering on awe. Moreover, there are not halfway states in these three fields: either you make it or you fail. We don't have amateur brain surgeons, nuclear hobbyists, or weekend astronauts. But programmers do not belong in the same category with neurosurgeons, nuclear physicists, and astronauts, even though they go to great lengths to give that impression. Anyone who has been exposed to computers can testify to the dense fog of jargon that seems to shroud the machines in mystery. Now, every special group of people creates its own special subset of the language; it's a normal means of establishing a group identity and often simplifies communications. But of all the groups I have encountered, programmers have the most singular lingo. The jargon of programming goes far beyond the reasonable need for handy terms that precisely describe complex concepts unique to the group. Why, for example, should a programmer "architect the program's user interface" instead of simply "designing how people use the program"? Why do programmers talk about "CPU cycles" as a measure of time when they aren't actually counting those cycles? Why don't they simply talk about time? The answer to these questions is that programmers have developed a culture that prides itself in a sharply defined hierarchy. It is a highly structured meritocracy, with the highest positions reserved for those most knowledgeable in the arcane ways of computers. The members of this meritocracy wear no badges of rank, no feathered plumes, no sashes or medals. They carry their rank in their vocabulary; they dazzle with an opulence of acronyms. Another aspect of this culture is its exaggerated sense of taste and discernment. Tell a programmer that you prefer BASIC; it's like telling a

Jehovah's Witness that you worship Satan. Prepare yourself for a true fire-andbrimstone sermon on the evils of BASIC. BASIC, your programmer friend will tell you, is not merely a slow language or an unstructured language; no, it is an execreble language, and trashy language. Only peasants use BASIC. You'll get similar reactions about anything else about computers. Hardware? Brand X was brought down from on high by Moses himself; everything else is rank trash undeserving of the name "computer". Operating systems? Anybody who doesn't use XXX operating system is a simpleton. Guess where all this puts you, the nonprofessional? You haven't even heard of this wonderful operating system or that fabulous piece of hardware. If only simpletons and perverts use other products, you must be an even lower creature not to have heard of them. Perhaps you'd better slink off before you are exposed for the presumptuous fraud you are. Leave programming to the experts who know what they are doing. Right? Wrong! Programming is not like neurosurgery, nuclear physics, or astronautics. Programming is like writing, woodworking, or photography. Anybody can do it. Doing it well, doing it like an expert – that takes a lot of work, a lot of experience, and a lot of talent. But anybody who can write a comprehensible paragraph can write a workable program. All it takes is a computer and some time. Two Wrong Reasons for Learning to Program Given that learning to program is within most people's intellectual grasp, the next question to consider is, why should anyone bother? Before I answer that question, I must first dispel two commonly cited (but incorrect) reasons for learning to program. The first reason has bounced around in countless expressions. Computers are the coming thing, we are told. Someday soon, they will be everywhere: in your car, your kitchen, even your comode. Why, you won't be able to flush the toilet if you can't program. A variation on this theme has shown up in television commercials. Perhaps you've seen them: You are standing knee-deep in snow. You are dressed in rags. You are shivering; your teeth are chattering. Looking through the nearby window, you see warm, happy people, talking and laughing, talking about computers. Someone notices you, and with a mixture of pity and contempt they close the drapes. You're out in the cold because You never learned to program! Your parents never bought you a Brand X computer!

This may be what some computer manufacturers want you to believe, but it just isn't true. This arguement is based on naive assumptions about the relationship between people and technology. No technology, no matter how useful, makes any headway into the mainstream of society until it is accessible to the average person. If the computers of the future require as much skill to operate as, say, private airplanes, then they won't be any more numerous than private airplanes. Computers won't become as ubiquitous as automobiles until they are as easy to use as automobiles. So you really don't need to learn to program to prepare yourself for the brave new world of computers. The LEDblinking, disk-spinning, RAM-guzzling monsters that left the laboratory will evolve into cuddly puppies by the time they reach your doorstep. A second "mis-reason" for learning to program refers to the myriad employment opportunities that will be available to those graced with the skill of computer programming. Perhaps people have in mind the stunning newspaper accounts of sixteen-year-old "whiz kids" who made their first million before their Junior Prom. The fact is, most of those newspaper stories were grossly exaggerated. For every person who has gotten rich writing programs, there must be thousands slaving away on a typical white-collar salary. As an ex-Atari employee who has known both high income and protracted unemployment, I can assure you that nobody should enter programming for the money. Some Good Reasons for Learning to Program Why, then, should anybody learn to program? I can give you several good reasons. The first is recreation – and I'm not talking about computer games. I refer instead to the creative enjoyment one derives from writing one's own program. It might seem strange to suggest that someone would go to all the trouble of writing a computer program for the sheer fun of it. But consider the range of similar activities that people undertake for recreation: photography, pot-making, painting, music – the list is very long. Every year people spend billions of dollars and millions of hours on such hobbies. For example, when Uncle Fred and Aunt Etna go to San Francisco, they stop by the Golden Gate Bridge where Uncle Fred takes a snapshot of Aunt Etna standing in front of the bridge. The lighting isn't particularly good, and the wind keeps dislodging her hat, and three kids are strangling a seagull in the background, but Uncle Fred doesn't mind. He could step into any tourist shop and purchase a picture-postcard of the Golden Gate Bridge, taken by a professional photographer in an airplane on the one day of the year when the

if only you had a symphony orchestra to play it. you could write a great symphony. I would shoot off my mouth. is not so constraining. Spaceships. Moreover. wine – if you can imagine it. but in his heart he knows that the computer is not "out to get him" or "always trying to trip him up". equipment. This is a lesson that I did not learn until I was well into my twenties. He figured the lighting. on the other hand. It is a creative exercise and is therefore fun. When I was younger. Amateur programming. I angrily blamed these catastrophes on the blindness of my seniors. blackjack. But he wouldn't value that postcard as much as the picture he took all by himself. The second reason for learning to program is that it will teach you the importance of clear communications. who obviously lacked the insight to recognize my genius. (How many times do parents hear those lines?) When the temper tantrum ends he sits down and mutters to himself. or it's simply impossible with the materials available.fog and the light are perfect. programming offers a tremendous range of creative possibilities. or stage. you can write a program about it. it's his little work of art and he'll take it over the professional's picture any day. the framing. the computer will do whatever he wants it to do. actors. laboratories. "Well. but you don't have the cameras. You can write a program about anything you want. He may rant and rave. but like a young bird on its first successful flight. it is true. I now realize that these disasters arose because I did not take the responsibility to express myself clearly. A computer program is an assembly of thought and imagination captured in much purer form than we can achieve with other media. The young hothead can't blame the computer when his bad input generates a "Syntax Error" message. There are constraints. Amateur programming is the same as amateur photography." The good thing about this experience is that the computer will eventually respond. propelling myself into stupid predicaments at which I can now laugh only because many years have passed. the constraints are less of a concern than the possibilities. let's figure out what I have to say to this thing to make it do what I want. You'd love to make a fun movie. Sure. Either it costs too much. Most other creative outlets impose constraints on your efforts. It's not so easy to blame the computer when you fail to communicate clearly to it. and the composition. Computer programming is limitless in scope because its expression is not tied to a physical medium like clay or paint or photographic film. If the hothead can only get his inputs right. accounting books. At the time. The lesson learned from this experience is important because people are much the same: .

until such time as we choose to pluck one out of the mist and condense it into base words.) Through all of this abuse. English is a powerful and expressive language. It readily warps and twists to conform to all the ridiculous demands we make upon it. but you've got to make the effort to communicate clearly. I had to dig my hole deeper. devoid of any manifestation. When my turn came. he would select the worst blooper of a sentence from the assignments and read it out loud. We coin a torrent of new words with wild abandon." To which my teacher retorted. I'll have to digress for a moment and talk about language. "I know what I'm talking about.they will do almost anything for you. And we shamelessly steal expressions from other languages. I maintain that learning to program will make you a better thinker. ethereal "thoughtworld". We speakers of English warp and twist the language to suit our every whim." That English teacher had expressed one of the fundamental truths of human existence. I lacked the wisdom to keep my mouth shut. It is blessed with a vocabulary three or four times larger than that of the next largest language. Now. arguably the most expressive in the world. many of them strained." I argued. no. Thought and language are intimately associated. and that's not what I meant to say. concerns the way that it will change your thinking. To explain why. the English language performs with truly English aplomb. I once had a crusty old English teacher who loved to embarrass his students. This implies that the nature of our thinking is shaped by the nature of the language we use. No! The act of expressing a thought is part and parcel of the thinking itself. It's not as if our thoughts exist and grow in some pure. yet they seem unappreciative of our attempts at reimbursement with such gems as "jeans" and "burger". Each time an assignment was handed in. that language is English. The expression of a thought is not merely a postscript to the process of thinking the thought in the first place. We make puns. (The French are the longest-suffering victims of this last crime. though. you don't know it. the Gumby of . Everybody in the class (save for one) would howl with laughter at the inanity. It is also blessed with an unparallelled flexibility. Language is the vehicle of thought. It is the "one size fits all" language. For most readers of this book. If only I had known that twenty years ago! The most important reason for learning to program. "That's not right. using voice intonation to accentuate the absurdity of the blooper. "If you can't say it. Advertising people routinely put the language through unbelievable torture tests.

a language that expresses precise. Every word in a computer language means exactly one thing and only one thing. but they are much better-suited for the special task of rigorous thinking. would throw their hands up in frustration and grieve that they just weren't logical enough to understand physics. When one word. any computer language. struggling with difficult concepts. the law looks like this: "The gravitational force between two point masses is directly proportional to the product of their masses and inversely proportional to the square of the distance between them. On these occasions. in one respect. English fails us. for they are so emphatically narrow-minded. rigorous thoughts clearly and simply. It is nonsense to assert that one person is innately incapable of understanding a concept that another person grasps. with hard. can mean three completely different things (to excavate. the expression of one of the fundamental laws of physics. flexibility becomes ambiguity. I offer for your consideration a computer language. Newton's law of gravitation. Words are put together to form commands according to a simple set of rules for which there are no exceptions and no variations. In English. Yet. and plasticity becomes imprecision. to insult. it loses all value for absolutely precise expression. This flexibility bestows upon the English language vast power to express almost any new idea that comes along. Trying to think logically with the English language is like trying to cut down a tree with a nail file – it's the wrong tool for the job. Sometimes we need to think with absolute precision. but their deficit was one of language.languages. or to appreciate). They are utterly useless for the general-purpose work that human languages must handle. Consider. Their admission reflected some truth and some falsehood. What we need is a different language. It is true that some of my poorer students were not wellequipped to learn physics. unyielding logic. Sometimes our thoughts must be disciplined and rigorous. Computer languages are very different from human languages like English. not of mind. It is false to assert that a human being is not smart enough to understand physics. "dig". Computer languages are ideal tools for disciplined thinking." . Oftentimes my students. I experienced this limitation of English when I taught college physics. It's not as if there were some section of the brain labelled "Logical Thinking" that shows up as only a void in some brains. for example.

you must be dumb. Chapter Two How to Talk to a Computer BASIC We will embark on this grand adventure using BASIC as our vehicle. don't you? Since you can't understand this mouthful. which do you think would be easier to learn: the long unwieldy one or the short simple one. First. is frustrating to learn at first. it can take you to places you never dreamed existed. But I'll ask you to use your imagination for a moment. It will make you a better thinker. But a computer language is like a boat.Sounds pretty imposing. if you can't read BASIC. any language. it's resilient. A language is a vehicle for exploring intellectual territory. you see the results of your attempt almost immediately. when you attempt something in BASIC. Many other computer languages require you to endure time-consuming intermediate steps before you can see the results of your work. and it can cover a lot of territory. BASIC's interactivity has great importance . it is an interactive language. BASIC is the most common computer language. you'll experience an exhilirating sense of discovery as you chart new mental territory and think with a clarity and precision you had never thought was within your reach. You should learn to program. right? Not necessarily. But once you get rolling. and do it now. human or computer. for ultimately learning to program will do more for you than all the computer games and spreadsheets and word processors in the world. English is like a dune buggy. After all. If you were equally unfamiliar with English and BASIC. BASIC: F=G*M1*M2/R**2 Now. BASIC boasts two other advantages that make it ideal for our efforts. doesn't it? You probably have to read it a few times to figure out what it's saying. Consider now the way we would say the same thing in a computer language. versions of BASIC are available on just about every microcomputer. You'll find your initial attempts at learning slow and tedious. this might look just as bad as the upper statement. and I presented you with both statements. it's tough.

Most computers will require you to load BASIC into the computer from your disk drive. Fire up your computer and get it started in BASIC. Indeed. A computer keyboard acts just like a typewriter keyboard. You type a key on the keyboard and the corresponding character appears on the screen. The fast feedback it offers makes it much easier to see one's mistakes. I can't tell you how to set up your computer with BASIC because it varies with each computer. and special commands before you can write your first program. you're all set to go. Of course. The trial-and-error approach that BASIC encourages is an excellent way to learn. so computer scientists disdain BASIC as a naughty language. professional programmers are not supposed to use trial-and-error programming techniques. These rules aren't "break this rule and the computer will explode into a million pieces" type rules. It's that simple. KEYBOARD ETIQUETTE Before you can easily converse with the computer. Not so BASIC. As you learn more. Since we're not here to become professional programmers. with a very few special exceptions. you will need to learn a few simple rules of etiquette that will simplify matters for you. they're not even "break this rule and I'll think that you are a bad person" type rules. Follow the instruction manual that comes with the BASIC language. And that is exactly how you're going to learn programming. they are "break this rule and the computer will probably get confused" type rules. One of these is the backspace key. your programs can become better. This language is so simple that you can start using it in a matter of minutes. normally erasing the character to the left. . structure. This key takes you back one space.to a beginning programmer. You'll have to go to the computer store and buy a BASIC language program. when the screen says "READY". this fast feedback encourages lots of experimenting with the language. The second advantage of BASIC is its simplicity. It can take days or weeks of study before one is knowledgeable enough to write the simplest program with the language. you just backspace all the way back to the typo and retype from there. we'll just thumb our noses at those computer scientists. Other computer languages require you to learn all sorts of theory. Let us begin. The exceptions are what give people problems. Instead. This is the key you use to correct a typo &emdash.

there is always a right way to get unstuck. for example. you type in an entire command like "DO THIS" and then you hit the RETURN key on the right side of the keyboard." Lots of people will type a command into the computer and get mad waiting for the computer to execute it. The RETURN key has a special meaning to the computer. a very good rule is: don't bother with the control key. but it might take you forever to find that command in the manual. That is. but it makes no difference. It is usually marked "Ctrl" on the keyboard. It means "OK. Sometimes when you are working with the computer you get stuck. in other situations it might exit a program. some sneaky command like Control-Q that will magically solve all your problems. meanwhile. it's not sitting there listening to everything you type in. "none". What does this tell the computer? That depends on the type of computer. It's probably labelled "ESC". How do you get unstuck? Well. the computer wants to know how many pages you want to print. It's important to realize that the computer does not carry on a normal humantype conversation with you. the program you are using. It is really like a second shift key: you hold it down while striking a second key. Most computers place the ESCAPE key on the upper left corner of the keyboard. How do you know what the control key does in your situation? You have to study the documentation. although they frequently have some nasty side effects. might delete a character in some situations. So it's good to know a few emergency techniques that often work. For now. You tell it "no pages!" but it just keeps on asking for the number of pages to print. Control-X. Getting stuck like this is very frustrating and has done more to slow the computer revolution than anything else.A very tricky key that causes no end of trouble with beginners is the control key. and very likely the phase of the moon. You tell it to do something and for some reason it just sits there like a dumb ox. Or maybe you tell it to do one thing and it retorts with some idiotic question like "How many pages to print?" when you didn't want to print any pages. In most situations. computer. It doesn't control anything at all. I've gotten this command just the way I want it. ESCAPE is supposed to mean something like "escape from this awful . the computer is waiting for them to hit the RETURN key to tell it to go ahead. You type "0". "nada". The first emergency command is the ESCAPE key. Go ahead and do it now. Oftentimes the only explanation of a particular control key combination is found in a footnote on a loose-leaf addendum that fell out of the binder when you opened the package.

Type the following command into the computer: . then turn it back on. Sometimes the computer goes so completely bonkers that even the RESET key doesn't bring it around. There is always one last resort with any computer that has gone wild: turn it off. This is a violent and brutal tactic. This key. and woke you up 5 seconds later with a cold shower? These rules of etiquette with the computer are only general guidelines. When you use RESET. it's not good for the computer's chips if overdone. Please. if it exists on your computer. There are rare occasions when even RESET won't do the trick. they put you to sleep with an anesthetic shot. It is supposed to mean something like "break off this line of communication". akin to the determined leader slapping his raving underling with the command. the data. and is frequently used as a fairly innocuous escape hatch. in many situations they may not apply. It will awaken calm. will probably be on the upper right corner of the keyboard. it might be called "BRK". the next one to try is often the BREAK key. serene. Some computers don't have a RESET key. It will not break your computer. Even more powerful than the BREAK key is the RESET key. do not overuse this tactic. however. everything. A COMMAND Let's try something with the computer. kid!" Wait a few seconds for the computer to completely forget whatever was driving it wild. But they are useful when you are in doubt and cannot find the correct course of action. But at least it regains control of the computer. RESET usually means "Stop everything! Erase your memory! Start all over from scratch!" RESET will erase everything in the computer's memory: the program. How would your body feel if.trap". The only survivors will be the programs stored in ROM and whatever you saved onto disk. Its name is misleading. "Get ahold of yourself. you are throwing away all the work you did since you last saved things to disk. every time you made a tiny mistake. and completely unaware of the wild or stubborn behavior that had possessed it only seconds earlier. If the ESCAPE key doesn't work. The BREAK key will almost always break you out of a BASIC program that's locked up. This is a powerful and dangerous key.

The general rule is simple: anything you put between the quotation marks. Thus.N. You have demonstrated who is the master and who is the slave. When it looks right. press the RETURN key.O. it will print.R. you must first understand some general principles of communications with flaws. but it might say something like "ERROR 23" or "HUH?" or some other indication that it is confused. the computer will print the word "HELLO" directly underneath your command. or in some way contains a flaw. and another quotation mark with two ticks. only this time. or XQYQKLZ. your screen should look like this: PRINT "HELLO" HELLO Congratulations! You have just given the computer a command. Consider communications between people. and smashed computers than all other sources combined. Give it the same PRINT command. strange message. Now let's try something else. What happens? The computer will probably come back with a short. Here you encounter one of the most important and frustrating problems in all of computing. If you typed it properly. Now try variations on the theme. We normally think of such communication as being flawless. a quotation mark with two ticks. the source of more frazzled nerves. not one. Try it.PRINT "HELLO" This means that you should type the capital letters P.E.I. I refer to the scurillous. Make up something good. sinful. give it your name to print in some clever sentence.L. the capital letters H. or whatever. SYNTAX ERROR A syntax error arises whenever a command is misspelled or out of place. instead of the word "HELLO". such as speech or writing. lost hours. Let's give it a new command. Most likely it will say "SYNTAX ERROR". and it has successfully executed your command. then type it in and press RETURN. yet in truth all .L. Try uppercase and lowercase letters. but a nonsense command. To properly understand syntax errors and their implications. like SNARGLEBLAB.T. not a PRINT command. try some other words.

communications between people are full of flaws. package from Steve?" "Steve. And the entire process probably took you less than a second. for spoken language is a messy hodge-podge of words. it does make sense. You realized that "gaps" fit the sentence perfectly." "So when do you collect from Fred?" "Oh. "hops". But if you were too look at it coldly. you could easily show that this conversation makes absolutely no sense. phrases. "gods". like an English teacher. considering such possibilities as "gobs". Indeed. what could it be? Here you went through a long. excuse me. almost unconscious pattern-matching process. Consider the process you went through when you read the word "gops". you can figure out what's going on. in the previous sentence. he doesn't need it. I got a quarter. Yeah. You probably went back and reread it to make sure that you got it right. did you notice? If you did notice. why. Let's eavesdrop on a conversation between two people on a city street: "Fine. he's too busy. where'd you get that bump? No. it really does say "gops". you didn't recognize it. the uh. How are we able to extract meaning from communications that are highly flawed? Some people . On first reading the word. uh. Sure enough. It is absolutely essential in understanding spoken language. The trick is. did you get the. OK. For example. Sure. He gave it to Fred. scan memory carefully: is there such a word as "gops"? No." "What the hell's he need with it?" "Hey. there isn't." You probably have very little trouble figuring out the meaning of this conversation. jeez. he was just around when Steve needed to hand it off to somebody. This kind of activity is very common in human communications. uh. Yet. Well. "tops". it certainly didn't stop you and probably didn't even slow you down. two. three days. there's Tom. and so on until finally you came upon "gaps". I deliberately misspelled the word "gaps". Tom. Hey. and so you mentally replaced "gops" with "gaps". you'd find all sorts of mistakes and syntax errors. "cops". and clauses thrown together in a wild jumble. we are very good at filling in the gops created by such flaws.

Authorization for Transmittal of Individual Confidential Information. I got a quarter. On a higher level. and the relationship provides context for the communication. the context of the world gives meaning to an otherwise flawed sentence. I prefer to think in terms of context. so they don't have any context. so that if the message becomes garbled. we are able to understand the comment.". it says its message more than once. For example. The reasoning is that a normal English sentence is redundant. but we cannot honor your request. Sure . to correct the flaws. ". . The sentence provides context for the word. There is much truth to the redundancy arguement. . not the quarter or the bump. And even communications do not exist in isolation. because the real thrust of the conversation is about the package. only if we know something about city streets and panhandlers. In the right circumstances. How many times have you heard this line: "We're sorry. A word does not exist in isolation. You have not properly filled out form RC/22b. A sentence does not exist in isolation. the communication provides context for the sentence. so they cannot correct flawed communications as we can. the pronoun "it" refers to the package. Please review this form and fill it out completely and resubmit your application. The context of the conversation tells us that. Hence. I am ready to make my point about syntax errors. they are part of a relationship and part of the world. The context provides information that allows us to fill in the gaps in communications. in the street conversation. Again. but I don't think that it hits the nail on the head. . people can still understand it. so infuriatingly narrow-minded. We humans are able to understand deeply flawed communications only because we understand the context in which they are made. a bump). people can be just as block-headed. it is part of a longer communication." . sir. it is part of a sentence.give redundancy as the answer.Yeah. computers aren't the only ones to exhibit extreme sensitivity to syntax errors. Redundancy is the practice doing the same thing two or more times as a back-up. . Now at last. We know that even though we talk about other possible antecedents (a quarter. the tendency of computers to be so frustratingly picayune. But computers don't know anything about the world. Actually.

this is really the same response as the computer's "SYNTAX ERROR" plaint. please. "That's fascinating". Just to be fair. I think that the responsibility for clear communications falls squarely on the shoulders of the speaker. Sometimes the listener is so completely lost that he doesn't even know where to begin. "Run that by me one more time. assuming that everything you say is lost on the audience. tend to answer that both sides share responsibility for clear communications. and I think that your experiences with computers will lend weight to my position. Sometimes the audience doesn't want to appear stupid by asking a dumb question. Whatever the cause. steeped in egalitarianism and a spirit of cooperation." This scheme insures that our conversation will move smoothly and efficiently. You must be a defensive driver. In the real world. In theory. Thus. You must drive home every single point with ruthless drive and determination. How then can we communicate well if our audience can't be trusted to speak up when it is confused? There is only one sure-fire solution. Sometimes the listener believes that his confusion is temporary and will quickly abate. the audience of a communication is supposed to give feedback to the speaker on how clearly the message is getting through. this seldom happens. How else could you respond to it other than to throw up your hands and say "Syntax error!"? Whose fault is it in a case like this? Who has the responsibility for insuring that the communication gets through loudly and clearly? The speaker or the audience? We Americans. and that is to assume very little of the audience.If you think about it. . let me throw in another example: "If the moment of inertia tensor is not diagonal. if you and I are conversing. and something I say doesn't make sense to you. I disagree. You must be pessimistic. you are supposed to say. he just nods his head knowingly and mutters. however. unstable perturbations will develop. Both the computer and the bureaucrat respond to a communication that does not fit their required format with the same unyielding obtuseness." Does this sentence make any sense to you? You have no context with which to understand it.

"Come down 3000". the screwup would never have developed. As I recall. This was an ambiguous instruction. The lesson you learn in the process will benefit you in many areas other than computers. Neither of us knew that there were two Doggie Diners on Main Street.imagining what is going on in the mind of the audience. It can respond to your commands only in their absolute. the tower had instructed the pilot. you never knew you were so sloppy a communicator. you will find that the number of syntax errors you generate will fall. I went to the other. It assumes nothing. It will indeed drive you crazy. Precise communications are important in almost everything we do. It has no context with which it can second-guess what you really meant to say. trying to guess where they might be tripped up next. How many arguements have you endured that were started by a misunderstanding? How many foul-ups have you gotten into because somebody didn't express themselves exactly? I well remember the time my father drove 30 miles to pick me up "at the Doggie Diner on Main Street". The most powerful demonstration of the crucial importance of precise communications is provided by an airline accident some years ago. "Does this bus go to Notre Dame?". or "Where is the bathroom?". But it will also discipline you to think hard about exactly what you say. This chapter will . If I had been more specific. the computer equivalent of "My name is Fred". It is a sobering experience to have so many of your commands rejected as syntax errors &emdash. But once you learn to express yourself clearly and carefully. or was he ordered to come down by 3000 feet? The pilot assumed the former. This is the only way to communicate with confidence. The next task is to learn a few simple expressions. knows nothing. The pilot came down to 3000 feet. but the tower meant the latter. but the computer provides an excellent training ground. It is a hard lesson to learn. literal sense. Precise communications can be a matter of life and death. there was a mountain at 3200 feet. Chapter Three Arithmetic. and Input You are now on speaking terms with your computer. was the pilot instructed to come down to 3000 feet. Deferred Execution. He went to one. there were no survivors.

arithmetic is an excellent topic to begin studying because it is familiar to people. when you used a number like 3254. We begin with ARITHMETIC Many people mistakenly think that performing arithmetic computations is the prime function of a computer. did you type it as 3254 or as 3.introduce you to three absolutely fundamental facets of computing: arithmetic. and input. For example. A delimiter is a marker that tells you where the end of one word is and where the beginning of the next word is. computers spend most of their time doing far less exalted work: moving bits of information around from one place to another. you can do addition. Try this with your computer: PRINT 3*4 The computer will type under your command the answer. The symbol for addition is a plus sign: +. you can do arithmetic on a computer. subtraction. When you have it right. Some versions of BASIC use a space as a "delimiter". Use some big. painstakingly examining huge piles of data for those few scraps of data that are just what the user ordered. It may seem silly untilyoutrytoreadabunchofwordswithoutanydelimitersatall.OK? There is no reason why you have to restrict yourself to multiplication. Nevertheless. Then put a space. type the word PRINT in capital letters. If you wish. If you can do arithmetic on a calculator. The general rule is: first. OK. In truth.254? That comma in between the 3 and the 2 will generate a syntax error. they cause more syntax errors than any other character. It may seem picayune. it's even easier on the computer. Then the first number. So watch your commas! The spaces are also important. deferred execution. messy numbers like 3254 or 17819. so quickly that you might suspect that it's up to some trickery. The . but I warned you that computers have no sense of context. Because commas are so small and hard to notice. So give the computer a break and give it spaces where it needs them. type in some different numbers. The symbol for multiplication is an asterisk: *. In fact. or rewriting the data in a form that is easier for the user to appreciate. use the BackSpace key to go back over the mistake. B u t d o n ' t p u t i n extraspacesorthecomputerwillgetveryconfused. press the RETURN key. an asterisk to mean "multiply" and then the second number. You may get a few minor items wrong. then type it over. or division just as easily. If you make a mistake. 12.

the computer will subtract the second number from the first number. it turns out that it doesn't really matter. dividing 12 by 4 to get 3. The first idea that comes to most people's minds is to type: PRINT 8+12/4 which will yield a result of 11. and performed the division first. Who wins? Well. With subtraction. *. you probably have two quick objections to this system of operator precedence. It's one of those arbitrary rules of the road like "Y'all drive on the right side of the road. If you are a reasonable and thoughtful person. And the symbol for division is a slash: /. yes? How does one avoid mixups like this? The primary means is through an idea called "operator precedence". If it had done what I wanted it to do. in our example above. that you want to add 8 to 12 and divide the sum by 4. for example. the computer will divide the first number by the second number. Quite a mixup. Whenever we have a situation in which two operators (an operator is one of the four arithmetic operation symbols: +. then divided the 20 by 4 to get 5.symbol for subtraction is a minus sign: -. y'hear?" Thus. then the division. if I type: PRINT 3+4-2 . we automatically yield to the * or the /. -. I told the computer to do two operations &emdash. Why? Because this command is ambiguous. So to subtract 551 from 1879 you type: PRINT 1879-551 To divide 18 by 3 type: PRINT 18/3 But what if you want to do more complex calculations? Suppose. This is a big phrase that means very little. With division. or /) vie for precedence. I wanted the addition done first. an addition and a division. First. the computer gave precedence to the division operation over the addition operation. you might wonder what happens when two operators with equal precedence contest each other. Then it added 3 to 8 to get 11. Which one did I want done first? It makes a difference! The way I described the problem. For example. the computer did the division first. Instead. it would have added 8 to 12 to get 20.

In our example. In this example. You can pile parentheses on top of parentheses to get ever more complex expressions. that 12 belongs with the 8. but the cruel computer would tear our hapless 12 away from the 8 and mate it in unholy union with the 4. then we get 4/2 is 2. Try it. See? It doesn't matter what order you do them in. protecting and preserving relationships that a cold set of rules would violate. bundle it up with a pair of parentheses. So operator precedence doesn't matter with operators of equal precedence. we get 3*4 is 12. "Parenthesis conquers all. 3+4 is 7. If you do it backwards. To adapt a phrase. If you want a particular operation done first. divide by 2 gives 6. like so: PRINT (8+12)/4 I always imagine parentheses as a pair of protective arms huddling two numbers together. 4-2 is 2. Here is an example: PRINT (((3+4)/7)+((6-2)/2))/3 What does this mess mean? The way to decode a monstrosity like this is to start with the innermost operation(s) and work outward. Your second objection might be. You can use parentheses to build all sorts of intricate arithmetic expressions. add 3 gives 5. The parentheses become like the bonds of true love. If we do the division first." So much for ridiculous metaphors. subtract 2 gives 5. "OK. The same thing applies to multiplication and division: PRINT 3*4/2 If we do the multiplication first. multiply by 3 gives 6.It doesn't matter one bit whether the addition or the subtraction is done first. the . protecting them from the cold winds of operator precedence. not the 4. the parenthesis pair. how do we get the computer to add 8 to 12 before it divides by 4? The answer is to bring in a new concept. how do we get the computer to do the calculation that we really wanted:" PRINT 8+12/4 In other words.

Now notice that both the 7 and the 4 are surrounded by a complete pair of parentheses. gee. parentheses protect relationships. Finish up the operation: PRINT (3)/3 Clear out the parentheses: PRINT 3/3 And there is the answer: PRINT 1 This long exercise shows how the computer figures out a long and messy pile . and replace the "6-2" with a "4". Let's make them come true: PRINT ((1)+(2))/3 Well. Remember. They are innermost because no parentheses serve to break up the computation. now we have more numbers floating inside extraneous parenthesis. So get let's get rid of those excess parenthesis: PRINT ((7/7)+(4/2))/3 Now we have another pair of uncluttered operations: 7/7 and 4/2. Out go the extra parentheses: PRINT (1+2)/3 Now we're getting so close we can smell it. a pair of parentheses around one single number is a waste of time. you would see that the big long command is equivalent to: PRINT (((7)/7)+((4)/2))/3 All I did to get this was to replace the "3+4" with a "7". not numbers. because you don't need to protect a solitary number from anything. and so is the 6-2. Now. If you were to mentally perform these operations. Having a pair of parentheses around a number is like putting a paperclip on a single piece of paper.3+4 is an innermost operation.

why don't I just say 12. always count your parentheses to make sure they balance. For example. no more. it creates a box &emdash. no cookbook for building expressions. why do we need code words for simple numbers? If I want to mess around with the number 12. How do you create such a pile? There is no specific answer to this question. use parentheses. group them together with a pair of parentheses. If you are willing to continue. First. I can give you a few guidelines that will make the effort easier. do it. no less. The box is given a name so that we can talk about it. a variable &emdash. we learn to talk not of a number itself. I can now show you an idea that will take you a little further than you could go with a calculator. you will generate a syntax error. and if it gives you some insurance. Indirection is one of the most important concepts associated with computers. when in doubt. then you must have five left parentheses &emdash. Second. VARIABLES Congratulations! All of this learning has catapulted you to the level at which you can use your expensive computer as a $10 calculator. try this command on your computer: FROGGY=12 This command does two actions: first. it puts the number 12 into this box. whatever it might be. second. If your parentheses don't balance. From here on. It is the concept of indirection as expressed in the idea of a variable. we can talk about FROGGY instead of talking about 12. It is absolutely essential that you understand indirection if you are to write any useful programs. but of a box that holds the number. that we will call "FROGGY". Using extra parentheses is like using extra paper clips: it is a little wasteful but it doesn't hurt. You might wonder. In the simplest case of indirection. Whenever you want to make sure that a pair of numbers are calculated first. instead of going through all this mumbo-jumbo about FROGGY? . indirection is a concept that can be applied to many real-world considerations.of parentheses. If you have five right parentheses. More important.

For example. 1:22:30. How far can you travel in two hours?" This is a simple arithmetic problem. Time is a variable whose value was 1:22:30 for one second. but behind it lies a much more interesting and powerful concept. then you have not fully grasped the concept of indirection. "What time is it?" I say." That number. and whatever the time is. Thereafter. Variables are the means for doing this. Do you remember your grammar school arithmetic exercises: "You are travelling at 40 mph. There is an experimental effort underway at some computer science laboratories to develop a computer language in which the user is not required to think in terms of indirection.34 and another day it might be $5327. If. but at any given time has exactly one number. When we use an equation like this. Let's say that you and I are having a conversation about time. It is true whatever the speed is. When we think about time.34. but the time must come when you unbolt the trainer wheels and think in terms of the relationship itself. we instead think of time as a variable that can take many different values. The importance of indirection is that it allows us to focus our attention on grander relationships. suppose we talked about a different number: the time. For example. The user of such languages . not merely its application in a few examples. "The time is 1:22:30. and what the time is. 40 mph for 2 hours gives 80 miles"). whenever you think of time. but you have to admit that it is a bonafide number. It lies in the equation distance = speed * time The big idea here is that this equation only makes sense if you forget the petty details of exactly what the speed is. and is a total perversion of the philosophy of computing.The trick lies in the realization that the actual value at any given instant is not the essence of the thing. we don't fixate on the number 1:22:30. It is called "programming by example". You say. is formatted in a strange way. we transcend the petty world of numbers and focus our attention on grander relationships between real-world concepts. do you think of 1:22:30? Of course not. of supporting your weight as you learn to walk. you must use examples ("Well. This is the essence of a variable: something that could be any of many different numbers. to understand this equation. your speed is a variable: sometimes you are going 55 mph and sometimes you are going 0 mph. Your bank balance is a variable: one day it might be $27. Examples are a useful means of introducing you to the concept.

" Again. Take little Johnny Smith. the distance was 20 miles. our program is meant to work with the variable whatever its . to think in larger terms of relationships between variables. when the speed was 20 mph and the time was 1 hour. instead. We can save a number into a variable. the computer is able to infer the correct relationship. multiplying or dividing other numbers by the variable. you must have the courage to use your mind. The proper relationship between human and computer makes the human the thinker and the computer the drudge. it is a step backwards. When we say. but about children and parents in general. And it is a number. we are making a general statement about the nature of human beings." After the user succeeds in listing enough examples. In truth. for it reverses the relationship between human and computer. while the computer engages in the exalted thinking. the user would tell the computer that "When the speed was 40 mph and the time was 2 hours. he provides many examples of their effects. the distance was 80 miles. "Children look like their parents". the important concept is not about Johnny and Fred and Wilma. Instead. Unless.does not describe concepts and relationships in their true form. asking "Which children look like which parents?" We all know that the noun "children" applies to any children. Time to get back to variables themselves. his parents are Fred and Wilma Smith. not merely individual numbers. only we don't care when we write the program whether that number is a 12 or a 513. changing its value. A variable is a container for a number. then grab a specific child off the street and plug him into this verbal equation. It forces the human to do the drudge work. Only the most literal of nincompoops is troubled by this statement. We use indirection in our language all the time. the user would not tell the computer that "distance = speed * time". In an extreme application of this philosophy. of course. you enjoy being a drudge. using it just as if it were a number itself. without being forced to think in terms of grand generalities. if you want a specific case. The computer then draws inferences for the user and engages in the indirection itself. It is a variable. and thenceforth perform any operations on the variable. listing lots of petty examples. Programming by example appears to be a new application of artificial intelligence that will make computers more accessible to users by allowing them to program the computers in simple terms. Then the statement becomes "Johnny Smith looks like Fred and Wilma Smith. To realize this relationship. The concept of indirection is not confined to mathematical contexts.

as demonstrated by this example. 4) Variables are "indirect numbers" and can be treated like numbers. you can PRINT. . The computer remembers that FROGGY has a value of 15. 5) You set a variable's value with an assignment statement. operators. 3) Parentheses defeat the normal rules of precedence. 6) Anything you can calculate. It will then put that 16 into FROGGY. It is called an assignment statement. how can a number equal itself plus 1? The answer is that the line presented above is not an equation but a command. and add 1 to it. this equation must look like nonsense. 2) Multiplication and division have precedence over addition and subtraction. Try this: FROGGY=3*5 PRINT FROGGY Now make some changes: BIRDIE=FROGGY+5 PRINT BIRDIE Not only can you put a number into a variable. getting a result of 16. for its true function is not to declare an equality to the world but to put a number into a variable. and retrieves that value to calculate the value of BIRDIE. An assignment statement tells the computer to take whatever is on the right side of the equals sign. which happens to be 15 just now. calculate it to get a number. Thus. and variables. Some exercises are in order. It is time to summarize what we have learned before we move on to deferred execution: 1) You can form an expression out of numbers. and put that number into the variable on the left side of the equals sign. but you can also take a number out. the above assignment statement will take the value of FROGGY.value might be. Now for something that might really throw you: FROGGY=FROGGY+1 If you think in terms of algebra. After all.

All of the things you have learned so far. it all depends on how big a command you consider storing. One does not idly converse with a computer. This still may seem a bit silly. A command that is executed now happens once and is gone forever. The question I take up in this section is. We can give a command right now and expect that it be executed right now. and the next. When does the computer execute your commands? You might think the question silly. . one instead issues commands. sounding like a temporary reprieve from a death sentence. DEFERRED EXECUTION This rather imposing term. After all. In the context of computers. are commands that tell the computer to do something. execution means nothing more than the carrying out of commands. There isn't much point in storing a simple command such as "PRINT 3+4". If you could store all those steps the first time. and the next. I want it executed NOW. and later the next day. You issue the command. when I issue a command. But what if you have a big calculation that has many steps? Typing in all those steps every single time you wanted to do the calculation would be a big job. you didn't buy the computer to sit around and wait for it to execute your commands at its leisure. Why should anyone bother recording a command for later reference? If I want to PRINT 3+4 sometime next week. and then call them automatically every time you needed to do the calculation. as many times as you want. but a command that can be executed later can be executed later tomorrow. and all of the things that you will learn. not later!" But there are indeed times when it is desirable for the computer to be able to execute your commands later. and the computer executes the command. let's move on to the next topic. What a wonderful idea! There is a term we use for this wonderful idea: we call it a computer program.With these items under our belts. "Computer. I can imagine you barking in true military style. then you would have saved a great deal of time. but it would be even more useful to be able to record a command right now and execute it at any later date. in truth means something far less dramatic. why don't I just type "PRINT 3+4" next week when I need it? Why go to the bother of some scheme for storing that command for later use? The answer is.

Each variable can take different "values" &emdash. the President can be Washington. But my favorite example is the Constitution of the United States of America. Lincoln. it is rather like the boss at the factory saying to the workers. There is an interesting analogy here. Follow these instructions. you don't have to worry about him or her any more. or the Supreme Court. ("OK.") A much more efficient way is to explain the entire process to the worker before he or she starts work. the Congress. It would be wasteful to stand over each worker. A cookbook is a set of commands that tell you how to make food. This is analogous to the storing of commands for a computer. Once the worker has memorized the process. I don't even know what the instructions are. So the concept of deferred execution is really not some weird new idea that only works in the silicon minds of computers. Now put the nut onto the bolt. Suppose that you were the boss at a factory. When you buy a computer program and put it into your computer. tightening up the sloppy wording. the user. What is particularly curious is the concept of a program that you. making sure that the commands would work in all conceivable situations. now put that short screw into the hole at the top. Like a computer program. it has variables: the President. the programmers have spent a long time getting all the bugs out. Show me a computer program with that kind of performance record. you are instructing it to execute all those commands that were stored by the programmer." The concept of deferred execution is not unique to the computer. This document is composed of a set of commands that prescribe how the government of the USA will operate. and so on.. but the commands are the same regardless of the "value" of the President. and when. Roosevelt. the Supreme Court. did not write. telling him or her what to do at each step of the manufacturing process. It specifies who will do what. It's been around for a while. saved for future reference. Like any computer program. In the corporate world we have the venerable "Policies and Procedures Manual" that tells us how to get along in the corporate environment.A computer program is nothing more than a collection of commands for the computer. When you tell the computer to run a particular program. but I like the machine. the Congress. and how. And like any real computer program. Now.. Despite this. it has worked very well for nearly two hundred years now. Good. a great deal of effort was expended getting each part of the Constitution just right. "Here is a book of instructions for how to build a new machine. We see it in a variety of places in our regular lives. With .

The sequence with which commands are executed can be vitally important. 2. Those numbers in front of the commands &emdash. and those three commands together caused it to print the "20". It remembers! Even better. Break out the champagne. To prove it to yourself. uncluttered by the complexities of the real world. the computer is the place to see it clearly. How do you get deferred execution on your computer? With BASIC. They also specify the sequence in which the commands are to be executed. the technique is simple: give numbers to your commands. The computer will save them for later use. though. command #2 second. Consider this sequence of commands: . type LIST. Congratulations. and 3 that began the lines &emdash. Where earlier you typed: FROGGY=3*5 BIRDIE=FROGGY+5 PRINT BIRDIE Now type this: 1 FROGGY=3*5 2 BIRDIE=FROGGY+5 3 PRINT BIRDIE Those numbers in front of the commands tell the computer that these instructions are meant to be executed later. clean context. and command #3 third. If you really want to understand the idea of deferred execution. Sure enough. You have written and executed your first computer program. the 1. deferred execution is used in a very pure. Type RUN The computer will respond almost instantly by printing "20" immediately below the command RUN.computers. those numbers actually tell the computer more than the mere fact that you intend the commands to be executed later. it can now execute all three commands for you. The computer automatically sorts them and executes command #1 first. It executed all three commands in your little program. the computer will list the program that you typed in.

The command for doing this will probably look something like this: SAVE"MYPROGRAM" Unfortunately. When you get a program finished the way you want it. then the next. making sure that they are in the order you want. Move your hand away from the walnut. then command #30. you are wiser than the Founding Fathers. and then they made a provision for adding amendments to their masterpiece. . consider the wisdom of the Founding Fathers. the computer won't allow you to add a command #2 1/2. That's why we give numbers to these commands: it makes it very easy for the stupid computer to get the right commands in the right order. and so on. and someday you need to change your program. . you would truly appreciate the importance of executing commands in the proper order. you must tell the computer to save the program to your diskette. . why would anybody want to number their commands by 10's instead of just plain old 1. You might wonder. They knew that. no matter how good their constitution was. and trying them out with the RUN command. Just keep adding commands. . Hit the walnut with the hammer. then does command #20. You can now write very large programs. and up. someday there would be a need to change it. 3. what are you going to do if you need to add a new command between command #2 and command #3? Sorry. of course. . you just call it command #25. Now. and so on. or if you want to save it before ending a session with the computer. 20. The computer is smart enough to be able to figure out that 10 is smaller than 20. and expect no need to change your program. They wrote the best Constitution they could. . and executed #1. But if you number your commands 10. Put the walnut on the table. It always starts with the lowest-numbered command. . . Well. . then if you need to add a command between #20 and #30. . Unless. 2. 30. 3. 30.1. Now. . and then goes to the next larger number. . 20. and so on. if you got the commands in the wrong sequence. . 3. Most BASIC programmers number their commands 10. . you will probably need to type . . it isn't necessary to number the commands 1. if you number your commands 1. 2. and so it starts with command #10. . whatever that is. 3. then #3. 2. then #2. since all computers are different. giving each a line number.. 2. . By the way.

the INPUT command has vast implications for programming. this may be an exciting revelation the first ten or twenty times. An example shows how simple it is: 10 INPUT FROGGY 20 BIRDIE=FROGGY+5 30 PRINT BIRDIE If you were to RUN this program. and 2) that the name isn't too long &emdash. If you don't save the program. but eventually it does get a little boring to be told for the umpteenth time that 3*5+5 is 20. about all the computer will care is that 1) you don't give it a name that it's already using for something else. The question mark is a prompt. would always calculate 3*5+5 to be equal to 20. Then it will proceed with the rest of the program. it is waiting for you to type a number and press RETURN. I want to introduce you to the INPUT command. The "MYPROGRAM" part is the name that you give your program. usually 8 characters is the limit. you will have to type something just like the SAVE command. This little command allows the computer to accept input from the keyboard while the program is running. Up until this point. When you want to get your program back. Call it "THADDEUS" or "AARDVARK" or "ROCK". With the INPUT statement. INPUT One last topic and we are done with this chapter. Despite its simplicity. Your first program. though.something slightly different from this. for example. you would see a question mark appear on the screen. you could type in a different number each time you ran it. and get a different answer. the computer's way of telling you that it is expecting you to do something. You could . You'll still have to tell it the name of the program that you want to load. the programs you could write would always do the same thing. you can start to have some variety. When you do this. That's all the INPUT statement does. it will take that number and put it into FROGGY. Now. You can give your program almost any name you want. only you type "LOAD" instead of "SAVE". it allows you to type in a number for the computer to use. In this case. then it will be lost as soon as you turn off the computer or load another program. Using the program listed above. Look up the exact wording in your BASIC manual under "Saving a Program".

no!") But. that's how simple programs work. It is the concept of program flow. Every program traces a path as it executes. So too does the computer move from one command to another as it follows the program flow. Perhaps we could even make a movie out of a single program's execution: Our story starts with FROGGER set equal to 4 ("Wow!"). Wowie. just like a movie does. this is only chapter 3. Then. carrying out first one command. then the computer stops executing the program. and discover that 8+5 is 13. At least. and then the heroine does something heroic. and then another. then you could type in 9. The program flow follows a straight path from the beginning of the program to the end. quick as a flash. and then that happens. imagine a movie in which . you could type in a big.type in 8. Program flow is similar to the concept of a storyline for a movie: first the heroine does this. and they all live happily ever after. but it does show the similarity between program flow and storyline. he added 12 to FROGGER! ("Oh. and another. then the third. zowie! Aren't computers impressive? Have patience. In the end. The story moves from one event to another as it follows the storyline. the fourth. all of a sudden. The best way to appreciate branching program flow is to imagine a movie that you could change. and so on until it reaches the end of the program. until it reaches the end of the program. and learn that 9+5 is 14. The important concept here is that the program flow starts at the first command of the program. Decisions PROGRAM FLOW I begin this chapter by introducing you to a new concept that you probably already understand intuitively. he printed both FROGGER and BIRDIE. For real thrills. Granted. and find out that 279+5 is 284. and then somebody else does something. moves to the second command. ("Yay!"). this would not make a very exciting movie. and they were both correct. scary number like 279. But in this chapter I am going to introduce you to something you will never see in the movies: program flow that branches. Chapter Four Decisions. For example. he stored the answer into BIRDIE ("Whew. that was close!").

the British commander. planning for every possible contingency. Suraj-ud-Dowlah. India was won by sheer force of decision-making power. celebrated the victory he felt certain to achieve on the morrow. Well. "I'll just wait in the house until morning". our innocent maiden chirps. Perhaps a little story will drive home how crucial this religious devotion of ours is. the dummy. The night before the battle. the Indian commander. or technological superiority. But in this case. or superior firepower. " On second thought. reasonable thing. thorough. or better discipline. what makes a bad movie makes a good program. Blood-red eyes peer from dark windows. We take it for granted.000 men and 53 cannons. what if the movie could change in response to your wishes? When you cry out." If you think about it. Robert Clive. spent the night meticulously going over every aspect of the coming battle. Clive. inspecting troops. "Don't go into that creepy house!" she pauses and says. not realizing the degree to which we worship at the altar of decision-making. "Don't go into that creepy house!" But in she goes. So let's talk about branching. I think I'll just wait in the car. and they would as dull and boring as the rest of us. abandoned house. not by heroism. you'll probably agree that movies like this would not be as powerful or as interesting as regular movies. In 1757 India was a semi-autonomous collection of principalities under the partial domination of European powers. by contrast. led a tiny army of 3. It was won. Precisely what is a decision? How do we make decisions? At heart. a decision is a choice between options. France and England contended for primacy on the Indian subcontinent.000 men and 8 cannons against an Indian force of 50. but by careful.the beautiful young heroine's car mysteriously breaks down on a dark and stormy night in front of an old. The odds looked bad. DECISIONS The essence of branching lies in decision-making. to say the least. The act of making decisions carefully is one of the central components of Western civilization. When the battle was fought. "NO!" you cry out. The battle of Plassey delivered India into the British Empire. After a series of complex diplomatic maneuvers. Three steps are required in the decision-making process: . the British forces emerged triumphant. positioning his meager forces with painstaking care. meticulous planning. the heros and heroines would always do the mature.

let's not dawdle on fine points when time is so short. if we attempt to swerve to the right. we must now identify our criteria for choosing between options. we choose the option "swerve to the left". From this assessment we conclude the following: if we attempt a straight-line brake to a stop. These are the little nasties that demoralize our efforts to decide things carefully. or hit the brakes and stop here. and if we attempt to swerve to the left. that car is coming fast! Having identified our options. the condition of the road surface. "It's too complicated to figure out. is.1. Identify the options available 2. I'll just choose arbitrarily. so we must think in terms of probabilities. but we don't have time to debate. Our decision criterion. We throw our hands up and declare. Our prime criterion is. Suddenly an oncoming car makes a left turn directly in front of you. What do you do? Let us begin by dispensing with all the nonsense options such as "Play a game of bridge" or "Whistle Dixie"." It is sad to see people abandon their greatest human birthright. the avoidance of a collision. and the intentions of the other driver. Evaluate criteria and resolve the decision An example might show this process in action. This example also demonstrates the fact that most decision-making is bedevilled by ugly complications and confusing uncertainties. we cannot be certain as to the efficacy of any of the options. We gauge the relative positions and velocities of the two cars and assess the probabilities of avoiding collisions of each of the three options. That is an example of decision-making. again. Given our uncertainties about the speed of the oncoming car. about to enter an intersection. Suppose you are driving your car. There might be more. "Which option has the greatest probability of avoiding a collision?" Again. Identify criteria for choosing between options 3. but. then. of course. the probability of collision is moderate. Let us focus on the options that might avert an accident. . Since our decision criterion is the lowest probability of collision. the probability of collision is very high. we could get snazzy and throw in such considerations as the fact that an impact on the driver's side of our car is more likely to injure us than an impact on the passenger side. the probability of collision is low. swerve to the left. Three simple possibilities come to mind: swerve to the right.

If team A has the higher score. or it doesn't. is there? It's either true or false. C. "team A is the winner". And "action" is simply. It can be a simple true-false or yes-no type of criterion. There is another way to deal with complexity and uncertainty in our decision-making efforts. Instead of asking. then team B is the winner. "Action" is the option that is selected. the football game is a decsion-making process that determines the winner. There is no uncertainty or equivocation with "condition": it is one or the other. then team A is the winner. In the case of football. or D. just try the example: "condition" is "team A has the higher score". the criterion for choice between the two options becomes ridiculously simple. How can we reduce decision-making to its absolute essence? The first step in this process is to reduce a complex decision to a series of binary choices. To determine the best football team in the National League. When we are considering taking an action. That way is to strip away the extenuating circumstances. If team B has the higher score. There's nothing abstruse about that. sometimes it is possible to reduce a decision to "Do I take the action or don't I?" This yes-no type of decision is the simplest possible way to approach decisions about actions. Instead. until there is but one ultimate victor. should I take decision A. If this all sounds strange. twelve-sided game. to cut through the underbrush of complicating factors and get down to the heart of the matter. B. the statement becomes: IF (team A has the higher score) THEN (team A is the winner) . Choosing between two things is always simpler and easier than choosing between many things. we play a series of binary games. we can use a process of elimination rather like that used in sports playoffs. either team A has the higher score. Thus. It takes the form: IF (condition) THEN (action) "Condition" is something that is either true or false. we don't throw all the football teams in the league into a single stadium and have them play one monstrous.the ability to exercise free will by making decisions. Sometimes we can simplify even further. always pitting victors against victors. We have now arrived at a surprisingly simple formula for making decisions. In the case of a binary decision. each game determing one victor and one loser.

The symbols for these are ">" (greater than) and "<" (less than). So we could have the following code: 40 IF FROGGY=BIRDIE THEN PRINT"They are equal!" 50 IF FROGGY<>BIRDIE THEN PRINT"They are not equal!" A particularly useful aspect of logical expressions is their ability to evaluate inequalities &emdash. The condition-part is a little trickier. the command-part is any regular BASIC command. and it looks like this: IF condition THEN command In this statement. It is a logical expression. evaluate the statement as false. then you are ready to use it in your programs. They can evaluate equality with the equals sign (=). It is a statement. such as FROGGER=5 or PRINT BIRDIE. The symbol to use for this is <>. A logical expression is not a command. I command you to put a 5 into FROGGY!" But in line 20. Here's an example of what I mean: 10 FROGGY=5 20 IF FROGGY=6 THEN PRINT "YOU GOOFED!" Line 10 is a command. as in the above example. "Computer. You can get much more complex than that example if you want: 30 IF (FROGGY+2)*5=(BIRDIE-7)/3 THEN PRINT "FROGGY'S the one" For that matter. The statement in BASIC that makes decisions is called the IF-statement. for this is exactly the way that decisions are made in BASIC.If you understand this simple concept of decision-making. Together. because FROGGY is actually 5. they mean "is not equal to". but that doesn't make it the same. a "less than" sign followed by a "greater than" sign. the reference to FROGGY is a logical expression. you can also determine if two numbers are unequal. The computer will. It asks the computer if FROGGY really is 6. whether one number is bigger or smaller than another. and so it will not print "YOU GOOFED!" Logical expressions can take many forms. I always get . of course. a declaration that may or may not be true. it tells the computer. Sometimes a logical expression can look just like a command.

How do you put the two factors together? In most BASICs you can solve this problem with Boolean operators. For example. There are three ways to add richness to the decision-making that we can do with the IF-THEN statement: compound conditions. yes-no decisionmaking may look great in a program.them straight by thinking that the big guy is on the big side of the sideways V. but you'll be surprised at how much you can do with this simple IF-THEN statement. you can get very messy with the logical expression: 80 IF ((FROGGY-7)*12)+3 > ((BIRDIE+4)/4)-8 THEN PRINT "What a mess!" Now let's lean back for a moment and consider broader issues. but only wants to consider teenagers whose age is between 13 and 16? The program must consider two conditions: whether AGE is greater than 13.g. Mind you. but what good does it do in the real world? It turns out that we can now use these simple decisions like building blocks to address a much more complex range of decisions. then the result is true only if both expressions are true (e. Now that we have reduced decision-making to its simplest form. You may remember that I began this discussion by emphasizing the need to strip away petty details and get down to the heart of the matter. thereby creating a third. and whether age is less than 16. Their use is illustrated with these commands: 60 IF FROGGY>BIRDIE THEN PRINT "FROGGY is bigger than BIRDIE" 70 IF FROGGY<BIRDIE THEN PRINT "FROGGY is less than BIRDIE" Just as with the equality symbol. compound logical expression. COMPOUND CONDITIONS Sometimes you may want to consider several factors before taking an action. suppose that your program is considering the age of the various people it is working with. we must now return to the question of making real-world decisions. The general rule is pretty much common sense: AND: If you AND two logical expressions together. we won't be able to solve all the world's problems. but they are used much more precisely in BASIC than in English. compound commands. "AND" and "OR". You use these operators to couple two logical expressions. These are simple words. if expression A AND expression B are both . All of this simplistic. and multiple options..

First. it's quite practical to think of logical expressions in much the same way that you think of arithmetic. Let's try it with the last expression in the list. Suppose. OR: If you OR two logical expressions together. And indeed. you are working with just plain old true-false answers. substitute that result into the expression.true).).g. only instead of working with numbers. look at each inequality and determine whether it is true or false. then the result is false. both are true.. then the result is true. You will recall that the rule for AND is that when both expressions are true. If it generates confusion. then the result is true if either expression is true (e. just think of the parentheses the same way that you think about parentheses when you calculate numbers: figure out the innermost parentheses first and work outward. if either expression A OR expression B is true. In fact. that AGE has a value of 14. If both expressions are false. for example. That gives: ((TRUE) AND (TRUE)) OR (FALSE) Now discard unneeded parentheses that mark off single expressions: (TRUE AND TRUE) OR FALSE Now let's collapse that TRUE AND TRUE phrase into a single result. So now we have: . Here are some examples of true and false statements: StatementValue AGE > 13 TRUE AGE < 16 TRUE AGE > 99 FALSE (AGE > 13) AND (AGE < 16) TRUE (AGE > 13) AND (AGE > 99) FALSE (AGE < 16) OR (AGE > 99) TRUE (AGE > 16) OR (AGE > 99) FALSE ((AGE > 13) AND (AGE < 16)) OR (AGE > 99) TRUE This last example demonstrates the use of parentheses with logical expressions.

If the inputted number is unreasonable. without explaining. Therefore. it would ask for the age a second time." 90 (this is the rest of the program) This code would not do what you want. lines 70 and 80 are executed regardless of the results of the IF-THEN statement. and thank the user. Your program might look like this: 50 INPUT AGE 60 IF (AGE < 1) OR (AGE > 99) THEN PRINT "That age is odd. then thank the user for being patient. please repeat. for example. In other words. and you want to check to make sure that the number that the user types in is reasonable. consider this bit of code that one might see in a football program: 70 IF (DOWN = 4) AND ((YARDS > 2) OR ((THEIRSCORE-OURSCORE) < 20) THEN PRINT"PUNT!" Can you figure out what it means? COMPOUND ACTIONS What happens if you want to execute more than one command if the condition of an IF-THEN statement is satisfied? Suppose. then the result is true. that you have a program that asks the user to input the age of a certain person.(TRUE) OR FALSE Discard the unneeded parentheses: TRUE OR FALSE And now remember the rule for OR: if either one or the other expression is true." 70 INPUT AGE 80 PRINT "Thank you for your patience. you want to print a message telling the user that and ask for him to input the value again. Even if the age were correct. our expression works out to be: TRUE The value of compound expressions is that they make it possible to evaluate very complex situations. So there is the problem: how do you put multiple lines inside the "THEN" part of an IF-THEN statement? . For example.

you simply type "GOTO n". So. It is called "END" and it means just that. But the GOTO statement commands the computer to jump to whatever line number is specified." 1030 GOTO 70 This code will execute properly. Then it will execute those lines. then the next. This is a very powerful command. even though there was no error. At the end of the group. What happens when the computer reaches the end of the program? It will eventually work its way through all the line numbers higher than 70 and come to lines 1000-1030. There is one minor problem with it. where n is the line number of the line you want the computer to go to. it will do nothing in line 60 and go straight on to line 70. the next. If the age is OK. As you remember. you can tell the computer to GOTO the line from which it had earlier come. The command is called GOTO and to use it." 1010 INPUT AGE 1020 PRINT "Thank you for your patience. then when it is done it will jump back to line 70 to resume the normal program. When the computer reaches the END statement. a technical detail. please repeat. and so on until the computer reaches the end of the program. Oops! The solution to this is a minor command that I never bothered to mention before. it will immediately jump there and continue computing from line 60. It allows you to create whole groups of commands and execute them all just by telling the computer to GOTO the first command in the group. In our example. you should always put an END statement after your regular program but before all the little chunks of code like the example.The answer relies on a new command that is very simple in operation. if the age is wrong then the program will jump to the corrective code in lines 1000-1030. For example. the program flow starts with the first command in the program and continues to the next largest line. it stops executing the program. a correct way to solve the problem of the bad age input would look like this: 50 INPUT AGE 60 IF (AGE < 1) OR (AGE > 99) THEN GOTO 1000 70 (this is the rest of the program) 1000 PRINT "That age is odd. The GOTO command breaks the normal program flow. If you tell the computer to GOTO 60. the END statement might look like this: .

" 64 INPUT AGE 66 PRINT "Thank you for your patience. MULTIPLE OPTIONS Now we tackle the toughest problem: how do you put together all of these binary IF-THEN statements to handle complicated sets of options? For example. This approach cuts down on the amount of "spaghetti code" that you create. The same thing is true in English: no statement that isn't written with no negatives is not knotty to figure out. if you dig through it diligently. The difference is one of style. If an expression is true. It's a simple idea. Let's say that it has stored the probability of avoiding a collision by swerving to the . Programs like this are very confusing to read. you can figure it out." 70 (this is the rest of the program) This code reverses the logic of the IF-THEN statement by using the NOToperator. in effect. but it requires a backwards approach. not function. Since this latter approach is cleaner than the former approach. Line 60 now says. then NOT-expression is true.200 END As it happens. and so they are difficult to work with. How could it choose among three options with its IF-THEN statement? The answer requires the use of several IF-THEN statements in a sequence. then NOT-expression is false. This operator just takes the opposite of a logical expression. but it can be confusing to figure out. The code for it looks like this: 50 INPUT AGE 60 IF NOT ((AGE < 1) OR (AGE > 99)) THEN GOTO 70 62 PRINT "That age is odd. then skip over lines 62-66 to line 70. Spaghetti code is code that is full of GOTO statements. jumping all over the program. how would a BASIC program handle the traffic collision problem that I used at the beginning of this chapter? Let us assume that the computer is driving the car (Lord help us!) and is capable of calculating the probabilities of collision for each of the three options available. "if the opposite of the old condition is true. it is considered superior. If the expression is false. please repeat. However. no? Nevertheless. please remember that both approaches work just as well. there is a neater way to solve the problem of the bad age input." The advantage of this approach over the earlier version is that lines 62-66 automatically feed into line 70 when they are done without requiring another GOTO statement.

a reluctance on our part to reduce fleshand-blood issues to numerical form. The crucial element is our ability to express seemingly incalculable factors in quantitative form. There is an ambiguity when two of the three values are equal. in this case.left into the variable LEFTSAFE. They are simple. We can differentiate between decisions involving incalculable factors and decisions that are merely complex. Similarly. you will find that the program correctly deduces the correct course of action in each case. they are not expressions of free will. They are not the sort of soul-searching. It does this by examining each in turn. it has stored the probability of avoiding a collision by swerving to the right into the variable RIGHTSAFE. Moral and emotional decisions like. It seems dehumanizing to reduce issues to mere numbers. the program will prefer straight over right and right over left. . and simililarly for STRAIGHTSAFE. that is an arbitrary aspect of the order in which the statements are executed. we should not minimize the value of this kind of decision-making. agonizing decisions that we humans make. mechanical decisions. You might be surprised to know just how many decisions really can be submitted to calculation. "Should we get married?" fall into the incalculable category. such as "Which computer should I buy?" are at least theoretically calculable. Yet. It must decide which probability is highest and indicate the proper course of action. Part of the problem is our own squeamishness with numbers. but many other decisions. Here's how it's done: 50 IF LEFTSAFE > RIGHTSAFE THEN GOTO 110 60 IF RIGHTSAFE > STRAIGHTSAFE THEN GOTO 90 70 PRINT "GO STRAIGHT" 80 GOTO 200 90 PRINT "SWERVE RIGHT" 100 GOTO 200 110 IF LEFTSAFE < STRAIGHTSAFE THEN GOTO 70 120 PRINT "SWERVE LEFT" 200 END If you trace the program flow for each of the three possible cases. What does it all mean? The important lesson here is that the computer really can make decisions. CONCLUSIONS This has been a long and involved chapter.

One command from that section looks something like this: 2240 INTEGRITY=INTEGRITY . something we revere as special.But what is so "mere" about a number? Precisely what is wrong with expressing ideas in numerical form? Let's consider a specific example. then SHOULD will have a low value. but rather from the relationship itself. no matter how . lies and theft &emdash. then SHOULD will have a high value. while others are possessed of little integrity? Is it not a small jump from "great or little" integrity to "100 or 20" integrity? Does not the numerical form allow us greater precision? I will press the arguement even further. In other words. had I written 2240 INTEGRITY=MURDER + LIES + THEFT that would be blasphemy. not guarantees. beyond the soulless world of numbers. which measures the degree to which the player should help another nation in time of need. There is nothing intrinsically blasphemous about a language. Is this not a reasonable concept? Does it not reflect the truth of the world? Numbers and formulas are only a way to express ideas. magic. As you might guess. Ideas can be blaspemous. Integrity does not arise from murder. But is it not a quantity that a person can possess more or less of? Are not some people distinguished by great integrity. The value of SHOULD is derived from treaty commitments made by the player. Now.SHOULD Talk about blasphemy. if I have made solemn treaty commitments to you. integrity is one of our most cherished human virtues. My program has a section dealing with the ramifications of a failure to honor one's commitments. The blasphemy does not arise from the quantification of the relationship. They are another language. The idea expressed in line 2240 is simple: if you fail to honor your commitments. One of the variables I used in the program is called "INTEGRITY". here is a formula for integrity! Before you cross yourself and reach for the garlic. consider this: line 2240 does not present the formula for integrity. My program uses another quantity called SHOULD. then your integrity falls in proportion to the solemnity of the commitment. I once wrote a program (Balance of Power) that concerned geopolitical conflict. this variable keeps track of the integrity of the player in his dealings with other nations. it presents a formula for integrity. whereas if I have made only minor assurances. though.

You might be tempted to dismiss computer programming as a lot of high-sounding pap. you will have made a large step into a new world.you say it. If you can learn how to express thoughts in quantitative form. But if I know . so if all I want to do is dig a single hole. But we are at last going to learn something that makes computers really useful. all such decisions should be checked against simple common sense. Decisions become much clearer when they can be expressed in calculable form. you can do arithmetic with a $10 calculator without learning all this high-faluting nonsense about variables and constants and deferred execution. that I want to dig a small hole. there is a price we pay for this benefit: the cost of the tool. We even use "tool-tools" &emdash. and it is very important that you understand the fundamental concept behind this capability. building the shovel might take me several hours. though. but you can manage without it. After all. Now. you might wonder what good it all is. hairy deal!" You would be right to dismiss computers as a waste of time if all they did was calculate and branch. Or I could go build myself a shovel and then dig the hole in one minute. ultimately. TOOLS We humans have come a long ways since the good old days of caves and woolly mammoths. Suppose. Chapter Five Over and over again So far you have learned a number of things to do with your computer: arithmetic. The computer's ability to make decisions is interesting. I am better off using the rock. In other words: "Big. We use tools for almost everything we do. fat. One of the key factors contributing to our progress has been the development of increasingly powerful tools. Of course. I could grab a nearby rock and scrape out a hole in five minutes. input and output. Just exactly what is a tool? It is a device that allows us to execute some special function quickly and more easily than would otherwise be possible. tools that make other tools. for example. If you think about it. But beware of taking your new-found skills too seriously. Only a fool would take the equation in line 2240 as final truth. and branching.

it is the wheels of civilization going round. Then do another shingle. PLAY IT AGAIN. because he has painted many houses. Take the ticket from the customer's hand.that I will be digging quite a few holes in my time. If we use it over and over. tear it in half. This is the central concept behind any tool. Hammer the nail into the shingle. we suddenly become a great deal more efficient. Repetition allows us to specialize. cumbersome. to learn and hone our skills. and again. will not lie in simple computations. and another. But if we do it over and over. Then the piston goes back up and does it again. If we can develop a system (a tool) that allows us to reduce a huge job to a sequence of repetitive operations. because he has managed many companies. a carpenter nailing nails is engaging in manual repetition. Repetition doesn't make the wheels of civilization go round. automatic repetition is the repetition of the machine. while an automobile engine is automatically repetitive. You. If my shovel cost me 60 minutes to build and saves me four minutes per hole. turning the wheel that goes round. Thus. we'll have a piston that pushes down once. and another. then the savings from the shovel can really add up. But the computer can engage in automatic repetition. and return the pieces to the customer. The real value of the computer as a tool. Manual repetition is the repetition of the human. and again. Again and again and again. The calculator itself doesn't know or care anything about repetition. You pay a steep entry price to get the tool. Experience is nothing more than the end result of repetition. then. we develop speed and accuracy. then after fifteen holes I am ahead of the game. Doing something once is slow. Then turn to the next person and do it again. you enjoy a savings of time. But there are two types of repetition: manual and automatic. A painter can paint my house faster and better than I can. The difference between a . another and another and another. and again. SAM Implicit in all of this is one of the most fundamental concepts behind all technology: the concept of repetition. the user provide the repetition by using it over and over. A calculator is used in a manually repetitive manner. until the shingle is finished. An executive can manage a company better than I can. You want a machine to take you long distances? OK. This is the stuff of productivity: repetition. moving you forward. The real utility of this machine is realized in repetition. and again. then get another nail and do it again. but each time you use it. we derive the true benefit of the tool. and prone to mistakes.

orders a broom to bring some water. TERMINATING THE LOOP Do you remember the story of the Sorcerer's Apprentice? The apprentice. This statement does nothing over and over. the program moves to line 60. Any computer program without a loop is not worth writing or executing. a pen and a printing press. There is a lesson here for the beginning programmer: make sure you know how to terminate a . It is more Sisyphusean than Sisyphus himself. but the magic spell has apparently set the broom into an infinite loop. in which the program flows back to itself. at least he had a boulder to roll over and over. and the broom continues to bring more and more water. This simple loop is called an infinite loop. having overheard certain magic words.calculator and a computer is the difference between a chisel and a jackhammer. a rifle and a machine gun. This the broom does. never folding back on itself. Looping is the stuff and substance of computing. hip. But consider the following fragment of code: 50 PRINT "Hip. THE INFINITE LOOP The simplest type of loop is trivially simple to create. After it prints "Hip. An even more extreme case of an infinite loop is the following statement: 60 GOTO 60 This statement will execute forever. because it will continue forever unless you either a) press the BREAK key on your keyboard or b) reset or turn off the computer. going to itself but never doing anything. to alter the program flow. setting the room awash. hooray!" 60 GOTO 50 This is the simplest type of backward branching. Looping is truly the essence of computing. The only branching cases I discussed in that chapter were cases of forward branching. The key to this automatic repetition with the computer is called the loop. in which the program always flows forward. so he is unable to stop the broom. hooray!". You will recall from Chapter 4 that branching allows you to jump to different points in the program. hip. which directs it back to line 50. The apprentice realizes to his dismay that he doesn't know how to terminate the loop.

The infinite loop is an academically interesting beast. Being able to start a process is only half a power. then it exits the loop. input a zero. In effect. We use this loop when we know how many times we want the loop to execute. repeatedly asks for the amount of the next check until the user enters a value of 0. you are telling the computer. we just put an IF-THEN statement at the end of the loop that loops us back up to the top of the loop unless the termination condition is satisfied. PREDETERMINED COUNT This is the second major type of loop." The condition is any logical expression that can be evaluated in an IF-THEN statement. If a computer program with a loop is to have any practical value." 70 INPUT AMOUNT 80 BALANCE=BALANCE-AMOUNT 90 IF AMOUNT<>0 THEN GOTO 50 This little loop. Thus. but it represents a useless extreme. Here's a simple example: 40 FROGGY=0 50 FOR X=1 TO 10 . All we know is that the loop will be executed at least once and possibly many. many times. being able to stop it is the other half. It uses a new type of BASIC command: the FOR-NEXT loop. which might come from a checkbook balancing program. the program repeats the process until some condition is met. Here is an example: 50 PRINT "Please input the amount of the next check.loop before you start it. we normally use an IF-THEN statement to terminate the loop. do this over and over again until (blank) happens. How does one stop a loop? There are two fundamental methods: the conditional termination and the predetermined count." 60 PRINT "If no checks are left. We keep executing it until the termination condition is satisfied. it must be able to terminate the loop. The general structure of this type of loop is simple. "Computer. CONDITIONAL TERMINATION In this form of looping. We use this type of loop when we don't know how many times we want the loop to be executed.

and proceeds from line 70 to the next statement in the program. The general form of a FOR-NEXT loop is as follows: A FOR-statement goes at the top of the loop. But there is a difference between knowing how to operate a tool and knowing how to utilize a tool. when it first encounters line 50. There are very few cases of loops that do not in some way use an array. Then. The value of X is only 2. Then it goes to line 70. the computer stores a zero into FROGGY. 4. 10). Then it checks to see if X has passed the upper limit of 10 that was imposed in line 50 ("FOR X=1 TO 10"). It therefore decides to terminate the loop. and realizes that 11 is greater than the upper limit of 10 imposed in the FOR statement. it goes to the next X. The first of these is the array. An array allows us to readily deal with a group of numbers. and proceeds on to line 60. hold old are you? That's a number. 3. does nothing there. Now. which is 11. How old is your brother? Your sister-in-law? Your cousin? If you were making files on all your relatives. you might want to make a list of everyone's age. then an array is like row of boxes marked #1. In order to utilize loops. The next X after 1 is 2. Then it moves on to line 60.60 FROGGY=FROGGY+X 70 NEXT X This bit of code works as follows: first. 1) that tells the computer what value to start with for the loop variable. and so on. it stores a one into X. and so on all the way to 10. ARRAYS You now know how to construct a loop. When it reaches line 70 after the tenth pass. that specifies the last value that the computer should use for the loop variable before terminating the loop. X) that will step through all the values one at a time. which tells it to use the "NEXT X". 2) the initial value of the loop variable (in our example. An array is a group of numbers catalogued in a list. so it stores a 2 into X. and 3) the final value of the loop variable (in our example. This loop continues with X taking values of 1. For example. you must understand a variety of other concepts. We mark the bottom of the loop with a NEXT-statement. If a regular variable is like a box that holds a number. #3. #2. specifying three things: 1) the loop variable (in our example. so it automatically loops back up to line 50. the wrong way to do that . 2. where it adds X to FROGGY and stores the result (a one) into FROGGY. An awful lot happens in line 70. After the FORstatement comes the body of the loop.

We normally don't think of Grampa as person #3. You notify the computer with the command DIM. After you say DIM. you list the names and lengths of the arrays that you intend to be using in the program. If you had 10 relatives. but that's what we have to do if we are going to use arrays. Normally. if Joe is the first person. like this: 10 JOESAGE=33 20 MARYAGE=24 30 GRAMPAGE=62 and so on. notifying the computer of arrays is something you do right at the beginning of the program. but we'll get to them later in the book. To use an array. and the same thing goes for computers. I'll never know. 62. the problem with this system is keeping track of whose age is in which box. but we're stuck with it now. A typical DIM-statement might look like this: 10 DIM AGES(10) . The right way to deal with this is to save all the numbers in an array. and Grampa's age (62) in the third box in the array. 10 numbers in it. which is short for DIMENSION. As it happens.would be to store each age in a separate variable. and so on. The ages of the other relatives would go into other boxes. You must do this before you start to use the array. you'd end up with a mess. say. Then you get into all sorts of problems keeping track of who goes where. there are a number of ways to solve this. just think in terms of a list like this: # Name Age 1 Joe 33 2 Mary 24 3 Grampa 62 The array of ages is then 33. After all. Then. it's only simple courtesy to notify people up front of the expectations you'll be placing on them. and Grampa is the third person. then you would store Joe's age (33) in the first box in the array. For now. 24. Now for the technical details of implementing an array. This problem can become severe if you have a big array with. Now. you must first notify the computer that you want to use an array. and Mary is the second person. Why they gave it a dumb name like DIMENSION. Mary's age (24) in the second box.

it must instead refer to individual numbers in the array. you can't can't tell the computer to. you can only handle a single number in the array at a time. I never write a command like this: 40 AGE=5*FROGGY The problem with this command is that it doesn't tell the computer which number in the array is equal to 5*FROGGY. So. a million boxes. and said. Those boxes come out of the memory that your computer has. handed you a sheet of paper filled with numbers. that's how much memory your computer has. there is nothing that says that the number of the box has to be . You treat the array in the same way that you treat a regular variable. it tells the computer to put a value of 5*FROGGY into the second box in the array. it never seems to be enough. So don't waste your precious RAM by asking for more boxes than you need! Once you have notified the computer with your DIM-statement." ? What does that mean? Multiply each one by 5? Add them all up and multiply the sum by 5? Who knows? So our program never treats the array as a lump. The second difference between an array and a regular variable is that you must specify which element of the array you want to work with. say. How would you feel if somebody walked up to you. the program will not work. you are free to use the array. "Multiply this by 5. You want 10 boxes in this array to hold 10 numbers. or something like that? Well. to tell the computer which number you want. and the salesman yakked on and on about how it had "512K RAM". if you ask for 10 boxes. This is important. multiply the array by 5. you use parentheses. because if you try to use 11 boxes. First. Of course. then an open parenthesis. then the number of the box. Don't try to overcompensate by asking for. say. you specify the name of the array. Now. Whenever you want to refer to one of the boxes in an array.This statement tells the computer that you are going to be using an array that you will call AGES. If I have an array called AGE. no matter how much you have. then a close parenthesis. with two exceptions. That is. Remember when you bought the computer. and. you'll get 10 boxes. like this: 40 AGE(2)=5*FROGGY This command makes sense.

So you have to be careful when you write snazzy commands like the one above. and so contains numbers produced by previous computations. and that's not good. You see. AGE(5). Thus. You could say this. A loop like the above example will do that quite nicely. you don't have to always say things like AGE(2). when you create an array with a DIM-statement. if BIRDIE is. or AGE(9). say. when you first create an array. and the computer will get confused. Of course. in fact.specified as a constant. Odds are that memory was used for something else earlier. it already has all sorts of meaningless numbers in its boxes. for example: 30 BIRDIE=2 40 AGE(BIRDIE)=5*FROGGY These two commands will do exactly the same thing that the earlier example does. which isn't there. and the computer will try to store 5*FROGGY into the 11th box. You can even get snazzy with this. then 3*BIRDIE+2 will be 11. ARRAYS AND LOOPS The real value of arrays comes when you use them in loops. you can use any arithmetic expression inside those parentheses. This is a very common function. That is. they were made for each other. If you want. because we told the computer to make 10 boxes. if you want: 40 AGE(3*BIRDIE+2)=5*FROGGY This command will store a value of 5*FROGGY into whatever box is specified by the expression 3*BIRDIE+2. You've got to clear out those boxes so that you don't insult Auntie Millie by listing her age as 233. arrays and loops go hand in hand &emdash. setting all the ages to zero like the example may erase the . Of course. the computer sets aside some memory for the array. Here is a very simple example of a loop using an array: 50 FOR X=1 TO 10 60 AGE(X)=0 70 NEXT X This little loop does nothing more than store a zero into each box in the array. they will store a value of 5*FROGGY into the second box in the array. called initialization. 3.

turn right onto Hazel and follow it to the third stoplight." 100 INPUT Y 110 AGE(X)=Y 120 NEXT X This little loop will ask the user to type in the age of each person on the list."). . that's so . press on the accelerator. It is a set of steps that we know will lead to a solution. we must first design our algorithm. A good exercise is to find the largest number in an array. non-specific description of a procedure. but it doesn't put any real numbers into the array. we need the highest array value and the array number of that value. Algorithms are a useful way to figure out a problem without plunging into the picky details of writing a program. In programming terms. We want to find not one but two numbers: we want to know what the oldest age is and who has that oldest age. . That's what an algorithm is: a general. The algorithm expresses the general idea of the program. In other words. let's see how arrays and loops can work together. . it's a lot easier to translate the algorithm into a program than to go directly from your problem to the program. . An algorithm is just a strategy for solving a problem. In order to do this. Now that all the ages are properly stored in the AGE array. fuzzy version of a program. the program translates the algorithm into specific commands. Our algorithm for doing finding these numbers will be as follows: We'll start off by telling ourselves that the record-holding oldest age is 0 years old. Once you've got your general strategy figured out." You are describing the process in general terms. such as "Turn the steering wheel right 90 degrees. let's have the computer find the oldest person in our array. You use an algorithm when you give somebody directions to your home ("Go to the intersection of Elm and Hazel. You are not specifying the actual commands necessary to get to your home.chalkboard. An algorithm is like a soft. Our first task is to define what we are trying to accomplish. How do you do that? Here's an example: 80 FOR X=1 TO 10 90 PRINT "Please input the next person's age. It will then store that age into the AGE array.

Then we will sweep through the array. We will also set the record-holder as 0. all the way . For a real challenge. we should skip on to the next age. we ask. Now our only task is to translate the algorithm into some BASIC commands. we have a new record.") and print out a message if the condition was satisfied. (Of course. we need only change line 150 so that the 10 is 1000. It's that simple. but to change the loop to handle a thousand numbers. you could sort the array. we will print out our answer. which is to say. then the next. because you could search through a list of ten numbers and find the highest number in a few seconds. and you might make a mistake. What if." What is the significance of this little program? If you were blessed with a skeptical attitude. listing the oldest person. nobody.OLDESTAGE. then the next oldest. picking each age in turn." years old. somebody would still have to type in the thousand numbers. you might argue that this whole thing is a waste of time. Do you want the youngest person instead of the oldest? Just change line 130 to OLDESTAGE=999 and line 160 to IF AGE(X)>OLDESTAGE THEN GOTO 190. Then you could change the loop to test for that condition ("IF (AGE(X)>=40) AND (AGE(X)<=50). . .) There are plenty of other things we could do. But consider how easily this program could be changed. When we pick an age. so store this age into the worldrecord age. After we have done this for all the people in the array. "Is this age older than our world-record age?" If it isn't. and store its array number ("This is the 3rd number in the array") into the record-holder. instead of ten numbers.young that we are guaranteed that everyone will break that record. Suppose you wanted to find anybody between 40 and 50 years old. Read this code carefully and verify for yourself that the code implements the algorithm: 130 OLDESTAGE=0 140 WHOISOLDEST=0 150 FOR X=1 TO 10 160 IF AGE(X)<OLDESTAGE THEN GOTO 190 170 OLDESTAGE=AGE(X) 180 WHOISOLDEST=X 190 NEXT X 200 PRINT "The oldest person is person number ". there were a thousand numbers? To do that by hand would be a great deal more work. WHOISOLDEST 210 PRINT "This person is ". but if it is.

By this way of measuring.000 lines of code. Most of my computer games come out at around 10. and that doesn't include any of the graphics or sound! What is staggering about so large a program is not the sheer amount of code itself so much as the complexity represented by all that code. And Bureaucracies You may have noticed that the programming examples I have used have been getting larger and larger with the passing chapters. requiring larger and more involved examples. The use of illustrations was severely curtailed. A program is not . This is partly because the ideas I have been presenting have been getting more and more involved. Bytes. In the same way. and indeed they are. not just a few experts. my examples in the last chapter were 5-line or 6-line programs. The invention of moveable type was profoundly important because it allowed each type character to be used over and over again. practical tool. The characters could only fit into the press in a defined fashion. At the same time. the printing press is ranked as one of the most important inventions of human history. What will you print with your new press. The computer imposes constraints on our organization of data just as the early printing presses constrained the presentation of information on the printed page. Despite these restrictions. You may also have guessed that real programs must be larger than the examples I am giving. CONCLUSIONS The loop on the computer is closely analogous to the moveable type on the printing press. moveable type imposed severe constraints on the creative freedom of the author. and color was impossible to print. in different words on different places on the page. But that is too advanced a topic for this book. And the computer may well be another landmark in the history of civilization. Herr Gutenberg? Chapter Six Bits. This made possible the printing press. The size of a program is often measured by the number of lines of code written by the programmer. You can program this machine. no longer could the author scatter words across the page in any fashion that struck his fancy. you can guide it where you will. the loop is the critical concept that makes the computer a useful.to the youngest person. Real programs run considerably larger. But there is one big difference between the printing press and the computer: the computer is accessible to everyone.

is as complex as the devious ways of its many citizens. possibly keep track of this maze of interconnections and relationships? ANCIENT SOLUTIONS The problem we face here is not a new one. and train the legions that conquered the territories. . and brought peace and prosperity to a larger area. This is because the words in a book. It acts like a gigantic engine. papyri in hand. adjudicate disputes &emdash. to regulate commerce. A newly-won territory quickly became a prosperous component of the Empire rather than a poverty-stricken and sullen vassal. but a much more important factor in Roman success was the mousy bureaucrat following in the wake of the legion. The overwhelming complexity of a huge program is enough to try the courage of any programmer. We normally think of Roman legions marching across Europe.an inert mass of information like a book. these same skills insured that the conquered lands were smoothly and efficiently governed. but the Romans refined and developed the art of bureaucracy far beyond anything the world had known. What was the source of Roman power? How were the Romans able to first create and then maintain an empire over a span of nearly two thousand years? Historians cite many factors. conquering everything in sight. collect taxes. in comparison to the words in a computer program. are pretty much a loosely connected jumble. with thousands of gears and wheels and pulleys. equip. The words I chose to use in the last chapter have very little impact on the words I choose for this chapter. everything very tightly connected. than the world has known before or since. character for character typed into the computer. all packed into a very small space. The first civilization to develop effective techniques for dealing with these problems was Rome. for a civilization is itself a complex structure requiring maintenance. The task that falls on any government &emdash. by contrast. a large and efficient bureaucracy coordinated the flow of goods and people. A computer program. a program is a far more complex effort than a book. The creation and maintenance of complex structures has plagued civilization since its earliest days. for a longer time. How can one person. Rome did not invent bureaucracy. Throughout the Empire. is an immensely more demanding creature. Word for word. Such is the power of bureaucracy. or even a group of people. Roman administrative skills made it possible to raise. but a crucial factor often underestimated by the layman is the role of the Roman bureaucracy.

Each function is assigned to a single bureau. If a component is itself too large to digest. oneperson operation. the legislative. Each bureau is responsible for a single function. The third element is the set of communications procedures within the bureaucracy. and the judicial. or an MX missile. we could break the executive branch into the various departments (State. or it can be as large as the Department of Defense. the United States government. Why does a bureaucracy work? What is the source of its ability to handle complex problems? MODULARITY One strength of the bureaucracy is its modularity. A bureau can be a small. The bureaucracy is broken up into discrete chunks that are much easier to understand. Each of those three chunks includes within it a great many people. an environmental protection policy. The result? A Social Security program. going down further and further. Continue this process of breaking down into subcomponents as necessary. allow each bureau to tackle its small problem. This breaking down and putting together is one of the "big ideas" of Western civilization. It is the basis for many of our civilization's achievements. It parades under the name analysis and synthesis. It is fundamental to scientific inquiry. break them down into components. Analysis and synthesis appears in many other areas. What is it? Well. Consider. but they do not explain its strengths. for example. The second element is the assignment of functions to bureaus. etc). the executive. Each module within the structure can be broken down to smaller components. Once the problems have been broken apart and assigned. A bureau is a group of people performing a function. then put the pieces together. These three elements characterize a bureaucracy. and the modules can be reassembled to form the whole. be it broad or narrow. Commerce. The bureaus themselves constitute the first element. If you wanted more detail. break it down further into sub-components. The various bureaus must coordinate their actions. to do this requires a clear and simple communication system for transmitting work orders.Exactly what is a bureaucracy? Three primary elements determine the form of a bureaucracy. Defense. we could start off by breaking it into three chunks. Labor. assigning each component to a bureau. The bureaucracy is an example of analysis and synthesis applied to large organizations. The scientist approaches a complex and little-understood . Take all the problems that we require the US government to handle. We could then break one of the departments down into its subcomponents.

or a cure for cancer. is the simplicity of interaction between the modules. An engineer follows the same pattern in designing a machine. Suppose that I constructed a tangle of balls connected by springs. assemble their work into a new car. the key criterion. while a third can worry about engine cooling. If each module has but one simple interaction with all other modules. identifying those aspects that can be explained with existing theory and isolating the aspect that represents a mystery.phenomenon and starts by breaking it down into its component aspects. This makes it possible to focus intense attention on the single mysterious item. looking for patterns that break it up into modules that interact with each other in the simplest way. . The hidden skill in successful analysis and synthesis is the ability to see clean. when they are done. You would begin by separating the first group from the main mass. Send them off on their respective tasks. you would analyze the tangle on the basis of the lowest interaction between groups. If one attempts to subdivide a problem the way one partitions a vase with a hammer. How would you go about untangling this mess? If you studied it. One must scan the problem. This would form the basis of your untangling effort. natural ways to subdivide the problem. Once the core problem has been cracked. This is the key idea to intelligent analysis. THE INTELLIGENT HAMMER A crucial requirement for successful analysis and synthesis is that the problem be broken up in an intelligent manner. then the situation is less modular and will prove more difficult to handle. but connected to other groups of balls by only a single spring. then the situation is highly modular and ideal for analysis and synthesis. you would undoubtedly find at least one group of balls that was tightly interconnected with lots of springs. while other balls might have only one or two springs. A problem in analysis and synthesis is essentially a problem of untangling. the components can be reassembled to produce a new theory of stellar evolution. If some modules have multiple interactions with other modules. Break the problem up into components. a new chemical. As you pick through the tangle. Some balls might have many springs attached to them. And the basis for clean. Have another team tackle the suspension. you would search for easily-separated groups. one gets only a shattered mess. Put one team of engineers on the carburation system. natural subdivision. In short.

Indeed. the date that this person will start work. A messy. You would need to check your information with Personnel. they are probably taking care of details that you are completely unaware of &emdash. and they would need to check their information with you. Let's say that you are a manager in a large corporation and are about to hire a new employee. opening a personnel file on the candidate. those four pieces of information trigger a great deal of work inside Personnel. you need not worry about anything else. that you were responsible for notifying the government of the candidate's pay. number P-503. with slightly different or inconsistent information being reported to the government.An example is in order. the salary to be offered. Your interaction with Personnel is small and simple: only four items of information are required from you. Suppose. you and Personnel. new government regulations about hiring. You have interviewed a number of candidates and have made your decision. or engine subassembly has . and many springs inside Personnel. there are few springs between you and Personnel. and you would both need to check your information with the candidate. They'll take care of all the little details. that you fill out and send off to them. or bureau. obtaining the candidate's Social Security number. In short. and you and the candidate. Once a module. or whatever. Personnel has their little form. In terms of my tangled springs analogy. That's a highly modular situation. and the personnel requisition under which the candidate is being hired. you merely send a memo to the Personnel Department listing four items: the candidate's name. There is one other benefit of the highly modular environment: once you have shot off your message to another bureau. the absolute minimum of external communication between modules. for example. this situation has lots of springs running between you and the government. If you fill it out properly. and all the myriad other tasks that are required for employment in a large corporation. let us consider a situation with very low modularity. filling out all the forms for the government. home address. There is plenty of opportunity for a snafu here. but Personnel was responsible for notifying the government of the candidate's claimed deductions. Yet. Just for laughs. To implement it. and probably an internal employee number. Then both you and Personnel would have to obtain the candidate's name and Social Security number. you can forget about it. The Personnel Department will take care of all the details: notifying the candidate of the job offer. tangled situation like this emphasized the essence of good modularity: lots of internal communication within modules. telephone number.

"So long as I ship the right inputs. it will help you understand bureaucracies and analysis and synthesis better.SCORE 90 PRINT "That number is wrong. Time for an example. Anything that you can put into a regular section of program. If you think of it as a bureau within a bureaucracy. and after you have worked with it. You could write some code to check for this: 60 INPUT SCORE 70 IF (SCORE >= 0) AND (SCORE <= 100) THEN GOTO 110 80 PRINT "You typed in ". There are only two rules about subroutines: first. . You should not jump into or out of the subroutine halfway through. the concepts of modularity. but if you are a careful programmer. and all the test scores are between 0 and 100. or whatever. that the program analyzes different test scores. Suppose that you have a program in which it is necessary to get input from the keyboard several times during the course of the program's execution. you can put into a subroutine. you merely tell yourself. for some reason. Suppose further that the input must be conditioned. to that module. it will spew out the results I need. a subroutine is a closed module. Second. Please try again. It can be anything &emdash. and clear communications procedures are built into computer programming languages. for example. you would anticipate the likelihood of somebody typing in crazy test scores by mistake. It is trivially simple to implement. yet very difficult to master. you want to make sure that the right numbers are typed in. loops." 100 GOTO 60 This little bit of code insures that SCORE will always be between 0 and 100. INPUT statements. you treat it as a black box whose internal workings are of no concern. Suppose. or forms. MODULARITY IN COMPUTERS: SUBROUTINES So what does all this have to do with computers? As it happens." It simplifies your thinking. a subroutine is terminated by a new type of statement: the RETURN statement. they are expressed with pristine clarity in the concept of the subroutine.been set up and its inputs determined. A subroutine is a small section of a program. IF-THEN statements. The subroutine is one of the simplest and subtlest ideas in all of computing. analysis and synthesis. the idea will come more easily. scores like 537 or -33. Indeed. You could just hope that the user would always type the numbers in correctly. In future decision-making. You want to make certain that all the test scores are reasonable. That is.

even if the user makes a mistake. Now, you could type this code in every single time your program needed another score. But a much easier way to handle the problem would be to make a subroutine out of it. The subroutine might look like this: 3000 INPUT SCORE 3010 IF (SCORE >= 0) AND (SCORE <= 100) THEN GOTO 3050 3020 PRINT "You typed in ";SCORE 3030 PRINT "That number is wrong. Please try again." 3040 GOTO 3000 3050 RETURN The only difference between this subroutine and the earlier bit of code is that the numbering is different and the subroutine ends with a RETURN statement. To use this subroutine, your program need only say "GOSUB 3000". The GOSUB statement is like a GOTO with a memory. It means, "Computer, GOTO this line number, but remember the line you're on right now." The RETURN statement reverses the process; it says, "Computer, remember the line number you came from? Well, GOTO that line number." The advantage of this system is that you can call this subroutine from any part of the program. Consider this example: 120 GOSUB 3000 130 TEST=TEST+SCORE 140 GOSUB 3000 150 GRADE=GRADE+SCORE When the computer reaches line 120, it goes off to subroutine 3000. That subroutine will RETURN to line 120. Later on, line 140 will go to subroutine 3000, and the subroutine will then RETURN to line 140. You can call subroutine 3000 from any part of the program without the computer losing track of where you are. A GOSUB call is rather like telling the computer, "Computer, go off and do this chunk of work, then come back when you're done." SUBROUTINES AS BUREAUCRACIES Subroutines very precisely express the three primary elements earlier associated with bureaucracies: bureaus, assignment of functions, and communications between bureaus. The subroutine itself is a bureau. It may not have any bureaucrats to handle its functions, but it doesn't need any; its

commands take care of its operations. Indeed, the subroutine is a very precise bureau: one knows exactly what it does. None of this ambiguous "Bureau of Assorted Functions Support (BAFS)" nonsense that we so often see with modern bureaucracies. The subroutine executes a precise function specified in its code. And the competent programmer has no qualms about rearranging or eliminating a subroutine that is no longer needed. The second element of a bureaucracy is the assignment of functions to bureaus, and again we see the concept expressed very clearly with the subroutine. You use a subroutine to execute a particular function. If you need input conditioning, just use the sample subroutine presented earlier. That's the one and only place you need go for input conditioning. If your needs for input conditioning change, then change the input conditioning subroutine. Certainly makes life easy, doesn't it? One of the more abstruse concepts associated with subroutines is the generality with which functions are assigned to subroutines. The subroutine example given above is only capable of handling inputs that should fall between 0 and 100. But what if another portion of your program needs inputs between 100 and 200? You would like to have input conditioning for this part of the program, too, but do you need to write another subroutine? Not if you rewrite the first subroutine to be more general. One way to do this is as follows: 3000 INPUT SCORE 3010 IF (SCORE >= LOWER) AND (SCORE <= HIGHER) THEN GOTO 3050 3020 PRINT "You typed in ";SCORE 3030 PRINT "That number is wrong. Please try again." 3040 GOTO 3000 3050 RETURN The difference between this subroutine and the earlier one is in line 3010; the constants 0 and 100 have been replaced with variables LOWER and HIGHER. You would now call this subroutine with the following sequence: 116 LOWER=0 118 HIGHER=100 120 GOSUB 3000 . .

. 226 LOWER=100 228 HIGHER=200 230 GOSUB 3000 Now the subroutine is able to handle a wider range of functions. However, there is a price we pay for this greater generality: we must now specify the values of LOWER and HIGHER before we use the subroutine. The third element of a bureaucracy is the set of communications procedures between bureaus. This concept is particularly well-developed in computer programming. In fact, it has its own special term: parameter passing. In a bureacracy, you send all manner of messages: letters, memos, work orders, and so forth. But in a computer, you only send numbers. The numbers that you send to a subroutine to tell it what to do are called parameters; the act of sending them is called parameter passing. The reason we call it parameter passing instead of parameter sending is that parameters can be both sent and received. In our example subroutine, the parameter SCORE is passed back from the subroutine to the calling statement in the main program. Actually, BASIC uses a very poor method for passing parameters. The numbers that are passed back and forth between subroutines are always global variables. A global variable is a variable that is used throughout the program. The opposite of a global variable is a local variable, a variable that is used in only one subroutine. Imagine a bureaucracy that had no paper, only a gigantic blackboard and a bunch of telescopes, one telescope for each bureaucrat. Suppose then that bureaus communicated with each other not by sending memos back and forth, but rather by writing messages onto the blackboard. Everybody would then read the same blackboard, looking for the messages that concerned them. BASIC works the same way. All the variables in the program go onto one big blackboard. When our example subroutine had the properly conditioned score to pass back to the calling statement, it wrote the value onto the blackboard in the slot for the global variable SCORE. The calling statement then read the blackboard to find the value of SCORE. The system is very simple, but it can be clumsy when you want to pass lots of parameters. Suppose, for example, that you had a subroutine at line 5000 that needed three variables (V1,V2, and V3) as input parameters and produced another three variables (W1, W2, and W3) as output parameters. Then to call that subroutine you would have to write

so the subroutine gives you bad outputs. the odds are that your version of BASIC doesn't have this.SCORE. there is a much better way that some advanced BASICs and many other languages use: it's called a parameter list. Suppose also that you used it a little earlier in the program and that time. When the computer GOSUBs to the subroutine. for example. and you can't find anything wrong with it. you gave V1 a value of 33. isn't it? Unfortunately. Such a subroutine call with the above example might look something like this: 200 GOSUB 5000(27. and V3 as inputs. You get mad and try to figure out how that stupid subroutine fouled up. the subroutine looks at the blackboard through its telescope in the slot marked "V1" and it sees the same old value.this much code: 170 V1=27 180 V2=158 190 V3=-9 200 GOSUB 5000 210 SCORE=W1 220 GRADE=W2 230 FINAL=W3 All this work just to talk to the subroutine! What a waste of time! As it happens. V2. It goes ahead and does its job using that number. A little while later. but you forget to give V1 a new value appropriate to the situation. Suppose.FINAL) That's much simpler. The problem is not with the subroutine itself but with the parameters you passed to it. 33. .-9. you simply list all of the parameters in parentheses right after the subroutine call. you decide to call the subroutine. that's an old number. It is interesting to note that one of the most common bugs in any program is the failure to pass parameters properly. We goof and send the wrong parameters to the office across the street. so you will have to use the old blackboard method.158. just a little clumsy with some subroutines.GRADE. Don't despair. Of course. that you had a subroutine that needed those three global variables V1. and it's all wrong. The same thing happens with bureaucracies. it is perfectly serviceable. When you use a language with parameter lists. they do their duty and get it wrong.

When you consider that programs take up scarce RAM space. In-line code is merely the same code as the subroutine. croak a thin little "Oops". When you want to buy a large expensive computer. Any reasonable person would know that you don't go around buying multimillion dollar computers by the gross. The subroutine is always slower than the in-line code.Then we yell and scream over the phone at these idiots who screwed everything up. The two are functionally identical. and you reach the place on the form that asks "Quantity". In-line code is like having your own little bureaus within your organization. for company cars and paper clips. Eventually we find out what really happened. These time penalties. At least the computer doesn't have a sense of righteous anger. so we use it and pay the time penalty. you realize that subroutines can save you enough RAM to make the time penalty worthwhile. When you use a subroutine. There are two reasons for this. . put in place of the subroutine call. and crawl into a hole. And there is the same time penalty associated with generality. Bureaucracies are the same way. you write it each time you use it. The time penalty of subroutines is counterbalanced by their resourceefficiency. there is a time penalty paid just for talking with the subroutine. First. it will surely waste a little time handling computations not appropriate to that one situation. you write the code just once. If. are unavoidable and have nothing to do with the nature of the subroutine. although small. you are wasting time filling out "One". rather like having your own little Personnel department or Purchasing Office inside your department. subroutines tend to be generalized where in-line code is customized. PERFORMANCE ADVANTAGES AND DISADVANTAGES The alternative to a subroutine is called in-line code. when you use in-line code. It takes more time for the computer to look up the line from which it came when it reaches the RETURN statement. but differ somewhat in terms of performance attributes. for example. Moreover. It takes time for the computer to make a note of where it is when it encounters a GOSUB statement. then when it comes time to handle any one of those five. You always pay a time penalty just sending the forms through the inter-office mail. a particular subroutine is meant to handle five different kinds of input conditioning. Just getting somebody else to pay attention to your problem takes a little time. But this form is meant to work for big computers and little calculators.

Personnel would pay the time penalty but achieve no resource efficiency. in a well-organized bureaucracy. Too bad. Better to integrate that operation into Personnel. In this case.Again. no words to process. for everyone needs to hire a new employee occasionally. Thus. when you encounter a problem-ridden bureaucracy. but we enjoy no savings in RAM whatsoever. you can always see exactly where to go to get any job done. though. you should ask yourself. The ideal subroutine situation is analogous to a Personnel department within an organization. Subroutines help you organize your program into clean. It is called by nearly every bureau in the organization. This situation is analogous to having a hypothetical "Department of Personnel Telephone Answering". Similarly. matters are not so simple. "What kind of bureaucracy am I creating here? Is this a clean. arises from their modularity. you would find no spreadsheets. In a wellwritten program. The ideal use of a subroutine comes when it is called occasionally from many different statements in the program. understandable modules. As you organize your program. and would be called on many times a day. They make it easy to see the organization of the program. You can't simply press RESET and start all over. we pay the time penalty each time we use the subroutine. no programs. The worst possible use of a subroutine arises when it is called many times (by means of a loop) from a single statement only. Chapter Seven From Data to Information NUMBERS AND MEANING If you could look into the heart of a computer. you can find exactly the right bureau to solve your problem. because few departments hire en masse. The real advantage of subroutines. or is it a messy. snafu-prone one?" Unfortunately. Having your own Purchasing may be faster than going through Corporate Purchasing. but can your company afford the extra expense of your own Purchasing staff? It's a trade-off between speed and efficiency. bureaucracies are the same way. That's why so many organizations quickly sprout Personnel departments. understandable bureaucracy. but it is called few times by each bureau. no aliens to blast. Such a department would provide a service to only a single bureau. All you would find are .

numbers, thousands and thousands of numbers. The fundamental measurement of a computer's power is its storage capacity for numbers &emdash; typically 512 thousand numbers on a personal computer. With these numbers, the computer is capable of only a very small number of manipulations. It can move them, add, subtract, compare, and perform simple logical operations known as Boolean operations. Where in this mass of numbers and simple manipulations is meaning? How can the computer transform all these numbers into words to process, alien invaders, or programs? Consider atoms. Simple things, atoms. They can interact with each other according to the laws of chemistry. There are lots of combinations there, but little in the way of meaningful interaction. Yet, put enough atoms together and you get a human being, a person with character, feelings, and ideas. If you look deep inside a human being, all you will find are lots and lots of chemical reactions. Meaning does not come from its smallest components, but from the way that they are organized and the context in which they are used. Data is what the computer stores, but information is what we seek to manipulate when we use the computer. The key word in understanding the difference between data and information is context. Data plus context gives information. This is a fundamental aspect of all communication systems, but it is most clearly present in the computer. The computer stores only numbers, but those numbers can represent many things, depending on the context. NUMERIC DATA They can, of course, represent numbers with values, things like a bank balance, or a score on a test, or somebody's weight. Even then, these numbers are not without a context of their own. First, they have dimensions, the units with which they are measured. We don't say only that my weight is 110 &emdash; it is 110 pounds. The number 110 all by itself doesn't mean anything; you have to include the unit of measure to give it a context to make it meaningful. Similarly, my bank balance of 27 makes no sense until I specify whether it is 27 dollars, 27 cents, 27 pesos, or whatever it is. There is another context to consider when using the computer. It recognizes only one kind of number: the 16-bit integer. This is a number ranging from 0 to 32,767, with no fractions or decimal points. In other words, the computer can count like so: 0, 1, 2, 3, 4, . . . 32,765, 32,766, 32,767. It cannot recognize a number bigger than 32,767. When it reaches 32,767, the next number is just 0;

it starts all over again. Now, you might wonder what use there is in a computer that can only recognize the first 32,768 numbers in the whole universe. Well, there's a trick that programmers learned long ago. You can combine little numbers to make big numbers. Actually, we do it all the time. If you think about it, you only know ten numbers yourself. Those ten numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. You think you know more? Look closely at the next number, 10. It's nothing but a 1 followed by a 0. There's nothing new or different about the number 10; it's just two old numbers stuck together! Of course, you know perfectly well that what makes 10 different from 1 or 0 is manner in which you interpret it. The number 10 has a context of its own. We think in terms of "the tens place" and "the ones place", and so we interpret 10 as "1 in the tens place plus 0 in the ones place." Using this system, we can build any number we want. The only price we pay is that we have to write lots of digits to express big numbers. The programmer's trick is to do the same thing with the computer. If you stick together 8-bit bytes, you can get bigger numbers. With the computer, you pay two prices to get bigger numbers: first, it takes one 16-bit word for each part of the number that you add, and second, it takes more computer time to manipulate such bigger numbers. There is also the restriction of context: you have to remember that the numbers in such a compound number belong together and must be taken as a group, rather than individually. It is even possible to group these 16-bit numbers together in such a way as to interpret the group as what is called a floating-point number. This has nothing to do with water or boats; it is a number whose decimal point is free to move around ("float" &emdash; get it?) within the number. The idea sounds weird until you see some examples: Floating point numbers Integers 12.36835418 127 17,893.35 94,366 .00231 90 -451.0 -451 As you may have guessed, all floating point numbers have a decimal point. The big question about any floating point number you have is, how many significant figures does it have? Let me show you an example, using the value

of π. 3.14159265358979323 3.1415926536 3.1416 3.14 3 The first value gives π to 18 significant figures. The second value gives π to 11 significant figures. The third gives it to only 5; the fourth gives 3; and the fifth gives only one. Each number is correct to within its number of significant figures; it is rounded off from the previous one. A lot of people make the mistake of assuming inappropriate zeros. For example, that last value of π, 3, is it a 3 or a 3.0 or a 3.000 or a 3.0000000000? Many people think that 3 is the same thing as 3.000000000, but it isn't. The next digit of π after the 3 should be a 1, but we rounded it off when we went down to only one significant figure. So, if you were trying to reconstruct the value of π after I gave you only a 3, you would be wrong to put a 0 after the 3 to make it a 3.0. In other words, 3 is not the same as 3.0. If you want to say 3.0, say it; if I say 3, don't read it as 3.0, because it isn't. It could be 3.1, or 2.9, or anything between 2.5000000 and 3.4999999. The meaning of significant figures is that they show us the limitations of computers and arithmetic. Remember, each significant figure costs you some RAM space and some execution time. For this reason, some computers use only 4 bytes to save a floating-point number; others may use 8 or even more bytes. A floating-point number expressed with 4 bytes has about 7 significant figures; thus, you could express ¹ this accurately with such a computer: π = 3.141593 This is fairly accurate for most purposes. But now we come to a nasty trick that trips up lots and lots of people. Suppose I divide 1 by 3. That should yield the fraction 1/3rd, whose decimal value is .333333 . ., with the 3's repeating forever. Now, when I do this division on my computer equipped with 4-byte floating point arithmetic, it will report the result as .3333333, with 7 significant figures of 3's, but not an infinite number. The difference between the computer's answer (.3333333) and the correct answer (.3333333. . . .) is small (about one part in a million), but the fact remains that the computer is wrong. Now, this discovery tends to upset some people. They think that computers

we're talking hundreds of billions of dollars here.237.300. but if you don't enough room to say it. For example. that you had a brilliant plan to solve. it can completely wipe out your number. The problem is that there is no mathematical way to correctly express the value of 1/3rd with a finite number of significant figures. Let's say the program statement looks like this: 8230 TOTAL=TOTAL+WHFFOLDERS Now. The problem is not that the computer is mistaken. I then gave you one piece of paper and a crayon and told you. Now suppose you have a "bottom line" routine that adds up all the expenditures of the budget to see what the grand total is. or that it is stupid and cannot perform arithmetic. yet here is incontrovertable proof that the computer is wrong. This really rattles their cage. This problem is so common that it has a name: round-off error. it can round off some of the accuracy of the number. You had figured out a detailed plan that included all the critical factors for eliminating the budget deficit without wiping out the economy. say.are always right. Let's say that you had even figured the amount of money to go for buying file folders at the White House.57 . "You think you're so smart. In some cases. Remember." You may have the answer. Suppose. that they can make no mistakes.00 23. Let's say that you figured $23. Let's say that the grand total is about $300 billion dollars by the time the program gets around to adding in your figure for file folders.57 a year would be a good figure. We call it that because the computer rounds off numbers to make them fit into its floatingpoint format. for example. the problem of the American budget deficit. put your plan on that paper with that crayon. The same thing goes with the computer: with anything less than an infinite number of significant digits. you had developed a computer program to figure out how much money to allocate each part of the Federal budget. There isn't enough room to be accurate in so small a space. especially with arithmetic. you come out looking pretty stupid. suppose as part of your plan to solve the deficit. the computer will sometimes be wrong by a tiny amount. the computer will add the numbers like this: 312. and in the process.

only understands numbers. or "%". Accuracy truly does have its price. almost all versions of BASIC will do this automatically for you with a facility called "string data". Using strings from BASIC is very simple.00 If you count digits.300. and you would think that it had a very mysterious bug. which will take more space and run more slowly. To read it out. To use it. but a 65. a string is always indicated by a "$" symbol at the end of the variable name. You can always treat a string as a collection of characters. right out of existence! It's as if the $23. Every letter and symbol gets its own number.57 never existed. They can also be used to mean alphanumeric characters. C gets 67. you need lots of significant digits.237.312. ALPHANUMERIC DATA Numbers can mean more than just values. These are just letters and symbols like "a". Lo and behold. This code is similar. if you want the computer to use great big numbers next to little bitty numbers. just convert back. Here's a simple example: 50 NAME$="CHRIS" 60 PRINT NAME$ There are only two syntax rules to note about this construction. and so forth. That tips off . With this one code you can store text messages inside the computer. The system for using them is very simple. but its purpose is not to hide messages but to make them understandable to the computer. and so forth. while B gets 66. the 2 in 23. Perhaps you used a code like that when you were a kid. you convert a character to a number using the ASCII code and store the number in the computer. First.57 is in the eighth significant digit place. Another difference is that the letter A does not get a 1. you will see that the computer's seven significant digits are used up on the high part of the number. A 1 stood for the letter A. Your program would produce unreliable results. even though it's really a collection of numbers. and so it is rounded off &emdash. it uses a code called ASCII (pronounced "ass-key"). which. The moral of this story is. a 5 stood for the letter E. A string is a collection of numbers that are always treated in the context of ASCII code conversion. this is one of the natural limitations of the computer. an acronym meaning "American Standard Code for Information Interchange. after all. The reason why A starts at 65 is a bit of technical trivia with which I won't waste your time." This code assigns a number to every character. "(". In truth.

a program might ask you if you want some data sent out to the printer. that it really is a number. it would GOTO 2000. Remember. The program can then keep track of your answer as a variable called. named after George Boole. a choice that is either taken or not taken. you can take strings apart. INSTRUCTION DATA . These two functions allow you to see the code conversion process. insert and delete sections of a string. If the result were true. Quite often. You can answer yes (true) or no (false). computer programs allow the user to set a particular choice. though. Two fairly common facilities. Thus. the Boolean variable is a good way to keep track of such true/false conditions. which is C. The second value will print the character corresponding to 67. For example. allowing you to join strings. extract a portion of a string. are the ASC function and the CHR$ function. Boolean data is very simple: it takes one of only two values. just interpreted differently. true or false. Second. it might have a statement like this: 1120 IF CHOOSEPRINTER THEN GOTO 2000 This statement would treat the value CHOOSEPRINTER the same way it would treat a logical expression. Thus. the string data should be placed inside a pair of double quotation marks. say. although that is certainly the hard way to do it. and manipulate them with arithmetic. Most BASIC languages store a zero to represent a value of false. though. and much more. whenever it is about to send something out. otherwise it would continue on. Then. Try this little example out on your computer: 80 PRINT ASC("C") 90 PRINT CHR$(67) The first line will print the ASCII value of C. I cannot tell you much more about string handling because different computers handle strings differently. Some allow you extensive facilities for manipulating strings. find their numeric equivalents. and something else to indicate a value of true.the computer that you want this data treated as a string. which should be 67. who founded the mathematics of formal logic. CHOOSEPRINTER. BOOLEAN DATA Another kind of data is Boolean data.

associated with it. after it reads a BASIC instruction. A BASIC interpreter translates your BASIC commands into the computer's machine language. 66. There is more information on machine language in the appendix. The interpreter allows the computer to figure out what it is supposed to do. 67. 65. This language. Native code is program instructions that are couched in the natural language of the computer. it must look up the meaning of the instruction in a "book of commands" called an interpreter. called a token. What. the computer would scan through RAM. the token for the command PRINT might be 27. . then the command PRINT "ABCD" would be stored in RAM as 27. machine language is nothing more than numbers. are nothing at all like BASIC. The 27 stands for PRINT and the 65. Native code is much faster than interpreted code. That is. They can be treated as instructions to the computer. These are instructions that the computer itself recognizes as instructions to directly execute. Even then. there are two variations on this. 66. What is worse. For example. you might wonder. even if it has executed that instruction thousands of times previously. BASIC Instructions Your BASIC program is stored in RAM as a set of instructions for the computer. however. The difference between BASIC instructions and native code is that the BASIC instructions are foreign to the computer. does machine language look or sound like? Perhaps you imagine some weird language of beeps and buzzes. a BASIC program is slowed down quite a bit by having to go through this interpreter. Other commands. looking at each instruction code and translating it into action. and 68 are the ASCII codes for "ABCD". If this were the case. 67. It is the fundamental language that the computer uses for all its work. Each instruction has a code number. the computer must interpret each instruction each and every time it encounters the instruction. As you might imagine. To RUN a BASIC program. called machine language. For example. a 96 will tell some computers to return from a subroutine. 68.The numbers in a computer can be interpreted in a completely different manner. it is exactly the same as the RETURN statement in BASIC. the computer does not really know what the BASIC instructions mean for it to do. Native Code The second form of computer instructions are what is called native code. But no. is built deep into the innards of the computer and cannot be changed.

B. and "deci" means 10. Now. we count by 16's in a hexadecimal system. 6. 3. You already know about decimal. cast aside your natural familiarity with that 10 and look at it closely. C. and F is 15. So we count like this: 0. C. Where else would 8+8=$10? Or try to figure this one out: $30/2=$18. 7. or a 100's place. E. In decimal. you must first learn something about number systems. 1. or just plain old everyday 10. so hexadecimal refers to a base-16 numbering system. hexadecimal. 9. we started over again with 0. That place is a 1's place.PIXEL DATA Data inside the computer can also be interpreted as pixel data. 2. This is data to be displayed on the screen. F. E. replace it with a 0 and add 1 to the next place. carry the one. be careful about that last 10. The next 6 numbers after 9 are A. 7. Doing anything in hexadecimal is enough to drive almost anybody nuts. or 16. which throws that 9 over the top to 0. 1. What happened was this: we reached 9. the last numeral in our possession. 8. 2. In the hexadecimal system we count by 16's. it is the number system that you normally use. A. which takes us over the top. so we go back to 0. 6. so we carry the 1 again. "hex" in this case means 6. we add 1 to 9. so 10 is 16. It sounds like a number system that witches might use to cast hexes. Now. and end up with a 1 in the hundreds place. 10. The rule is simple: when you reach the highest number in the system and go up. or so on in the decimal system. The idea to master here is the idea of counting up until we reach the top of the number system and start over. 4. 10. but 10 is decimal 10. When we reach 99. 4. Does that confuse you? As you might imagine. Decimal is the first. 8. and F. most . To help out. and binary. There are three commonly used number systems to master: decimal. $10 is hexadecimal 10. Whenever a programmer writes down a hexadecimal number. 3. 5. This stuff gets real hairy real fast. reading hexadecimal numbers can be quite confusing. Thus. 9. D. he puts a dollar sign in front of it so that you'll know that it is special. or a 10's place. Hexadecimal is the second system. B. It's really the number after F. That is. Arithmetic is really wild. 5. but we put a 1 in the 10's place. so programmers have one little trick to help out. but actually. D. To go to the next higher number. It is not the same as the 10 you are used to seeing. we do it like this: 0. To understand how this is done.

In binary. But there is one situation in which it is handy to worry about individual bits. A blow-up of the letter "A" makes the point better than words: Those big black squares are the pixels that we use to draw the A on the screen. About all you can do is pack eight of them together into a byte. There are only two states possible for a pixel. Thus. there are eight bits in one byte. 4. $10 is 16. For example. 10 is 2. 8 This means that in decimal. a pixel's state can be represented by a binary number. The one saving grace of binary numbers is that they directly show the status of the bits inside the computer. So in binary. no in between. 100. 110. what can you do with something that is either 0 or 1? Not much. 6. A bit is the fundamental unit of memory inside the computer. 5. and in binary. 6. 111. 4. 7. We normally don't worry about individual bits because one bit is too small to do much with. 5. 2. Are you getting confused yet? Binary numbers get very long very quickly. Now. 101. 3. the number 999 in binary is 1111100111. because the computer is organized around bytes. notice that a pixel is either black or white. The word pixel is a contraction of "picture element". 8. But bytes are made up of bits. and hexadecimal has 16 numerals. The third numbering system that programmers use is called binary. 1. in hexadecimal. so simple that it confuses lots of people. 7. 1. On a black and white display. a pixel is either black or white. we count like this: Binary: 0. They are also very tedious to do arithmetic with. I mean. 1. binary has only two: 0 and 1. 10. we only count up to 1 before starting over. and 9). and then you've got a number between 0 and 255. a 1 or a 0. It is a very simple numbering system. 10 is 10. while decimal has 10 numerals (0. 1000 Decimal: 0. 3. and that is when you are making a screen graphic.programmers use a little hexadecimal calculator that lets them figure these things out quickly and easily. 2. We might say that a 0 means white and a 1 means . 11. All computers draw images on the screen by breaking the screen up into little tiny cells called pixels. We normally talk in terms of bytes. Thus.

grimacing alien. then our letter A can be represented by binary numbers. Consider the word "dig". SUMMARY OF NUMBER TYPES We have seen that a number can mean many different things. we can process the images themselves. This is nothing new.black. How could you tell which of the fourteen interpretations applied? Only from the context. My Webster's Unabridged lists fourteen different definitions for the word. There are many other things that a number might mean. Or it might be a part of an image. as a fluent speaker of the language. So too it is with computers. Behind every twisting. The key word to examine is "established". It can be your plain old. It could also be an instruction for the computer to execute. like so: What we have here is something very exciting and very important: the ability to express images as numbers. you have no problem determining the exact shade of meaning of the word from the context in which it is used. How is it that one number could mean so many different things? Because we can apply so many different contexts to that one number. like Joe's bank balance or Fred's weight. there's a microprocessor frantically shuttling numbers around. it all depends on the context in which the number is taken. we do it all the time with words. It can also be a character. but the context is always clear. one for each row in the letter. That's how computer games are able to create those animated images. just by processing the numbers that represent the images. everyday word like "dig" could be interpreted fourteen different ways. the question bears the seeds of the answer. Now if we apply the powerful numbercrunching capabilities that the computer gives us. Exactly how is context established? As in so many things. like an "A" or a "%". everyday number. If you were a foreigner first learning English. DATA VERSUS PROCESS Let us look more closely at this concept of context. Context is not some static entity . They may use a number in many different ways. It could also be a simple "true or false" indicator. A simple. If so. Yet. you might be angry at such a stupid language that cannot keep its words straight. Thus is it possible to breathe meaning into something as meaningless as a number.

No. number and context. is composed of both data and process. 12 Or I could send the same information in a process-intensive form: 10 FOR X=1 TO 6 20 SCORE=2*X 30 NEXT X Both messages convey the same information. If you regard the computer as a communications medium. If a program runs too slowly. created. context must be established. one of our most heavily used media. and often use it in polishing their programs. 6. I could send you the information in a data-intensive form: 2. Both are necessary to create an idea or message. A contrivedly simple example may help make this point. This is because data consumes space while process consumes time. Just because data and process are to a large degree interchangeable does not mean that we should use them without bias. A sufficiently clever programmer can obtain almost any desired trade-off of space for time by finding the precise trade-off of data for process. translate process-intensive sections into more dataintensive forms. 8. though. 6.that lies on the page the way that data does. An idea or a message. but one uses primarily data and the other uses primarily process to convey the same information. the ratio of data to process is not fixed. then when using a computer. Context is intrinsically part of a process. If a program is too large and must be made smaller. Here is a medium ideally suited for . Here we encounter one of the most profound concepts of computing: the complementarity of data versus process in the computer. the printed page. 4. 4. Suppose that I wish to convey to you scores of six students. Data are the numbers inside the computer. translate data-intensive portions into more process-intensive forms. it is established or created by some activity. you must always bear in mind the possibility of using another medium to convey your message. Consider. process is active. and 12. Any message can be expressed with any combination of data and process. process is what the computer does with them. for example. 10. Programmers are intensely aware of this process-data duality. 10. But there is a point many programmers miss. Data are passive. 8. Oddly enough. and suppose that these scores just happen to be 2. or forged.

though. it is strongest at presenting data and weakest at communicating processes. How many textbooks have you dragged through. but the same computer can perform approximately 300. It follows. all other media are expository. If you let it run for just four hours. so are word processing programs. Nevertheless. with little success? Look how much work I have had to go through to explain to you the small ideas presented in this book. it can perform over 4 billion operations. even though holding same measly 512. Now we are getting a little more demanding of the medium.000 bytes of data.conveying data and quite incapable of directly presenting process. trying to divine the author's explanation of some simple process.000 bytes. but somehow the description of a complicated sequence of events can get a little muddled and require perhaps a few re-readings before we can understand it. the computer might well be said to be more process-intensive than data-intensive. but not very well. Because the printed page is a data-intensive medium. if you list the most successful programs for computers. is the only medium we have that can readily handle processes. information that was once stored with paper and pencil. We find that the medium is certainly capable of doing so. If you want to find the atomic weight of beryllium. Both allow you to store lots of information.000 operations per second. The computer. more convenient. but about events. Indeed. Spreadsheets are a good example. that the ideal application for the computer will stress its data-processing capabilities and minimize its data-storage capabilities. and it does not perform quite as satisfactorily. therefore. you will see that key element in all has very little to do with data storage and very much to do with data processing. there is no medium cheaper. Indeed. It is especially adept at presenting static data. But the real appeal of these programs is not . On a per-idea basis. we are able to use the printed page to convey a great deal of information about the world. This is not a medium for storing data. But suppose we wish to convey information not about facts. the population of Sierra Leone. or some other simple fact. and more effective. it is a machine for processing it. The typical personal computer can store 512. It manages. certainly. a reference book is an ideal source to consult. Now let's go to the extreme of the spectrum and consider the ability of the printed page to convey information about processes. That is because it is the only medium that is intrinsically interactive.

but information is what we seek to manipulate when we use the computer. The jerk who tries to intimidate you with lots of numbers is wasting your time unless he can orchestrate those numbers into a coherant line of reasoning. The moral of this chapter is that data is not information. If you look deep inside a human being. The key word in understanding the difference between data and information is context. atoms. With these numbers. Concentrate your attention on the context behind the numbers. Numbers are only the junior partner in the partnership of information. no programs. Data plus context gives . subtract. It can move them. and ideas. put enough atoms together and you get a human being. Numbers without context are useless. Where in this mass of numbers and simple manipulations is meaning? How can the computer transform all these numbers into words to process. or programs? Consider atoms.the way they allow you to store data but the way that they make it easy to manipulate data. compare. The senior partner is context. Chapter Seven From Data to Information NUMBERS AND MEANING If you could look into the heart of a computer. the reasoning that gives them meaning. Yet. The fundamental measurement of a computer's power is its storage capacity for numbers &emdash. feelings. which is derived from the processing to which the numbers are subjected. Be the master of your own numbers. no aliens to blast. but from the way that they are organized and the context in which they are used. you would find no spreadsheets. Data is what the computer stores. no words to process. is really not a way to store data but a way to select data. All you would find are numbers. Even the most data-intensive application on computers. meaningless piles of digits. and perform simple logical operations known as Boolean operations. Simple things. a person with character. They can interact with each other according to the laws of chemistry. but little in the way of meaningful interaction. all you will find are lots and lots of chemical reactions. There are lots of combinations there. add. alien invaders. the database manager. Meaning does not come from its smallest components. thousands and thousands of numbers. typically 512 thousand numbers on a personal computer. the computer is capable of only a very small number of manipulations.

5.768 numbers in the whole universe. we do it all the time. or whatever it is. It's nothing but a 1 followed by a 0. 32. We think in terms of "the tens place" and "the ones place". you can get bigger numbers.767. 32. my bank balance of 27 makes no sense until I specify whether it is 27 dollars. 4. 8.information. you have to include the unit of measure to give it a context to make it meaningful. 27 pesos. NUMERIC DATA They can. The number 110 all by itself doesn't mean anything. If you stick together 8-bit bytes. There is also the restriction of context: you . Well. and 9. 27 cents. it takes more computer time to manipulate such bigger numbers. 6.767. with no fractions or decimal points. 4. it takes one 16-bit word for each part of the number that you add. the computer can count like so: 0. you pay two prices to get bigger numbers: first. there's a trick that programmers learned long ago. 1. The computer stores only numbers. If you think about it. The only price we pay is that we have to write lots of digits to express big numbers. Similarly. the next number is just 0. You can combine little numbers to make big numbers. but it is most clearly present in the computer." Using this system.766. of course. 3. you might wonder what use there is in a computer that can only recognize the first 32. 3. and second. First. it's just two old numbers stuck together! Of course. we can build any number we want. 2. . 2. it starts all over again.765. 32. represent numbers with values. In other words. When it reaches 32. It cannot recognize a number bigger than 32. There is another context to consider when using the computer. 7. This is a number ranging from 0 to 32. This is a fundamental aspect of all communication systems. Those ten numbers are 0.767. Now. It recognizes only one kind of number: the 16-bit integer. 10. 1. these numbers are not without a context of their own. Even then. We don't say only that my weight is 110 &emdash. . it is 110 pounds. There's nothing new or different about the number 10. but those numbers can represent many things. You think you know more? Look closely at the next number. The programmer's trick is to do the same thing with the computer. . or a score on a test. With the computer. you only know ten numbers yourself. or somebody's weight. depending on the context. things like a bank balance. The number 10 has a context of its own. the units with which they are measured. Actually. you know perfectly well that what makes 10 different from 1 or 0 is manner in which you interpret it.767. and so we interpret 10 as "1 in the tens place plus 0 in the ones place. they have dimensions.

how many significant figures does it have? Let me show you an example.0000000000? Many people think that 3 is the same thing as 3. that last value of π. or 2.0 -451 As you may have guessed. and the fifth gives only one. you would be wrong to put a 0 after the 3 to make it a 3.14 3 The first value gives π to 18 significant figures. Each number is correct to within its number of significant figures.35 94.14159265358979323 3. rather than individually. 3.000 or a 3.00231 90 -451. say it. if you were trying to reconstruct the value of π after I gave you only a 3. but it isn't. It could be 3.893.36835418 127 17.5000000 and 3.0. It is even possible to group these 16-bit numbers together in such a way as to interpret the group as what is called a floating-point number. all floating point numbers have a decimal point. using the value of π. it is rounded off from the previous one. the fourth gives 3.0 or a 3.0. but we rounded it off when we went down to only one significant figure.9.0. So.0. don't read it as 3. get it?) within the number. In other words. or anything between 2. The second value gives π to 11 significant figures. because it isn't. The next digit of π after the 3 should be a 1. .1415926536 3. 3 is not the same as 3.000000000. A lot of people make the mistake of assuming inappropriate zeros. This has nothing to do with water or boats. 3. The third gives it to only 5. it is a number whose decimal point is free to move around ("float" &emdash.4999999. For example. The idea sounds weird until you see some examples: Floating point numbers Integers 12. if I say 3.1416 3. The big question about any floating point number you have is. If you want to say 3.have to remember that the numbers in such a compound number belong together and must be taken as a group.1. is it a 3 or a 3.366 .

3333333. For this reason. The problem is that there is no mathematical way to correctly express the value of 1/3rd with a finite number of significant figures. . The problem is not that the computer is mistaken.The meaning of significant figures is that they show us the limitations of computers and arithmetic. but not an infinite number. . There isn't enough room to be accurate in so small a space.) is small (about one part in a million). the computer will sometimes be wrong by a tiny amount. You had figured out a detailed plan that included all the critical factors for eliminating the budget deficit without wiping out the economy. the problem of the American budget deficit. That should yield the fraction 1/3rd. and in the process. Now. This problem is so common that it has a name: round-off error. but if you don't enough room to say it. The difference between the computer's answer (. They think that computers are always right. This really rattles their cage. this discovery tends to upset some people. . But now we come to a nasty trick that trips up lots and lots of people. with the 3's repeating forever. you come out looking pretty stupid. Suppose I divide 1 by 3. you could express ¹ this accurately with such a computer: π = 3. . it will report the result as . Suppose. for example.3333333.3333333) and the correct answer (.333333 . but the fact remains that the computer is wrong. Now." You may have the answer. Remember. put your plan on that paper with that crayon. A floating-point number expressed with 4 bytes has about 7 significant figures. whose decimal value is .141593 This is fairly accurate for most purposes. when I do this division on my computer equipped with 4-byte floating point arithmetic. that they can make no mistakes. that you had a brilliant plan to solve. thus. I then gave you one piece of paper and a crayon and told you. with 7 significant figures of 3's. each significant figure costs you some RAM space and some execution time. We call it that because the computer rounds off numbers to make them fit into its floatingpoint format. or that it is stupid and cannot perform arithmetic. The same thing goes with the computer: with anything less than an infinite number of significant digits.. yet here is incontrovertable proof that the computer is wrong. it can round off some of the accuracy of the . "You think you're so smart. especially with arithmetic. others may use 8 or even more bytes. say. some computers use only 4 bytes to save a floating-point number.

and you would think that it had a very mysterious bug.237.57 312. which. this is one of the natural limitations of the computer. the 2 in 23.57 never existed. In some cases. Perhaps you used a code like that when you were a kid.300. after all. For example. a 5 stood for the letter E. you need lots of significant digits.57 a year would be a good figure. Let's say that the grand total is about $300 billion dollars by the time the program gets around to adding in your figure for file folders. if you want the computer to use great big numbers next to little bitty numbers. you had developed a computer program to figure out how much money to allocate each part of the Federal budget.00 23. Now suppose you have a "bottom line" routine that adds up all the expenditures of the budget to see what the grand total is.237. and so forth. we're talking hundreds of billions of dollars here. it uses a code called ASCII (pronounced "ass-key"). In truth. Another difference is that the ." This code assigns a number to every character. The system for using them is very simple. Let's say that you had even figured the amount of money to go for buying file folders at the White House. the computer will add the numbers like this: 312. The moral of this story is. Let's say the program statement looks like this: 8230 TOTAL=TOTAL+WHFFOLDERS Now. This code is similar. "(". Remember. Your program would produce unreliable results. you will see that the computer's seven significant digits are used up on the high part of the number. Let's say that you figured $23. A 1 stood for the letter A. only understands numbers. right out of existence! It's as if the $23.number. Accuracy truly does have its price. These are just letters and symbols like "a".57 is in the eighth significant digit place.00 If you count digits. suppose as part of your plan to solve the deficit. They can also be used to mean alphanumeric characters. which will take more space and run more slowly. and so it is rounded off &emdash. ALPHANUMERIC DATA Numbers can mean more than just values. or "%". it can completely wipe out your number. an acronym meaning "American Standard Code for Information Interchange.300. but its purpose is not to hide messages but to make them understandable to the computer.

I cannot tell you much more about string handling because different computers handle strings differently. the string data should be placed inside a pair of double quotation marks. you can take strings apart. Boolean data is very simple: it takes one of . You can always treat a string as a collection of characters. who founded the mathematics of formal logic. Some allow you extensive facilities for manipulating strings. Every letter and symbol gets its own number. just convert back. and so forth. Lo and behold. Here's a simple example: 50 NAME$="CHRIS" 60 PRINT NAME$ There are only two syntax rules to note about this construction. while B gets 66. To use it. To read it out. Using strings from BASIC is very simple. though. but a 65. The second value will print the character corresponding to 67. C gets 67. BOOLEAN DATA Another kind of data is Boolean data. The reason why A starts at 65 is a bit of technical trivia with which I won't waste your time. Two fairly common facilities.letter A does not get a 1. find their numeric equivalents. extract a portion of a string. Second. allowing you to join strings. Thus. and much more. First. With this one code you can store text messages inside the computer. insert and delete sections of a string. which should be 67. almost all versions of BASIC will do this automatically for you with a facility called "string data". named after George Boole. are the ASC function and the CHR$ function. which is C. That tips off the computer that you want this data treated as a string. a string is always indicated by a "$" symbol at the end of the variable name. Try this little example out on your computer: 80 PRINT ASC("C") 90 PRINT CHR$(67) The first line will print the ASCII value of C. even though it's really a collection of numbers. although that is certainly the hard way to do it. These two functions allow you to see the code conversion process. you convert a character to a number using the ASCII code and store the number in the computer. and manipulate them with arithmetic. A string is a collection of numbers that are always treated in the context of ASCII code conversion.

For example. Quite often. computer programs allow the user to set a particular choice. otherwise it would continue on. To RUN a BASIC program. These are instructions that the computer itself recognizes as instructions to directly execute. say. associated with it. 67. 67. 65. You can answer yes (true) or no (false). that it really is a number. Most BASIC languages store a zero to represent a value of false. That is. The 27 stands for PRINT and the 65. then the command PRINT "ABCD" would be stored in RAM as 27. the computer does not really know what the BASIC instructions mean for it to do. and 68 are the ASCII codes for "ABCD". The program can then keep track of your answer as a variable called. Native Code The second form of computer instructions are what is called native code. 66. the token for the command PRINT might be 27. If the result were true. and something else to indicate a value of true. after it reads a BASIC instruction. it would GOTO 2000. BASIC Instructions Your BASIC program is stored in RAM as a set of instructions for the computer. Remember. called a token. a BASIC program is . If this were the case. though. They can be treated as instructions to the computer. it must look up the meaning of the instruction in a "book of commands" called an interpreter. 66. looking at each instruction code and translating it into action. the computer would scan through RAM. Then. Each instruction has a code number. INSTRUCTION DATA The numbers in a computer can be interpreted in a completely different manner. a choice that is either taken or not taken. The interpreter allows the computer to figure out what it is supposed to do. CHOOSEPRINTER. The difference between BASIC instructions and native code is that the BASIC instructions are foreign to the computer.only two values. 68. whenever it is about to send something out. just interpreted differently. Thus. there are two variations on this. a program might ask you if you want some data sent out to the printer. the Boolean variable is a good way to keep track of such true/false conditions. As you might imagine. true or false. it might have a statement like this: 1120 IF CHOOSEPRINTER THEN GOTO 2000 This statement would treat the value CHOOSEPRINTER the same way it would treat a logical expression. For example. Even then.

3. does machine language look or sound like? Perhaps you imagine some weird language of beeps and buzzes. What. "hex" in this case means 6. you might wonder. Decimal is the first. There are three commonly used number systems to master: decimal. we add 1 to 9. To understand how this is done. The rule is simple: when you reach the highest number in the system and go up. carry the one. the last numeral in our possession. machine language is nothing more than numbers.slowed down quite a bit by having to go through this interpreter. and binary. What is worse. Native code is much faster than interpreted code. it is exactly the same as the RETURN statement in BASIC. 1. even if it has executed that instruction thousands of times previously. hexadecimal. but we put a 1 in the 10's place. a 96 will tell some computers to return from a subroutine. you must first learn something about number systems. When we reach 99. It sounds like a number system that witches might use to cast hexes. 5. 7. 2. so hexadecimal refers to a base-16 numbering system. but actually. and "deci" means 10. This language. called machine language. That is. and end up with a 1 in the hundreds place. There is more information on machine language in the appendix. is built deep into the innards of the computer and cannot be changed. we started over again with 0. we count by 16's in a hexadecimal system. A BASIC interpreter translates your BASIC commands into the computer's machine language. 4. 9. For example. Now. it is the number system that you normally use. Other commands. In decimal. so we go back to 0. 6. the computer must interpret each instruction each and every time it encounters the instruction. What happened was this: we reached 9. replace it with a 0 and add 1 to . cast aside your natural familiarity with that 10 and look at it closely. we do it like this: 0. But no. which takes us over the top. The idea to master here is the idea of counting up until we reach the top of the number system and start over. 10. Hexadecimal is the second system. PIXEL DATA Data inside the computer can also be interpreted as pixel data. so we carry the 1 again. Native code is program instructions that are couched in the natural language of the computer. You already know about decimal. which throws that 9 over the top to 0. however. 8. It is the fundamental language that the computer uses for all its work. are nothing at all like BASIC. To go to the next higher number. This is data to be displayed on the screen.

The next 6 numbers after 9 are A. Are you getting confused yet? Binary numbers get very long very quickly. It is a very simple numbering system. we count like this: Binary: 0. 4. he puts a dollar sign in front of it so that you'll know that it is special. We normally talk in terms of bytes. 10. or a 10's place. we only count up to 1 before starting over. 3. 8 This means that in decimal. D. Does that confuse you? As you might imagine. 1. That place is a 1's place. 1. 3. So in binary. E. so programmers have one little trick to help out. so simple that it confuses lots of people. 6. so 10 is 16. or 16. 10 is 2. 6. To help out. in hexadecimal. $10 is hexadecimal 10. C. 2. and F. B. 2. 5. Where else would 8+8=$10? Or try to figure this one out: $30/2=$18. 11. because the computer is organized around bytes. most programmers use a little hexadecimal calculator that lets them figure these things out quickly and easily. and hexadecimal has 16 numerals. 7. there are eight bits in one byte. and F is 15. B. but 10 is decimal 10. be careful about that last 10. reading hexadecimal numbers can be quite confusing. $10 is 16. 101. C. 8. 8. 2. E. For example. 1. 3. 4. Whenever a programmer writes down a hexadecimal number. Arithmetic is really wild. the number 999 in binary is 1111100111. 4. F. In binary. Doing anything in hexadecimal is enough to drive almost anybody nuts. The one saving grace of binary numbers is that they directly show the status of the bits inside the computer. It is not the same as the 10 you are used to seeing. A bit is the fundamental unit of memory inside the computer. It's really the number after F. 110. The third numbering system that programmers use is called binary. binary has only two: 0 and 1. In the hexadecimal system we count by 16's. But bytes are made up of bits. 9. 7. A. 1000 Decimal: 0. We normally don't worry about individual bits because one bit is too . 5. 10. 1. 111. 7. while decimal has 10 numerals (0. 6. 100. or a 100's place. and 9). Thus. This stuff gets real hairy real fast. They are also very tedious to do arithmetic with. and in binary. 10 is 10. D. Thus. or just plain old everyday 10. So we count like this: 0. 5. Now. or so on in the decimal system.the next place.

it all depends on the context in which the number is taken.small to do much with. notice that a pixel is either black or white. That's how computer games are able to create those animated images. We might say that a 0 means white and a 1 means black. we can process the images themselves. If so. just by processing the numbers that represent the images. Now. a pixel's state can be represented by a binary number. On a black and white display. About all you can do is pack eight of them together into a byte. like Joe's bank balance or Fred's weight. a pixel is either black or white. Now if we apply the powerful numbercrunching capabilities that the computer gives us. Behind every twisting. But there is one situation in which it is handy to worry about individual bits. All computers draw images on the screen by breaking the screen up into little tiny cells called pixels. one for each row in the letter. and then you've got a number between 0 and 255. a 1 or a 0. It can be your plain old. no in between. and that is when you are making a screen graphic. then our letter A can be represented by binary numbers. grimacing alien. like so: What we have here is something very exciting and very important: the ability to express images as numbers. A blow-up of the letter "A" makes the point better than words: Those big black squares are the pixels that we use to draw the A on the screen. Thus. what can you do with something that is either 0 or 1? Not much. The word pixel is a contraction of "picture element". . It could also be an instruction for the computer to execute. I mean. There are many other things that a number might mean. It can also be a character. There are only two states possible for a pixel. everyday number. like an "A" or a "%". It could also be a simple "true or false" indicator. SUMMARY OF NUMBER TYPES We have seen that a number can mean many different things. Or it might be a part of an image. there's a microprocessor frantically shuttling numbers around.

10. Thus is it possible to breathe meaning into something as meaningless as a number. you might be angry at such a stupid language that cannot keep its words straight. Exactly how is context established? As in so many things. 4. created. Both are necessary to create an idea or message. everyday word like "dig" could be interpreted fourteen different ways. How could you tell which of the fourteen interpretations applied? Only from the context. This is nothing new. 6. I could send you the information in a data-intensive form: 2. 6. No. it is established or created by some activity.How is it that one number could mean so many different things? Because we can apply so many different contexts to that one number. So too it is with computers. Suppose that I wish to convey to you scores of six students. If you were a foreigner first learning English. The key word to examine is "established". My Webster's Unabridged lists fourteen different definitions for the word. and suppose that these scores just happen to be 2. 8. A simple. Data are the numbers inside the computer. though. Yet. An idea or a message. Consider the word "dig". 4. and 12. 10. Context is intrinsically part of a process. 12 Or I could send the same information in a process-intensive form: 10 FOR X=1 TO 6 20 SCORE=2*X . you have no problem determining the exact shade of meaning of the word from the context in which it is used. Oddly enough. Data are passive. They may use a number in many different ways. as a fluent speaker of the language. the question bears the seeds of the answer. is composed of both data and process. or forged. number and context. 8. Context is not some static entity that lies on the page the way that data does. Any message can be expressed with any combination of data and process. the ratio of data to process is not fixed. A contrivedly simple example may help make this point. process is what the computer does with them. but the context is always clear. we do it all the time with words. DATA VERSUS PROCESS Let us look more closely at this concept of context. Here we encounter one of the most profound concepts of computing: the complementarity of data versus process in the computer. process is active. context must be established.

and often use it in polishing their programs. a reference book is an ideal source to consult. But suppose we wish to convey information not about facts. A sufficiently clever programmer can obtain almost any desired trade-off of space for time by finding the precise trade-off of data for process. If you regard the computer as a communications medium. then when using a computer. for example. but not very well. we are able to use the printed page to convey a great deal of information about the world. If you want to find the atomic weight of beryllium. translate data-intensive portions into more process-intensive forms. Consider. Because the printed page is a data-intensive medium. It manages. and it does not perform quite as satisfactorily. If a program runs too slowly. Just because data and process are to a large degree interchangeable does not mean that we should use them without bias. On a per-idea basis. with little success? Look how much work I have had to go through to explain to you the small ideas presented in this book. trying to divine the author's explanation of some simple process. certainly. and more effective. How many textbooks have you dragged through.30 NEXT X Both messages convey the same information. But there is a point many programmers miss. there is no medium cheaper. This is because data consumes space while process consumes time. Now we are getting a little more demanding of the medium. We find that the medium is certainly capable of doing so. more convenient. . If a program is too large and must be made smaller. but one uses primarily data and the other uses primarily process to convey the same information. you must always bear in mind the possibility of using another medium to convey your message. but about events. Nevertheless. Now let's go to the extreme of the spectrum and consider the ability of the printed page to convey information about processes. It is especially adept at presenting static data. or some other simple fact. the population of Sierra Leone. it is strongest at presenting data and weakest at communicating processes. one of our most heavily used media. Here is a medium ideally suited for conveying data and quite incapable of directly presenting process. the printed page. but somehow the description of a complicated sequence of events can get a little muddled and require perhaps a few re-readings before we can understand it. Programmers are intensely aware of this process-data duality. translate process-intensive sections into more dataintensive forms.

This is not a medium for storing data. Chapter Seven From Data to Information NUMBERS AND MEANING If you could look into the heart of a computer. that the ideal application for the computer will stress its data-processing capabilities and minimize its data-storage capabilities. the database manager. typically 512 thousand numbers on a personal computer. Concentrate your attention on the context behind the numbers. The jerk who tries to intimidate you with lots of numbers is wasting your time unless he can orchestrate those numbers into a coherant line of reasoning. no aliens to blast. thousands and thousands of numbers. is the only medium we have that can readily handle processes. Numbers are only the junior partner in the partnership of information. the computer might well be said to be more process-intensive than data-intensive. it is a machine for processing it. no programs. With .000 operations per second. is really not a way to store data but a way to select data. Indeed. The moral of this chapter is that data is not information. so are word processing programs. The typical personal computer can store 512. it can perform over 4 billion operations. Spreadsheets are a good example. All you would find are numbers. The fundamental measurement of a computer's power is its storage capacity for numbers &emdash. If you let it run for just four hours. you would find no spreadsheets. no words to process.000 bytes. all other media are expository. you will see that key element in all has very little to do with data storage and very much to do with data processing. But the real appeal of these programs is not the way they allow you to store data but the way that they make it easy to manipulate data. It follows. the reasoning that gives them meaning. if you list the most successful programs for computers. which is derived from the processing to which the numbers are subjected. The senior partner is context. meaningless piles of digits.000 bytes of data.The computer. but the same computer can perform approximately 300. even though holding same measly 512. though. Even the most data-intensive application on computers. Indeed. Be the master of your own numbers. information that was once stored with paper and pencil. therefore. Both allow you to store lots of information. Numbers without context are useless. That is because it is the only medium that is intrinsically interactive.

or programs? Consider atoms. The key word in understanding the difference between data and information is context. 1. or a score on a test. of course. but from the way that they are organized and the context in which they are used. 2. alien invaders. there's a trick that programmers learned long ago. you might wonder what use there is in a computer that can only recognize the first 32. 27 pesos. 32. my bank balance of 27 makes no sense until I specify whether it is 27 dollars. a person with character. 3. the units with which they are measured.767. but information is what we seek to manipulate when we use the computer. The number 110 all by itself doesn't mean anything. It can move them. Even then. 27 cents. and ideas.767. 4. these numbers are not without a context of their own. Data is what the computer stores. it is 110 pounds.767.these numbers. We don't say only that my weight is 110 &emdash. with no fractions or decimal points. If you look deep inside a human being. This is a number ranging from 0 to 32. feelings. Now. NUMERIC DATA They can. you have to include the unit of measure to give it a context to make it meaningful. but little in the way of meaningful interaction. it starts all over again. they have dimensions.767. There is another context to consider when using the computer. the next number is just 0. Similarly. They can interact with each other according to the laws of chemistry.766. The computer stores only numbers. . or somebody's weight. compare. This is a fundamental aspect of all communication systems. represent numbers with values. Data plus context gives information. Where in this mass of numbers and simple manipulations is meaning? How can the computer transform all these numbers into words to process. Simple things. It cannot recognize a number bigger than 32. You can combine little . There are lots of combinations there. all you will find are lots and lots of chemical reactions. atoms. put enough atoms together and you get a human being. Well. depending on the context. 32. It recognizes only one kind of number: the 16-bit integer. First.768 numbers in the whole universe. . the computer is capable of only a very small number of manipulations.765. and perform simple logical operations known as Boolean operations. Meaning does not come from its smallest components. subtract. When it reaches 32. or whatever it is. but it is most clearly present in the computer. but those numbers can represent many things. the computer can count like so: 0. . 32. Yet. add. In other words. things like a bank balance.

you can get bigger numbers. The idea sounds weird until you see some examples: Floating point numbers Integers 12.numbers to make big numbers. it is a number whose decimal point is free to move around ("float" &emdash. 1.00231 90 -451. using the value of π. 7. 8. 5. and so we interpret 10 as "1 in the tens place plus 0 in the ones place. The programmer's trick is to do the same thing with the computer. you pay two prices to get bigger numbers: first." Using this system. This has nothing to do with water or boats. There is also the restriction of context: you have to remember that the numbers in such a compound number belong together and must be taken as a group. how many significant figures does it have? Let me show you an example. get it?) within the number. we can build any number we want.0 -451 As you may have guessed. it's just two old numbers stuck together! Of course.14159265358979323 . Actually. we do it all the time. you know perfectly well that what makes 10 different from 1 or 0 is manner in which you interpret it.893. and second. There's nothing new or different about the number 10. 4. With the computer.366 . 10.35 94. It's nothing but a 1 followed by a 0. 2. Those ten numbers are 0. The big question about any floating point number you have is. The number 10 has a context of its own. it takes one 16-bit word for each part of the number that you add. it takes more computer time to manipulate such bigger numbers. If you stick together 8-bit bytes. and 9. you only know ten numbers yourself. If you think about it. all floating point numbers have a decimal point. It is even possible to group these 16-bit numbers together in such a way as to interpret the group as what is called a floating-point number. 6. 3. You think you know more? Look closely at the next number. We think in terms of "the tens place" and "the ones place".36835418 127 17. The only price we pay is that we have to write lots of digits to express big numbers. 3. rather than individually.

0 or a 3. but not an infinite number.1415926536 3. if you were trying to reconstruct the value of π after I gave you only a 3. with the 3's repeating forever. say it. A floating-point number expressed with 4 bytes has about 7 significant figures. That should yield the fraction 1/3rd. Remember. . that last value of π. but we rounded it off when we went down to only one significant figure. especially with arithmetic. thus. it is rounded off from the previous one. don't read it as 3. For this reason.000000000. or 2. . this discovery tends to upset some people. The second value gives π to 11 significant figures. But now we come to a nasty trick that trips up lots and lots of people. that they can make no mistakes.3. .3333333.14 3 The first value gives π to 18 significant figures. In other words. The difference between the computer's answer (.000 or a 3.3333333) and the correct answer (. because it isn't. you would be wrong to put a 0 after the 3 to make it a 3. For example. yet here is incontrovertable proof that the computer is wrong. 3 is not the same as 3. They think that computers are always right.0000000000? Many people think that 3 is the same thing as 3.. or anything between 2.0. .333333 . A lot of people make the mistake of assuming inappropriate zeros.1416 3. you could express ¹ this accurately with such a computer: π = 3. others may use 8 or even more bytes. it will report the result as . The meaning of significant figures is that they show us the limitations of computers and arithmetic.9. This really rattles their cage.141593 This is fairly accurate for most purposes. is it a 3 or a 3. Now. some computers use only 4 bytes to save a floating-point number.3333333. The third gives it to only 5. each significant figure costs you some RAM space and some execution time. the fourth gives 3. If you want to say 3.) is small (about one part in a million). It could be 3. 3.4999999. The next digit of π after the 3 should be a 1. So. Now. but the fact remains that the computer is wrong.0.0. and the fifth gives only one. but it isn't.5000000 and 3. .0. if I say 3.1. whose decimal value is . with 7 significant figures of 3's. when I do this division on my computer equipped with 4-byte floating point arithmetic. Suppose I divide 1 by 3. Each number is correct to within its number of significant figures.

Let's say that you figured $23.237.The problem is not that the computer is mistaken. the computer will add the numbers like this: 312. Let's say that you had even figured the amount of money to go for buying file folders at the White House. suppose as part of your plan to solve the deficit. You had figured out a detailed plan that included all the critical factors for eliminating the budget deficit without wiping out the economy. The problem is that there is no mathematical way to correctly express the value of 1/3rd with a finite number of significant figures.300. for example. we're talking hundreds of billions of dollars here. say.57 a year would be a good figure. but if you don't enough room to say it. Now suppose you have a "bottom line" routine that adds up all the expenditures of the budget to see what the grand total is. The same thing goes with the computer: with anything less than an infinite number of significant digits. you had developed a computer program to figure out how much money to allocate each part of the Federal budget.00 If you count digits. the 2 in 23. put your plan on that paper with that crayon. For example. There isn't enough room to be accurate in so small a space. and in the process. you will see that the computer's seven significant digits are used up on the high part of the number. Let's say the program statement looks like this: 8230 TOTAL=TOTAL+WHFFOLDERS Now.57 312." You may have the answer. it can round off some of the accuracy of the number.300. Suppose. In some cases.57 is in the eighth . "You think you're so smart. it can completely wipe out your number. I then gave you one piece of paper and a crayon and told you. that you had a brilliant plan to solve. Remember.00 23.237. Let's say that the grand total is about $300 billion dollars by the time the program gets around to adding in your figure for file folders. We call it that because the computer rounds off numbers to make them fit into its floatingpoint format. the computer will sometimes be wrong by a tiny amount. you come out looking pretty stupid. or that it is stupid and cannot perform arithmetic. the problem of the American budget deficit. This problem is so common that it has a name: round-off error.

The reason why A starts at 65 is a bit of technical trivia with which I won't waste your time. Second. which will take more space and run more slowly. ALPHANUMERIC DATA Numbers can mean more than just values. the string data should be placed inside a pair of double quotation marks.significant digit place. The system for using them is very simple. Another difference is that the letter A does not get a 1. First. almost all versions of BASIC will do this automatically for you with a facility called "string data". You can always treat a string as a collection of characters. and you would think that it had a very mysterious bug. but its purpose is not to hide messages but to make them understandable to the computer. C gets 67. Your program would produce unreliable results. while B gets 66. I cannot tell you much more about string handling because different . With this one code you can store text messages inside the computer. To read it out. The moral of this story is. Accuracy truly does have its price. but a 65. This code is similar. right out of existence! It's as if the $23. or "%". A 1 stood for the letter A. a string is always indicated by a "$" symbol at the end of the variable name. and so it is rounded off &emdash. it uses a code called ASCII (pronounced "ass-key").57 never existed. To use it. only understands numbers. That tips off the computer that you want this data treated as a string. Every letter and symbol gets its own number. even though it's really a collection of numbers. if you want the computer to use great big numbers next to little bitty numbers. just convert back. They can also be used to mean alphanumeric characters. you convert a character to a number using the ASCII code and store the number in the computer. Lo and behold. this is one of the natural limitations of the computer. after all. In truth. A string is a collection of numbers that are always treated in the context of ASCII code conversion." This code assigns a number to every character. a 5 stood for the letter E. These are just letters and symbols like "a". and so forth. you need lots of significant digits. an acronym meaning "American Standard Code for Information Interchange. and so forth. "(". Here's a simple example: 50 NAME$="CHRIS" 60 PRINT NAME$ There are only two syntax rules to note about this construction. Using strings from BASIC is very simple. Perhaps you used a code like that when you were a kid. which.

a choice that is either taken or not taken. CHOOSEPRINTER. Two fairly common facilities. which should be 67. although that is certainly the hard way to do it. BOOLEAN DATA Another kind of data is Boolean data. and manipulate them with arithmetic. which is C. allowing you to join strings. just interpreted differently. They can be treated as instructions to the computer. otherwise it would continue on. The program can then keep track of your answer as a variable called. a program might ask you if you want some data sent out to the printer. Quite often. Even then. Remember. and much more. say. Thus. true or false. Try this little example out on your computer: 80 PRINT ASC("C") 90 PRINT CHR$(67) The first line will print the ASCII value of C. who founded the mathematics of formal logic. you can take strings apart. Some allow you extensive facilities for manipulating strings. computer programs allow the user to set a particular choice. named after George Boole. insert and delete sections of a string. find their numeric equivalents. These two functions allow you to see the code conversion process. that it really is a number. though. the Boolean variable is a good way to keep track of such true/false conditions. it would GOTO 2000. though. The second value will print the character corresponding to 67. Thus. Boolean data is very simple: it takes one of only two values. there are two variations on this. Most BASIC languages store a zero to represent a value of false. You can answer yes (true) or no (false). extract a portion of a string. Then. are the ASC function and the CHR$ function. For example.computers handle strings differently. If the result were true. . and something else to indicate a value of true. it might have a statement like this: 1120 IF CHOOSEPRINTER THEN GOTO 2000 This statement would treat the value CHOOSEPRINTER the same way it would treat a logical expression. INSTRUCTION DATA The numbers in a computer can be interpreted in a completely different manner. whenever it is about to send something out.

called machine language. 68. are nothing at all like BASIC. Each instruction has a code number. a BASIC program is slowed down quite a bit by having to go through this interpreter. A BASIC interpreter translates your BASIC commands into the computer's machine language. it is exactly the same as the RETURN statement in BASIC. even if it has executed that instruction thousands of times previously. It is the fundamental language that the computer uses for all its work. then the command PRINT "ABCD" would be stored in RAM as 27. and 68 are the ASCII codes for "ABCD".BASIC Instructions Your BASIC program is stored in RAM as a set of instructions for the computer. Native code is program instructions that are couched in the natural language of the computer. As you might imagine. it must look up the meaning of the instruction in a "book of commands" called an interpreter. you might wonder. These are instructions that the computer itself recognizes as instructions to directly execute. associated with it. 66. That is. 65. But no. The 27 stands for PRINT and the 65. called a token. you must first . What is worse. after it reads a BASIC instruction. does machine language look or sound like? Perhaps you imagine some weird language of beeps and buzzes. the computer must interpret each instruction each and every time it encounters the instruction. Other commands. 67. looking at each instruction code and translating it into action. For example. To RUN a BASIC program. a 96 will tell some computers to return from a subroutine. The interpreter allows the computer to figure out what it is supposed to do. The difference between BASIC instructions and native code is that the BASIC instructions are foreign to the computer. Native code is much faster than interpreted code. What. Native Code The second form of computer instructions are what is called native code. There is more information on machine language in the appendix. This language. 66. however. For example. the computer does not really know what the BASIC instructions mean for it to do. machine language is nothing more than numbers. To understand how this is done. If this were the case. This is data to be displayed on the screen. the token for the command PRINT might be 27. the computer would scan through RAM. PIXEL DATA Data inside the computer can also be interpreted as pixel data. 67. is built deep into the innards of the computer and cannot be changed.

be careful about that last 10. which takes us over the top. which throws that 9 over the top to 0. cast aside your natural familiarity with that 10 and look at it closely. 1. and F is 15. It is not the same as the 10 you are used to seeing. Where else would 8+8=$10? Or try to figure this one out: $30/2=$18. we started over again with 0. so we carry the 1 again. This stuff gets real hairy real fast. reading hexadecimal numbers can be quite confusing. Now. In decimal. C. E. 5. it is the number system that you normally use. we count by 16's in a hexadecimal system. we add 1 to 9. B. we do it like this: 0. 3. F. Now. so we go back to 0. 4. hexadecimal. "hex" in this case means 6. Does that confuse you? As you might imagine. 6. C. 9. but 10 is decimal 10. and end up with a 1 in the hundreds place. 10. You already know about decimal. D. and F. 7. 2. 10. replace it with a 0 and add 1 to the next place. so 10 is 16. It's really the number after F. E. In the hexadecimal system we count by 16's. Thus. but we put a 1 in the 10's place. $10 is hexadecimal 10. 4. What happened was this: we reached 9. It sounds like a number system that witches might use to cast hexes. the last numeral in our possession. Whenever a programmer writes down a hexadecimal number. and binary. but actually. There are three commonly used number systems to master: decimal. B. or just plain old everyday 10. 9. so hexadecimal refers to a base-16 numbering system. D. or a 10's place. most programmers use a little hexadecimal calculator that lets them figure these things out quickly and easily. To go to the next higher number.learn something about number systems. Doing anything in hexadecimal is enough to drive almost anybody nuts. 3. When we reach 99. The next 6 numbers after 9 are A. The rule is simple: when you reach the highest number in the system and go up. carry the one. It is a very . A. 7. or a 100's place. 8. 6. Decimal is the first. or 16. The third numbering system that programmers use is called binary. 2. he puts a dollar sign in front of it so that you'll know that it is special. 5. and "deci" means 10. or so on in the decimal system. 1. so programmers have one little trick to help out. So we count like this: 0. Arithmetic is really wild. That place is a 1's place. That is. 8. The idea to master here is the idea of counting up until we reach the top of the number system and start over. Hexadecimal is the second system. To help out.

A blow-up of the letter "A" makes the point better than words: Those big black squares are the pixels that we use to draw the A on the screen. The word pixel is a contraction of "picture element". 7. 6. a 1 or a 0. what can you do with something that is either 0 or 1? Not much. If so. They are also very tedious to do arithmetic with. 5. while decimal has 10 numerals (0. Thus. 10 is 10.simple numbering system. 101. 8. $10 is 16. 1. The one saving grace of binary numbers is that they directly show the status of the bits inside the computer. 6. 4. 1000 Decimal: 0. so simple that it confuses lots of people. a pixel's state can be represented by a binary number. notice that a pixel is either black or white. 7. 10. About all you can do is pack eight of them together into a byte. 111. 2. 1. because the computer is organized around bytes. But bytes are made up of bits. in hexadecimal. binary has only two: 0 and 1. I mean. then our letter A can be represented by binary numbers. 3. 10 is 2. A bit is the fundamental unit of memory inside the computer. and then you've got a number between 0 and 255. Now. We might say that a 0 means white and a 1 means black. we count like this: Binary: 0. There are only two states possible for a pixel. no in between. But there is one situation in which it is handy to worry about individual bits. we only count up to 1 before starting over. 1. and in binary. and hexadecimal has 16 numerals. So in binary. We normally don't worry about individual bits because one bit is too small to do much with. and that is when you are making a screen graphic. and 9). Thus. In binary. 2. like so: . 3. 11. 5. the number 999 in binary is 1111100111. 100. For example. 4. All computers draw images on the screen by breaking the screen up into little tiny cells called pixels. On a black and white display. one for each row in the letter. 8 This means that in decimal. a pixel is either black or white. there are eight bits in one byte. Are you getting confused yet? Binary numbers get very long very quickly. 110. We normally talk in terms of bytes.

Yet. you have no problem determining the exact shade of meaning of the word from the context in which it is used. or forged. They may use a number in many different ways. context must be established. there's a microprocessor frantically shuttling numbers around. we do it all the time with words. Or it might be a part of an image. the question bears the seeds of the answer. Now if we apply the powerful numbercrunching capabilities that the computer gives us. Context is not some static entity that lies on the page the way that data does. That's how computer games are able to create those animated images. just by processing the numbers that represent the images. Context is intrinsically part of a process. Consider the word "dig". created. My Webster's Unabridged lists fourteen different definitions for the word. Behind every twisting. you might be angry at such a stupid language that cannot keep its words straight. How is it that one number could mean so many different things? Because we can apply so many different contexts to that one number. SUMMARY OF NUMBER TYPES We have seen that a number can mean many different things. It could also be an instruction for the computer to execute. There are many other things that a number might mean. it is established or created by some activity. The key word to examine is "established". It can be your plain old. Here we encounter one of the most profound . it all depends on the context in which the number is taken. everyday number.What we have here is something very exciting and very important: the ability to express images as numbers. If you were a foreigner first learning English. Exactly how is context established? As in so many things. grimacing alien. It can also be a character. like an "A" or a "%". but the context is always clear. This is nothing new. like Joe's bank balance or Fred's weight. DATA VERSUS PROCESS Let us look more closely at this concept of context. How could you tell which of the fourteen interpretations applied? Only from the context. So too it is with computers. No. everyday word like "dig" could be interpreted fourteen different ways. we can process the images themselves. as a fluent speaker of the language. A simple. Thus is it possible to breathe meaning into something as meaningless as a number. It could also be a simple "true or false" indicator.

and 12. and often use it in polishing their programs. 10. translate data-intensive portions into more process-intensive forms. Data are passive. A sufficiently clever programmer can obtain almost any desired trade-off of space for time by finding the precise trade-off of data for process. the ratio of data to process is not fixed. Any message can be expressed with any combination of data and process. Oddly enough. If a program runs too slowly. you must always bear in mind the possibility of using another medium to convey your message. 10. 8. But there is a point many programmers miss. is composed of both data and process. 4. 12 Or I could send the same information in a process-intensive form: 10 FOR X=1 TO 6 20 SCORE=2*X 30 NEXT X Both messages convey the same information. Data are the numbers inside the computer. Suppose that I wish to convey to you scores of six students. the printed page. Both are necessary to create an idea or message. process is what the computer does with them. If a program is too large and must be made smaller. and suppose that these scores just happen to be 2. then when using a computer. Programmers are intensely aware of this process-data duality. translate process-intensive sections into more dataintensive forms.concepts of computing: the complementarity of data versus process in the computer. It is especially adept at presenting static data. Nevertheless. one of our most heavily used media. we are able to use the printed page to convey a great deal of information about the world. number and context. This is because data consumes space while process consumes time. If . If you regard the computer as a communications medium. 6. A contrivedly simple example may help make this point. 4. 8. I could send you the information in a data-intensive form: 2. Just because data and process are to a large degree interchangeable does not mean that we should use them without bias. Consider. process is active. though. Here is a medium ideally suited for conveying data and quite incapable of directly presenting process. but one uses primarily data and the other uses primarily process to convey the same information. An idea or a message. 6. for example.

you want to find the atomic weight of beryllium.000 operations per second. Indeed. This is not a medium for storing data. the computer might well be said to be more process-intensive than data-intensive. Spreadsheets are a good example. it can perform over 4 billion operations. though. information that was once stored with paper and pencil. the database manager.000 bytes. even though holding same measly 512. But suppose we wish to convey information not about facts. Now let's go to the extreme of the spectrum and consider the ability of the printed page to convey information about processes. is really not a way to store data but a way to select data. Because the printed page is a data-intensive medium. It manages. with little success? Look how much work I have had to go through to explain to you the small ideas presented in this book. If you let it run for just four hours. a reference book is an ideal source to consult. It follows. or some other simple fact. But the real appeal of these programs is not the way they allow you to store data but the way that they make it easy to manipulate data. that the ideal application for the computer will stress its data-processing capabilities and minimize its data-storage capabilities. and it does not perform quite as satisfactorily. We find that the medium is certainly capable of doing so. therefore. more convenient. so are word processing programs. certainly. That is because it is the only medium that is intrinsically interactive. but somehow the description of a complicated sequence of events can get a little muddled and require perhaps a few re-readings before we can understand it. . Indeed.000 bytes of data. The computer. The typical personal computer can store 512. How many textbooks have you dragged through. Even the most data-intensive application on computers. you will see that key element in all has very little to do with data storage and very much to do with data processing. On a per-idea basis. the population of Sierra Leone. it is strongest at presenting data and weakest at communicating processes. trying to divine the author's explanation of some simple process. but the same computer can perform approximately 300. but not very well. all other media are expository. there is no medium cheaper. it is a machine for processing it. Now we are getting a little more demanding of the medium. if you list the most successful programs for computers. is the only medium we have that can readily handle processes. and more effective. but about events. Both allow you to store lots of information.

Let's go over them: The first concept is the importance of clarity of expression (Chapter Two). which has developed its own language (mathematics) for precise expression of its concepts. What has been accomplished? The central message that I have tried to show in this book is that the computer concisely expresses many of the concepts central to civilization. you quickly learn to get your statements precisely correct or suffer the syntax error. science. Concentrate your attention on the context behind the numbers. meaningless piles of digits. And the computer reduces the decision-making process to its absolute essence. We see the same concept throughout many fields: law. which is derived from the processing to which the numbers are subjected. the reasoning that gives them meaning. Numbers are only the junior partner in the partnership of information. The senior partner is context. Throughout our civilization you can find people sweating over the precise expression of an idea. even advertising. Perhaps nowhere else is it better expressed than in the American political and legal system. the willingness to analyze a problem endlessly &emdash. Chapter Eight Conclusions We have journeyed a long way together. which has learned how to twist language masterfully to create impression without substance. these are hallmarks of our civilization. which expends vast efforts on achieving a correct decision-making process.The moral of this chapter is that data is not information. the enjoyment of carefully constructed disputation. allowing us to clearly see the central components of decision-making. The formal study of reason. The science and art of decision-making (Chapter Four) is the second great achievement of civilization. . Be the master of your own numbers. What other civilization would set free an admitted criminal solely because the process used to establish guilt was flawed? Or consider the fact that the American constitution sets no policies of the government whatever. which has developed the precise interpretation of English to a high art. Numbers without context are useless. With the computer. The jerk who tries to intimidate you with lots of numbers is wasting your time unless he can orchestrate those numbers into a coherant line of reasoning. it concerns itself solely with the process by which political decisions will be made.

smog. make the numbers dance. the same thing. is perfectly captured in the loop of a computer program. of course. and we have created unanticipated problems of excess &emdash. We love to hate bureaucracies. It matters not whether we are sawing lumber. Perhaps this is because a civilization is not a collection of artifacts or even people. the child of the civilization that created it. The taming and harnessing of numbers is the fifth great hallmark of civilization embodied in the computer (Chapter Seven). And a computer program with subroutines is a microcosm of a complex bureacracy. the computer is. It is created for the same reasons. the economy of scale associated with repetitive work. A civilization is. The parallels between the computer and the central structures of our civilization are no accident. Sometimes our productivity has outrun our wisdom. The only surprising thing is that it manages to capture so much of the essence of our civilization." The trick was not in the manipulation of numbers per se. or navigating a ship. and solves them in the same way. we owe our wealth and comfort to the economies of scale associated with highly repetitious production. irrigating crops. and a computer is. the numbers obediently dance to our tune. faces the same problems. at heart. The fourth great achievement of civilization is the development of the bureaucracy (Chapter Six) as a means of controlling so complex a phenomenon as a civilization. "To measure is to know. and technostress &emdash. but the computer does seem to be a convincing homonculus . and translate the results of their dance back into real-world results. The computer is the perfect tool to choreograph and observe the waltz of the numbers. but these are problems that the peasant of two centuries ago would have dearly loved to suffer. The essential nature of repetition. Lord Berkeley caught the spirit of it when he wrote. but rather a logical structure for controlling processes. after all. With each passing decade. but we all know that we simply cannot live without them. but rather in the ability to relate numbers to the real world.Repetition (Chapter Five) is the next great triumph of civilization. building larger and more efficient tools that allow us to create more and more wealth faster and faster. We have developed mathematics and applied it to a huge variety of problems. the hand-made. traffic congestion. Despite our romantic attachment to the individualized. we have pushed the scale higher and higher. We translate real-world phenomena into the cyber-world of numbers. an immensely richer and more complex structure than a computer.

"I'm sorry. He's just got to slow down every discussion with endless quotations of data. loaded with a zillion numbers about every aspect of the company's business. is the high school kid who falls in love with the computer. Thus. But how much better armed they are to enforce their puny view of the universe when they can say. The lessons of the computer impart a kind of intellectual power to their users. sex. It starts out innocently enough. that you may apply it to real-world problems. It's not that computers are small-minded. he learns many of the . we see a corps of overconfident technophiles who bring too much certainty to all aspects of their thinking." A variation on this is the number-happy manager. They know the answer to every question of politics. The quality of the numbers that come out of a computer is only as good as the quality of the numbers you put in. That certainty has been the source of more pig-headedness and nonsense than any anti-rationalist mysticism to sweep our society. and religion. and power always corrupts in proportion to weakness of character.to civilization. The black-and-white world of the computer does not admit subtle shades of gray. Of course. And most of the numbers that go into such a program are garbage. or that computer programmers are small-minded. The goal of this book is to teach you this style of thinking. but don't overdo it! The greatest victim of the computer. garbage out". It means "Garbage in. is to gain a glimpse into the heart of our culture. though. Consider the bureaucrat who inflexibly sticks to the rules even when it is to the obvious detriment of the bureaucracy as a whole. Johnny is curious about this computer stuff and shows some aptitude for it. As he plunges into it. we can't go bending the rules just because it might make things go more smoothly this time. To understand the logic of a computer. His parents give him a computer to encourage him. The clarity and precision of computer-style thinking gives a false sense of certainty to the small-minded. Rules are rules. But we must not overrate our understanding. There is also the danger of taking the lessons of the computer too seriously. the computer can't take it any other way. The best retort to this fellow is an acronym: GIGO. we didn't need to invent computers to create such people. He's got his computer printouts. then. you know. especially when we deal with the computer. but rather that small-minded people who learn the computer can do a lot of damage.

The real world is unresponsive. The day inevitably comes when the boss demands more than simple codehacking. His parents and teachers. maybe ten years. He stays up late. But whatever the symptom. His curiousity is always rewarded with discovery. the human pollution of our high-tech industry. especially learning that comes so easily. They are emotionally and educationally stunted. I have known many such whiz kids. encourage him in this. with whom communication is difficult. working on his programs. But there is more. He skips college. learning subroutines and stacks when he should be making a fool of himself with girls. Numerous excuses are given for the failure of whiz kids at an early age. forswearing beer busts and other crucial instructive foolishness for the foolishness of a job earning more money than his father. Deeper and deeper he sinks. school. and the whiz kid cannot satisfy the demand. something unavailable to a person without a college degree. Not one has beaten the curse. and girls. Others point to the need for career development.same lessons that this book has presented. The power to make things happen inside the computer. But most important. something he hasn't had before. which would you choose? And so our tragic hero renounces parents. every . But the computer responds to every communication in a fair and understandable manner. the underlying reason for failure is that whiz kids are not fully developed human beings. and pledges himself to the computer. a friend with whom the kid can talk. the first activity to which he has truly applied himself. the natural result of a too-intense workstyle. The real world has parents with unreasonable demands. It is the highest price we pay for the computer revolution. It is a tragic waste of talent. For five. Faced with the real world or the computer in your bedroom. Even the computer has its dark side. The computer obeys his every command. Some call it burnout. not seeing the trap. This should come as no surprise. He learns power. catered to and pampered. and he retreats further into his soulless world. and there is no more addictive drug than learning. The real world has girls with whom all interaction is invariably embarassing. mastering every intricacy of the technology. and most insidious. Some point out that whiz kids don't get along well with co-workers. the real world treats him like a dumb kid. is the cheerful willingness of the computer to be a companion. unable to cope with anything other than the computer. Society toasts him as a "Whiz Kid". he is treated like a budding genius. Then something goes wrong and he is discarded like an old sweater.

At each stage of the game. has potential for positive or negative uses. However. they do tend to pile one on top of one another in a rather intimidating heap. Level One: Transistors . nor deify them. for wisdom is outside the scope of this book. while the concepts themselves are simple. even bigger group of building blocks. And here I must stop. These forces were not foisted on us by some malicious demon &emdash. from needle to A-bomb. If you pay attention and bear with me. The computer does not introduce any new dehumanizing elements into our society. We must learn to use them wisely. will be worth the mental exertion. but not an impossible one. Leaping from atoms to societies is a mind-boggling endeavor. Appendix How Computers Work Goal of this Appendix My goal in this appendix is to explain in simple terms exactly how it is that a collection of silicon can do all the wonderful things that computers can do.tool we make. I assure you. It is the latest and most refined expression of forces that have been at work in our civilization for hundreds of years. This is certainly a tall order. We must not blame our tools. I'll start with the simplest building blocks and use them to assemble bigger building blocks. My fundamental strategy in this appendix will be a process of agglomeration. it really can make sense. but if you take it in steps. Its kind of like going from atoms to molecules to cells to people to societies. the result &emdash. Let's begin. we'll pick this heap apart. These bigger blocks will then form the basis for the next. you forget the internal details and just treat it as a black box whose properties you have already figured out. once you understand how the building block is put together. you should have no problems understanding this appendix. The computer is a single point in the cannonball trajectory of civilization. Those who bemoan the dehumanizing influence of the computer have forgotten their heritage. If you have followed me this far. connected to all other points and existing because of them. the knowledge that even the mighty computer is within your mental reach &emdash. they are the expression of the desires and efforts of millions of people over scores of generations.

It's rather like the double light switches in long hallways in some houses &emdash. The second special property of the transistor that makes computers possible involves a special type of transistor that can not one but two independent controlling wires. so that electricity on the input wire will yield no electricity on the output wire. we say that it means "1". If a wire has electricity on it (meaning that a transistor connected to it has turned on). Electricity means 1. It is also possible to make transistors reverse this relationship. The big trick is its ability to control the flow of many electrons with just a few electrons. What they do is very simple. then the wire represents a "1". Normally. The third special property of transistors is their ability to invert the relationship between input and output. You can use the presence or absence of electricity in one wire to turn on or turn off electricity in another wire. we think of the transistor as creating a direct relationship between the input wire and the output wire: if there is electricity on the input wire. it uses a few moving electrons to stampede many more electrons. either one will turn on the light. and if there is no electricity on the input wire. we say that it means "0". Let's summarize what we've got on transistors with some simple diagrams: . Crudely speaking. It's not as if there are tiny little 1s and 0s printed on the wires. to compute) by manipulating electricity. it's a code. We can extend the idea to the wires inside a computer.. This gives us the ability to manipulate numbers (i.The atoms of a computer are transistors. All the 1s and 0s inside a computer are just represented by transistors that are turned on or off. The result is like a switch that is controlled by electricity instead of a finger. I said that a transistor is like a switch that is controlled by electricity instead of a finger. and treat those two states as numbers. and no electricity on the input wire will yield electricity on the output wire. it is possible to make a transistor that uses two finger-wires instead of just one. Well. A transistor controls the flow of electricity by controlling electrons. If the transistor is on. if the wire has no electricity.e. it represents a "0". then it turns off the output wire. The first is that we can run it either all the way on or all the way off. Earlier. no electricity means 0. it turns on the output wire. Three special properties of the transistor make it possible to build computers out of transistors. if it is off. but how they do it involves a great deal of tricky physics. A typical personal computer will have millions of these little devices inside its chips.

. The first type of gate is called an "AND" gate. This gate is drawn as follows: The rule for the AND gate is simple: if the first input is a 1 AND the second input is also a 1. then the output will be a 1. A gate is an electronic circuit that accepts one or more inputs and produces a single output that is a logical function of the inputs. Otherwise. this is just like the OR Boolean function you met in programming and is the hardware source of the software capability. it will be a 0. and the diagram we use for it looks like this: The rule for the OR gate is also simple: if the first input is a 1 OR the second input is a 1. then the output will be a 1. this is the electronic circuit that the computer uses to make that program work. Whether or not the output wire will have electricity on it depends on the electricity on the input wires and the rule that the gate uses. This is just like the Boolean AND function you use in programming. The second type of gate is called the "OR" gate.Level Two: Gates (Assemblies of Transistors) We can use transistors as the building blocks for the next level in our hierarchy: the gate. In simple terms. Otherwise. it will be a 0. you plug wires into it and it has one wire coming out of it. Again. in fact.

we can use a decoder to talk about "that one". The first new assembly is called a decoder. However. If we hook it up directly to a light. Thus. and it is diagrammed like so: The inverter simply takes the input and inverts it.The third simple gate is hardly a gate at all: it is a simple inverter. for example. If you put a 0 into this decoder. The next doodad we will build is called a latch. it will turn the light on when we have a 1 on it. use it to select one of two light switches that we might want to turn on. This little guy is handy for all sorts of jobs. We build this one from NAND . It can carry a 1 or a 0. In other words. Latches. a decoder translates "Gimme number x" into "Gimme that one". Level Three: Decoders. then we want to turn on light #0. In short. A decoder for this job might look like this: If you put a 1 into this decoder. Ouput #0 will have a 1 on it and Output #1 will all have 0. and if it has a 1 on it. Instead of talking about "the third one". one wire can represent one of two choices. Its purpose is to electronically convert a numeric reference to a specific one. then we want to turn on light #1. for example. We could. so that a 1 becomes a 0 and vice versa. Adders (Assemblies of gates) We can use the gates we have just built to create even more elaborate devices. if the wire has a 0 on it. then Output #0 will get a 1 and Output #1 will get a 0. Suppose. that we have a wire. We need a decoder. there's a problem: the wire by itself can't turn on the right switch. and turn it off when we have a 0 on it.

In this case. If you make the "Remember 1" wire 1. "NAND" means "Not AND". AND Input #1 is a 1. then the output will be a 0. then the output wire will be 1. If you then make the "Remember 0" wire equal to 1. otherwise. It is not a snake. it is just an AND gate whose output is inverted. here is a latch: (Here's another fine point: when wires cross. they are not considered to be connected unless there is a dot marking the spot. and revert to the normal state in which both wires are 0. then the output wire will be 0. this circuit will be able to calculate just four possible additions: 0+0=0 0+1=1 1+0=1 1+1=10 . but a circuit that will add two numbers together. In other words.gates. the output will be a 1. we are going to keep it real simple: we are going to add two single-bit numbers. after you stop making one of those wires 1. in this diagram. We indicate this by putting a little circle on the end of the AND gate. but what it does is simple and important: it remembers. that makes it a NAND gate. In other words. More important. The rule for a NAND gate is as follows: if Input #0 is a 1. Thus. So. It remembers! The last device we will assemble is called an adder.) This one may look a little intimidating. Suppose that you start off with both inputs ("Remember 0" and "Remember 1") set to 0. There are four connections marked by four black dots. there is no connection between the diagonally crossing wires in the center. we take a plain old AND gate and stick an inverter on its output. then the output will STILL reflect the state that you put it into earlier.

Time for the next step. Here's a diagram: This is nothing more than eight separate latches sitting side by side. Level Four: Breadth We are now going to expand the circuits we have to make them more practical with real numbers. Who wants to add 1 to 0 all day long? Who needs to remember just a single 1 or 0? The big trick we are going to pull is embarassingly simple. The latch can remember only one bit. and add. Lo and behold. selecting one of only two possible options. Here's what the adder looks like: We now have devices that can select. so the equation really does work. for it's the easiest one to understand. Eight bits side by side. each one can handle only a single bit of information. and binary 10 is just decimal 2. since when did one plus one equal ten? Remember.That last addition may throw you. These devices are almost useless. remember. but you have known and used him many times. they will suddenly be useful! Let's start with the latch. The above circuits are all single-bit circuits. we are working in binary numbers here. a single 1 or 0. The decoder can decode just one wire. This little guy may not look like much. You can . May I introduce you to one byte of RAM. And the adder can only add two single-bit numbers. We are going to gang each of these devices up in parallel with a bunch of its brothers.

of course. What do you use a decoder for? I'll get to that in the next section. The two-bit decoder looks at two wires to select one of four possible options. That's enough to denote one character of text. then there are four possible combinations of the 1s and 0s: 00. but it is occasionally useful to a programmer. . 10. 01. or an integer between 0 and 255. The example I gave earlier was a one-bit decoder. one little latch may not do much. and 3. and 11. Now let's turn to the decoder. Three wires would give eight combinations. eight wires would give 256 combinations. and it makes an excellent introduction the next broadening trick. By making our decoder a little bit bigger. I have to admit. it suddenly becomes a worthwhile bit of silicon. we'll broaden out an AND-gate: This device allows us to take two eight-bit numbers. it's not one of the most useful stunts in the world. 2. 1. you will recognize these numbers as just decimal 0. why anybody would want to AND two numbers together. Here is a two-bit decoder: The single-bit decoder looks at one wire to select one of two possible options.store an eight-bit number in here. For out next breadth trick. but when it gangs up with seven siblings. If you have two wires carrying 1s or 0s. You may wonder. If you can read binary. AND them together. As you can see. and read the result at the output of the gates. we make it a lot more powerful.

What do we do with the extra digit when we add 1+1? All the other additions yield but a single bit of output. Level Five: Assembling RAM Now we are ready to construct our first major computer component: the computer's RAM. We will call it the "Carry" wire. We start at the right side of the number. you write down the result and carry up the one. and every bit needs one wire. All this nonsense with carry bits is important because it allows us to expand our adder to a useful size.536. in this case).) It takes no great leap of imagination to go from one byte to 65. If the one-bit adder ends up generating a carry. We will need better adders that can use the carry bit that is passed to them. They are obsolete now. That second wire will be treated differently. You probably know. adding just one column at a time. because the individual bits in an addition are not independent the way the latch bits in a byte are independent. that's 65. In the previous section. a carry bit that would come from a lower stage in the addition. write down the 0 and carry up the one to the next decimal place (or binary place. which adds it into its work. put down the 3 and carry up the 1"? The rule with addition is that when you get a number bigger than ten. that a typical microcomputer has 64K bytes of RAM &emdash. but the bigger computers that people use nowadays work on the same principles. There remain.Now we are going to broaden the one-bit adder. but that is simply a matter of a few more gates. "5 plus 8 is 13. It's the same way with binary addition. If we now throw in a circuit that will also add in an input carry bit. though.536 bytes total. Consider this example: we want to add two eight-bit binary numbers: 10110011 +01010101 If we break this addition up by digits. I showed you a single byte of RAM. however. a few practical problems associated with . Recall the problem of the one-bit addition. so we will need two output wires to represent the output. you get 10. then we can use a one-bit adder for each column. but this one needs an extra bit. This is a tricky operation. when you add 1+1. Do you remember your old addition exercises in grammar school? Do you remember chanting little songs like. then we can build adders as wide as we want. (Let's keep this simple by ignoring the current generation of 16-bit and 32-bit computers. I'll talk only about the simpler 8-bit computers that were the rage in the early 1980s. it passes the carry on to the next higher one-bit adder. just like you do in regular addition.

how do we get data into and out of the bytes? An address . and so forth until we reach the last byte. Thus. To summarize address buses: an address bus is a group of 16 wires that run from the main processor to the RAM. "I need to know what number was stored in byte number 37. called an address. The RAM chips have eight latches for each byte they store. A bus is a bundle of wires that everyone shares.actually using all that RAM. For example. and a huge decoder that decodes the address bus and selects the appropriate byte. That way. those little wires are built directly into the silicon chip. The first byte is called byte 0. saving everybody a lot of soldering.536 bytes it wants to use? It surely can't have 65. You may wonder. When the main chip tells the RAM. the next one is byte 1. Every computer has three buses: the address bus. The next question is. The address bus is the easiest to understand. There is.535 would have the binary code 1111111111111111 on the address bus.353 would have the binary code 1001000111101001 on the address bus. all the 65. "You're the one he wants" &emdash. that the computer can use to refer to it. how does the RAM decode that number to select the right byte? The answer comes from that decoder circuit that we worked up earlier. while byte number 65. but it's a little harder to understand. though. then byte 2. and the control bus. how the RAM can actually figure out which byte is the proper one. Sixteen wires allow us to specify any of these addresses. This is a group of 16 wires coming out of the main chip. How does the computer select which of those 65.536 little wires coming out of the main chip. The solution is to use an address bus. It allows the computer to specify exactly which byte it wants out of RAM. It's called a bus.535. Byte number 37. with one wire going to each byte of RAM.536 bytes with only a sixteen-wire address bus. If each byte of RAM has eight wires going into it and eight wires coming out of it. the data bus.353". byte number 0 would have the code 0000000000000000 on the address bus. the computer will need over one million little tiny wires inside just to hook up all those bytes. byte number 65. 3. You build a big decoder into each RAM chip that can decode the address bus and figure out exactly which byte is being accessed. Each byte of RAM has its own unique number.536 little wires that go directly to the bytes to say. That's ridiculous! There's gotta be a better way. a computer can specify any of its 65.

536 people on it. a 1. each byte of computer RAM stays shut up until the computer authorizes it to talk through the address bus. two. . a 1. I'm still a 0. yes I am. a 0. . Imagine him shouting into a pipe: "I'm a 0. a 1. that byte number 37 has the value 11111111 stored inside. yes. three. that raises a problem: who talks on the data bus? Let's say. The second trick to making a data bus work requires the use of a control bus. but three: 0. RAM is supposed to work two ways: either the computer wants to save a number into RAM. while byte number 38 has a 00000000 stored inside it. three. 1. or it wants to recall a number out of RAM. but they won't talk until the master operator tells them to talk. If both bytes are putting their values onto the data bus. four. It keeps everybody synchronized. Thus. you can shut him up with an electrical signal. Now.536 bytes of . Thus. then what does it have: 1s or 0s? Who wins when everybody talks at once? The answer to this question involves two tricks: tri-state logic and a control bus. now I'm a 1. a data bus is like a huge telephone party line with 65. tall 1. A data bus is a group of wires that run from the computer to the RAM. in a regular cycle. It is eight bits wide. and so allows the computer to transfer data a byte at a time. The other common wire on a control bus is called the clock signal. A regular chip is always sending out his value on his wire. 0. 0. a 1. I'm still a 1. Even handier.bus lets the computer point to a particular byte and say." This allows them to synchronize their actions. So we run a few more wires from the computer to the RAM called a control bus. I'm a big. After all. The first wire in the control bus tells the RAM whether it's being accessed for a write or a read operation. four. The data bus goes to every single byte in the computer's RAM. " A tri-state RAM chip can be a 0. with the data bus. You might say that this wire is a command to either talk or listen. silicon-head!" But how does the computer get data into or out of the byte? The answer is. "I'm talking to YOU. This wire goes on and off. or he can shut up. We also call this writing and reading. a big fat 0. except with bytes rather than knives. "One. . for example. one. two. or disconnected. whoops. Tri-state logic is a variation on normal chip design that allows a chip to have not just two states (0 or 1). a 1. . on and off. The clock wire in the control bus serves the same purpose. We have now built an imaginary RAM module that can store 65. Have you ever watched two jugglers tossing pins or knives back and forth? They count off to each other.

The first of these is the address controller. The ALU is a rather like one of those all-purpose handy-dandy kitchen utensils that slices. and shreds. Each of these is eight bits wide. you bring it to your desk. It activates the proper blade with a decoder-selector circuit and something like tri-state logic in much the same way that our RAM module selects the correct byte and tells everyone else to shut up. calls the subroutines. You will recall from Chapter Seven that bytes in the RAM can represent many different things. an OR-gate set. tell it which handy-dandy blade you want it to use. the instruction decoder. Almost all programs follow a very simple strategy: bring some bytes out of RAM into the registers. You ship two bytes to the ALU. From the point of view of the CPU. and an adder. This is the unit that actually crunches the numbers. We shall take up the ALU first. In this highly simplified and imaginary computer. the ALU contains four fundamental byte-munchers: an AND-gate set. Instead of a collection of blades in various shapes and sizes.information. and loops the loops. The next two parts of the CPU are trickier because they handle the more complex task of making the program go. The address controller fetches . The desk can't hold many documents. and you read the byte of output. only it does its work on bytes rather than morsels. spit out the results back into RAM. The relationship between register-RAM and regular RAM is rather like the relationship between a desktop and a desk drawer. those bytes in RAM fall into two broad categories: data to be processed. we will have but four parts: the ALU. taking two bytes as input and producing a single byte as output. crunch them up. ALU is an acronym for "Arithmetic and Logic Unit". These are simply bytes of RAM inside the CPU that can be used as quick storage of intermediate results. The registers are another simple part of the CPU. You keep your papers in the desk drawer most of the time. Level Six: The Central Processing Unit (CPU) Our next creation will be the heart of the computer: the CPU. the registers. and the address controller. but when you are actually working with a particular document. The computer can read and write data into it. These first two parts of the CPU (the ALU and the registers) are devoted to handling data. and EOR-gate set. but they are much easier to work with on your desk than in your desk drawer. its task is to get program instructions out of the RAM and into the CPU. and the whole thing is practical to build and operate. or instructions that tell how to process the data. dices.

this is done with additional bytes that follow the main instruction byte. Now we are ready to tackle the inner sanctum of the CPU: the instruction decoder. then the decoder will select the proper registers or RAM locations and send the proper signal to the Read/Write line on the control bus to indicate the direction of the move operation. This is the module that actually translates instructions into action. or from RAM to a register. There are two broad types of information conveyed in a typical microcomputer instruction: what to do and who to do it to. You could move a byte from one register to another register.those instructions out of the RAM in the proper sequence and delivers them to the CPU. All this is based on a fancy decoder circuit. if we have a move instruction. most programs follow an alternating sequence of "fetch an instruction. the most necessary of all the necessary components. from a register to RAM. These are very simple manipulations. The crunching part just tells the CPU to use the ALU to crunch two bytes. The "what to do" part is easy to understand. Moving information is just a matter of taking a byte from one place and storing a copy someplace else. The next part of the instruction specifies the object of the command. If the instruction indicates a move operation. It is the heart and soul of the entire computer. we must specify the source and destination register or RAM location. fetch a byte of data". Depending on the complexity of the processor. For example. you might have any number of combinations here. Thus. the address controller merely loads in the address of the new instruction and proceeds from the new location. successive instructions are placed in successive RAM locations so that the address controller doesn't have to think too hard to figure out where to get the next instruction. the decoder activates the ALU. It's that simple. if the program needs to branch or loop. However. Each program instruction sits at an address in RAM. The address controller also handles the manipulations required for branching and looping. The bits of the instruction go to the decoder. It is based on nothing more than the simple decoder. Thus. the essence of the computer. With a typical home computer. This boils down to just two basic types of commands: move information or crunch information. If they indicate a crunching operation. with a number of intricacies added. the command would consist of three bytes. sending it the proper code to activate the desired circuitry inside the ALU. The first . normally this is a register or RAM-location.

some might activate multi-step sequences. Some decoders might open up pathways in the CPU to ship bytes around to different locations. opens up a digital pathway that will send the next two bytes straight into the address controller. when it receives the first byte. it might be very complex. In a real computer. The second and third bytes give the 16-bit address of the RAM location. . then. then it activates the address controller. which in turn fetches the byte from the address it holds. the instruction decoder translates instructions into action by using decoders that activate different sections of the CPU.byte says "Load this register with the byte in the RAM location whose address follows". but it is certainly not magic. And that is how computers work. In essence. The instruction decoder. some might activate the ALU.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->