The Secret Guide to Computers
A letter can stand for a number. For example, x can stand for the number 47, as in this program:
The second line says x stands for the number 47. In other words, x is a name for the number 47.
The bottom line says to print x + 2. Since x is 47, the x + 2 is 49; so the computer will print 49. That’s the only number the computer will print; it will not print 47.
A letter that stands for a number is called a numeric variable. In that program, x is a numeric variable; it stands for the number 47. The value of x is 47.
In that program, the statement
A variable is a box
When you run that program, here’s what happens inside the computer.
The computer’s random-access memory (RAM) consists of electronic boxes. When the computer encounters the line “x = 47”, the computer puts 47 into box x, like this:
box x │ 47 │
Then when the computer encounters the line “PRINT x + 2”, the computer prints what’s in box x, plus 2; so the computer prints 49.
Instead of typing —
you can type just this:
At the end of that line, when you press the ENTER key, the computer will automatically put spaces around the equal sign.
Since the computer automatically capitalizes computer words (such as CLS), automatically puts spaces around symbols (such as + and =), and lets you type a question mark instead of the word PRINT, you can type just this:
When you press ENTER at the end of each line, the computer will automatically convert your typing to this:
Here’s another example:
The second line says y is a numeric variable that stands for the number 38.
The bottom line says to print y - 2. Since y is 38, the y - 2 is 36; so the computer will print 36.
The second line says b is 8. The bottom line says to print b * 3, which is 8 * 3, which is 24; so the computer will print 24.
One variable can define another:
The second line says n is 6. The next line says d is n + 1, which is 6 + 1, which is 7; so d is 7. The bottom line says to print n * d, which is 6 * 7, which is 42; so the computer will print 42.
Changing a value
A value can change:
The second line says k’s value is 4. The next line changes k’s value to 9, so the bottom line prints 18.
When you run that program, here’s what happens inside the computer’s RAM. The second line (k = 4) makes the computer put 4 into box k:
box k │ 4 │
The next line (k = 9) puts 9 into box k. The 9 replaces the 4:
box k │ 9 │
That’s why the bottom line (PRINT k * 2) prints 18.
When writing an equation (such as x = 47), here’s what you must put before the equal sign: the name of just one box (such as x). So before the equal sign, put one variable:
Allowed: d = n + 1 (d is one variable)
Not allowed: d - n = 1 (d - n is two variables)
Not allowed: 1 = d - n (1 is not a variable)
The variable on the left side of the equation is the only one that changes. For example, the statement d = n + 1 changes the value of d but not n. The statement b = c changes the value of b but not c:
The fourth line changes b, to make it equal c; so b becomes 7. Since both b and c are now 7, the bottom line prints 14.
“b = c” versus “c = b” Saying “b = c” has a different effect from “c = b”. That’s because “b = c” changes the value of b (but not c); saying “c = b” changes the value of c (but not b).
Compare these programs:
In the left program (which you saw before), the fourth line changes b to 7, so both b and c are 7. The bottom line prints 14.
In the right program, the fourth line changes c to 1, so both b and c are 1. The bottom line prints 2.
While you run those programs, here’s what happens inside the computer’s RAM. For both programs, the second and third lines do this:
box b │ 1 │
box c │ 7 │
In the left program, the fourth line makes the number in box b become 7 (so both boxes contain 7, and the bottom line prints 14). In the right program, the fourth line makes the number in box c become 1 (so both boxes contain 1, and the bottom line prints 2).
When to use variables
Here’s a practical example of when to use variables.
Suppose you’re selling something that costs $1297.43, and you want to do these calculations:
multiply $1297.43 by 2
multiply $1297.43 by .05
add $1297.43 to $483.19
divide $1297.43 by 37
To do those four calculations, you could run this program:
But that program’s silly, since it contains the number 1297.43 four times. This program’s briefer, because it uses a variable:
So whenever you need to use a number several times, turn the number into a variable, which will make your program briefer.
A string is any collection of characters, such as “I love you”. Each string must be in quotation marks.
A letter can stand for a string — if you put a dollar sign after the letter, like this:
The second line says g$ stands for the string “down”. The bottom line prints:
In that program, g$ is a variable. Since it stands for a string, it’s called a string variable.
Every string variable must end with a dollar sign. The dollar sign is supposed to remind you of a fancy S, which stands for String. The second line is pronounced, “g String is down”.
If you’re paranoid, you’ll love this program:
The second line says t$ stands for the string “They’re laughing at you!” The later lines make the computer print:
Spaces between strings
Examine this program:
The bottom line says to print “sin” and then “king”, so the computer will print:
Let’s make the computer leave a space between “sin” and “king”, so the computer prints:
To make the computer leave that space, choose one of these methods.…
Method 1. Instead of saying —
make s$ include a space:
Method 2. Instead of saying —
make k$ include a space:
Method 3. Instead of saying —
say to print s$, then a space, then k$:
Since the computer will automatically insert the semicolons, you can type just this —
or even type just this —
or even type just this:
When you press the ENTER key at the end of that line, the computer will automatically convert it to:
The computer can recite nursery rhymes:
The second line says p$ stands for “Peas porridge ”. The later lines make the computer print:
This program prints a fancier rhyme:
Lines 2-4 define h$, m$, and c$. The later lines make the computer print:
If you don’t define a numeric variable, the computer assumes it’s zero:
Since r hasn’t been defined, the bottom line prints zero.
The computer doesn’t look ahead:
When the computer encounters the second line (PRINT j), it doesn’t look ahead to find out what j is. As of the second line, j is still undefined, so the computer prints zero.
If you don’t define a string variable, the computer assumes it’s blank:
Since f$ hasn’t been defined, the “PRINT f$” makes the computer print a line that says nothing; the line the computer prints is blank.
Long variable names
A numeric variable’s name can be a letter (such as x) or a longer combination of characters, such as:
For example, you can type:
The computer will print:
The variable’s name can be quite long: up to 40 characters!
The first character in the name must be a letter. The remaining characters can be letters, digits, or periods.
The name must not be a word that has a special meaning to the computer. For example, the name cannot be “print”.
If the variable stands for a string, the name can have up to 40 characters, followed by a dollar sign, making a total of 41 characters, like this:
Beginners are usually too lazy to type long variable names, so beginners use variable names that are short. But when you become a pro and write a long, fancy program containing hundreds of lines and hundreds of variables, you should use long variable names to help you remember each variable’s purpose.
In this book, I’ll use short variable names in short programs (so you can type those programs quickly), and long variable names in long programs (so you can keep track of which variable is which).
Programmers employed at Microsoft capitalize the first letter of each word and omit the periods. So instead of writing:
those programmers write:
That’s harder to read; but since Microsoft is headed by Bill Gates, who’s the richest person in America, he can do whatever he pleases!
Humans ask questions; so to turn the computer into a human, you must make it ask questions too. To make the computer ask a question, use the word INPUT.
This program makes the computer ask for your name:
When the computer sees that INPUT line, the computer asks “What is your name?” and then waits for you to answer the question. Your answer will be called n$. For example, if you answer Maria, then n$ is Maria. The bottom line makes the computer print:
When you run that program, here’s the whole conversation that occurs between the computer and you; I’ve underlined the part typed by you.…
Try that example. Be careful! When you type the INPUT line, make sure you type the two quotation marks and the semicolon. You don’t have to type a question mark: when the computer runs your program, it will automatically put a question mark at the end of the question.
Just for fun, run that program again and pretend you’re somebody else.…
When the computer asks for your name, if you say something weird, the computer will give you a weird reply.…
This program prints a letter, admitting you to the college of your choice:
When the computer sees the INPUT line, the computer asks “What college would you like to enter?” and waits for you to answer. Your answer will be called c$. If you’d like to be admitted to Harvard, you’ll be pleased.…
You can choose any college you wish:
That program consists of three parts:
1. The computer begins by asking you a question (“What college would you like to enter?”). The computer’s question is called the prompt, because it prompts you to answer.
2. Your answer (the college’s name) is called your input, because it’s information that you’re putting into the computer.
3. The computer’s reply (the admission letter) is called the computer’s output, because it’s the final answer that the computer puts out.
INPUT versus PRINT
The word INPUT is the opposite of the word PRINT.
The word PRINT makes the computer print information out. The word INPUT makes the computer take information in.
What the computer prints out is called the output. What the computer takes in is called your input.
Input and Output are collectively called I/O, so the INPUT and PRINT statements are called I/O statements.
Once upon a time
Let’s make the computer write a story, by filling in the blanks:
To write the story, the computer must ask for your name, your friend’s name, and a verb. To make the computer ask, your program must say INPUT:
Then make the computer print the story:
Here’s a sample run:
Here’s another run:
Try it: put in your own name, the name of your friend, and something you’d like to do to your friend.
The following program prints a certificate saying you won a contest. Since the program contains many variables, it uses long variable names to help you remember which variable is which:
Here’s a sample run:
If you’re a nasty bill collector, you’ll love this program:
Can you figure out what that program does?
This program makes the computer predict your future:
Here’s a sample run:
Suppose you’re selling tickets to a play. Each ticket costs $2.79. (You decided $2.79 would be a nifty price, because the cast has 279 people.) This program finds the price of multiple tickets:
This program tells you how much the “energy crisis” costs you, when you drive your car:
Here’s a sample run:
This program converts feet to inches:
Here’s a sample run:
Trying to convert to the metric system? This program converts inches to centimeters:
Nice day today, isn’t it? This program converts the temperature from Celsius to Fahrenheit:
Here’s a sample run:
See, you can write the Guide yourself! Just hunt through any old math or science book, find any old formula (such as f = c * 1.8 + 32), and turn it into a program.
Here’s how to restrict the computer, so it performs certain lines only under certain conditions.…
Let’s write a program so that if the human is less than 18 years old, the computer will say:
Here’s the program:
Line 2 makes the computer ask “How old are you” and wait for the human to type an age. Since the symbol for “less than” is “<”, the bottom line says: if the age is less than 18, then print “You are still a minor”.
Go ahead! Run that program! The computer begins the conversation by asking:
Try saying you’re 12 years old, by typing a 12, so the screen looks like this:
When you finish typing the 12 and press the ENTER key at the end of it, the computer will reply:
Try running that program again, but this time try saying you’re 50 years old instead of 12, so the screen looks like this:
When you finish typing the 50 and press the ENTER key at the end of it, the computer will not say “You are still a minor”. Instead, the computer will say nothing — since we didn’t teach the computer how to respond to adults yet!
In that program, the most important line says:
That line contains the words IF and THEN. Whenever you say IF, you must also say THEN. Do not put a comma before THEN. What comes between IF and THEN is called the condition; in that example, the condition is “age < 18”. If the condition is true (if age is really less than 18), the computer does the action, which comes after the word THEN and is:
Let’s teach the computer how to respond to adults.
Here’s how to program the computer so that if the age is less than 18, the computer will say “You are still a minor”, but if the age is not less than 18 the computer will say “You are an adult” instead:
In programs, the word “ELSE” means “otherwise”. That program’s bottom line means: if the age is less than 18, then print “You are still a minor”; otherwise (if the age is not less than 18), print “You are an adult”. So the computer will print “You are still a minor” or else print “You are an adult”, depending on whether the age is less than 18.
Try running that program! If you say you’re 50 years old, so the screen looks like this —
the computer will reply by saying:
If the age is less than 18, here’s how to make the computer print “You are still a minor” and also print “Ah, the joys of youth”:
Here’s a more sophisticated way to say the same thing:
That sophisticated way (in which you type 4 short lines instead of a single long line) is called a multi-line IF (or a block IF).
In a multi-line IF:
The top line must say IF and THEN (with nothing after THEN).
The middle lines should be indented; they’re called the block and typically say PRINT.
The bottom line must say END IF.
In the middle of a multi-line IF, you can say ELSE:
That means: if the age is less than 18, then print “You are still a minor” and “Ah, the joys of youth”; otherwise (if age not under 18) print “You are an adult” and “We can have adult fun”.
Let’s say this:
If age is under 18, print “You’re a minor”.
If age is not under 18 but is under 100, print “You’re a typical adult”.
If age is not under 100 but is under 125, print “You’re a centenarian”.
If age is not under 125, print “You’re a liar”.
One word In QBASIC, “ELSEIF” is one word. Type “ELSEIF”, not “ELSE IF”. If you accidentally type “ELSE IF”, the computer will gripe.
Let’s turn your computer into a therapist!
To make the computer ask the patient, “How are you?”, begin the program like this:
Make the computer continue the conversation by responding as follows:
If the patient says “fine”, print “That’s good!”
If the patient says “lousy” instead, print “Too bad!”
If the patient says anything else instead, print “I feel the same way!”
To accomplish all that, you can use a multi-line IF:
Instead of typing that multi-line IF, you can type this SELECT statement instead, which is briefer and simpler:
Like a multi-line IF, a SELECT statement consumes several lines. The top line of that SELECT statement tells the computer to analyze a$ and SELECT one of the CASEs from the list underneath. That list is indented and says:
In the case where a$ is “fine”, print “That’s good!”
In the case where a$ is “lousy”, print “Too bad!”
In the case where a$ is anything else, print “I feel the same way!”
The bottom line of every SELECT statement must say END SELECT.
Complete program Here’s a complete program:
Line 2 makes the computer ask the patient, “How are you?” The next several lines are the SELECT statement, which makes the computer analyze the patient’s answer and print “That’s good!” or “Too bad!” or else “I feel the same way!”
Regardless of what the patient and computer said, that program’s bottom line always makes the computer end the conversation by printing:
In that program, try changing the strings to make the computer print smarter remarks, become a better therapist, and charge even more money.
Error trap This program makes the computer discuss human sexuality:
The second line (which is numbered 10) makes the computer ask, “Are you male or female?”
The remaining lines are a SELECT statement that analyzes the human’s response. If the human claims to be “male”, the computer prints “So is Frankenstein!” If the human says “female” instead, the computer prints “So is Mary Poppins!” If the human says anything else (such as “not sure” or “super-male” or “macho” or “none of your business”), the computer does the CASE ELSE, which makes the computer say “Please say male or female!” and then go back to line 10, which makes the computer ask again, “Are you male or female?”
In that program, the CASE ELSE is called an error handler (or error-handling routine or error trap), since its only purpose is to handle human error (a human who says neither “male” nor “female”). Notice that the error handler begins by printing a gripe message (“Please say male or female!”) and then lets the human try again (GOTO 10).
In QBASIC, the GOTO statements are used rarely: they’re used mainly in error handlers, to let the human try again.
Let’s extend that program’s conversation. If the human says “female”, let’s make the computer say “So is Mary Poppins!”, then ask “Do you like her?”, then continue the conversation as follows:
If human says “yes”, make the computer say “I like her too. She is my mother.”
If human says “no”, make computer say “I hate her too. She owes me a dime.”
If human says neither “yes” nor “no”, make the computer handle that error.
To accomplish all that, insert the shaded lines into the program:
Weird programs The computer’s abilities are limited only by your own imagination — and your weirdness. Here are some weird programs from weird minds.…
Like a human, the computer wants to meet new friends. This program makes the computer show its true feelings:
When you run that program, the computer asks “Are you my friend?” If you say “yes”, the computer says “That’s swell.” If you say “no”, the computer says “Go jump in a lake.”
The most inventive programmers are kids. This program was written by a girl in the sixth grade:
When you run that program, the computer asks to watch your TV. If you say “yes”, the computer promises to come to your house at 5. If you refuse, the computer insults your feet.
Another sixth-grade girl wrote this program, to test your honesty:
When you run that program, lines 2-4 print nonsense. Then the computer asks whether you understand that stuff. If you’re honest and answer “no”, the computer will apologize. But if you pretend that you understand the nonsense and answer “yes”, the computer will print more nonsense, challenge you to translate it, wait for you to fake a translation, and then scold you for lying.
Fancy IF conditions
A Daddy wrote a program for his 5-year-old son, John. When John runs the program and types his name, the computer asks “What’s 2 and 2?” If John answers 4, the computer says “No, 2 and 2 is 22”. If he runs the program again and answers 22, the computer says “No, 2 and 2 is 4”. No matter how many times he runs the program and how he answers the question, the computer says he’s wrong. But when Daddy runs the program, the computer replies, “Yes, Daddy is always right”.
Here’s how Daddy programmed the computer:
Different relations You can make the IF clause very fancy:
IF b$ = "male"If b$ is “male”
IF b = 4 If b is 4
IF b < 4 If b is less than 4
IF b > 4 If b is greater than 4
IF b <= 4 If b is less than or equal to 4
IF b >= 4 If b is greater than or equal to 4
IF b <> 4 If b is not 4
IF b$ < "male"If b$ is a word that comes before “male” in the dictionary
IF b$ > "male"If b$ is a word that comes after “male” in the dictionary
In the IF statement, the symbols =, <, >, <=, >=, and <> are called relations.
When writing a relation, mathematicians and computerists habitually put the equal sign last:
When you press the ENTER key at the end of the line, the computer will automatically put your equal signs last: the computer will turn any “=<” into “<=”; it will turn any “=>” into “<=”.
To say “not equal to”, say “less than or greater than”, like this: <>.
OR The computer understands the word OR. For example, here’s how to say, “If x is either 7 or 8, print the word wonderful”:
That example is composed of two conditions: the first condition is “x = 7”; the second condition is “x = 8”. Those two conditions combine, to form “x = 7 OR x = 8”, which is called a compound condition.
If you use the word OR, put it between two conditions.
AND The computer understands the word AND. Here’s how to say, “If p is more than 5 and less than 10, print tuna fish”:
Here’s how to say, “If s is at least 60 and less than 65, print you almost failed”:
Here’s how to say, “If n is a number from 1 to 10, print that’s good”:
Can a computer be President?
To become President of the United States, you need 4 basic skills:
So altogether, to become President you need to be a good talker and listener and decision maker and also have the patience to put up with monotonous repetition.
Those are exactly the four qualities the computer has!
The word PRINT turns the computer into a good speech-maker. By using the word PRINT, you can make the computer write whatever speech you wish.
The word INPUT turns the computer into a good listener. By using the word INPUT, you can make the computer ask humans lots of questions, to find out who the humans are and what they want.
The word IF turns the computer into a decision maker. The computer can analyze the IF condition, determine whether that condition is true, and act accordingly.
Finally, the word GOTO enables the computer to perform loops, which the computer will repeat patiently.
So by using the words PRINT, INPUT, IF, and GOTO, you can make the computer imitate any intellectual human activity. Those four magic words — PRINT, INPUT, IF, and GOTO — are the only concepts you need, to write whatever program you wish!
Yes, you can make the computer imitate the President of the United States, do your company’s payroll, compose a beautiful poem, play a perfect game of chess, contemplate the meaning of life, act as if it’s falling in love, or do whatever other intellectual or emotional task you wish, by using those four magic words. The only question is: how? The Secret Guide to Computers teaches you how, by showing you many examples of programs that do those remarkable things.
What programmers believe Yes, we programmers believe that all of life can be explained and programmed. We believe all of life can be reduced to just those four concepts: PRINT, INPUT, IF, and GOTO. Programming is the ultimate act of scientific reductionism: programmers reduce all of life scientifically to just four concepts.
The words that the computer understands are called keywords. The four essential keywords are PRINT, INPUT, IF, and GOTO.
The computer also understands extra keywords, such as CLS, LPRINT, WIDTH, SYSTEM, SLEEP, DO (and LOOP), END, SELECT (and CASE), and words used in IF statements (such as THEN, ELSE, ELSEIF, OR, AND). Those extra keywords aren’t necessary: if they hadn’t been invented, you could still write programs without them. But they make programming easier.
A BASIC programmer is a person who translates an ordinary English sentence (such as “act like the President” or “do the payroll”) into a series of BASIC statements, using keywords such as PRINT, INPUT, IF, GOTO, CLS, etc.
The mysteries of life Let’s dig deeper into the mysteries of PRINT, INPUT, IF, GOTO, and the extra keywords. The deeper we dig, the more you’ll wonder: are you just a computer, made of flesh instead of wires? Can everything that you do be explained in terms of PRINT, INPUT, IF, and GOTO?
By the time you finish The Secret Guide to Computers, you’ll know!
Exiting a DO loop
This program plays a guessing game, where the human tries to guess the computer’s favorite color, which is pink:
The INPUT line asks the human to guess the computer’s favorite color; the guess is called guess$.
If the guess is “pink”, the computer prints:
But if the guess is not “pink”, the computer will instead print “No, that’s not my favorite color” and then GO back TO line 10, which asks the human again to try guessing the computer’s favorite color.
END Here’s how to write that program without saying GOTO:
That new version of the program contains a DO loop. That loop makes the computer do this repeatedly: ask “What’s my favorite color?” and then PRINT “No, that’s not my favorite color.”
The only way to stop the loop is to guess “pink”, which makes the computer print “Congratulations!” and END.
EXIT DO Here’s another way to write that program without saying GOTO:
That program’s DO loop makes the computer do this repeatedly: ask “What’s my favorite color?” and then PRINT “No, that’s not my favorite color.”
The only way to stop the loop is to guess “pink”, which makes the computer EXIT from the DO loop; then the computer proceeds to the line underneath the DO loop. That line prints:
LOOP UNTIL Here’s another way to program the guessing game:
That program’s DO loop makes the computer do this repeatedly: say “You haven’t guessed my favorite color yet!” and then ask “What’s my favorite color?”
The LOOP line makes the computer repeat the indented lines again and again, UNTIL the guess is “pink”. When the guess is “pink”, the computer proceeds to the line underneath the LOOP and prints “Congratulations!”.
The LOOP UNTIL’s condition (guess$ = “pink”) is called the loop’s goal. The computer does the loop repeatedly, until the loop’s goal is achieved. Here’s how:
The computer does the indented lines, then checks whether the goal is achieved yet. If the goal is not achieved yet, the computer does the indented lines again, then checks again whether the goal is achieved. The computer does the loop again and again, until the goal is achieved. Then the computer, proud at achieving the goal, does the program’s finale, which consists of any lines under the LOOP UNTIL line.
is just a briefer way of saying this pair of lines:
Let’s make the computer print every number from 1 to 20, like this:
Here’s the program:
The second line (FOR x = 1 TO 20) says that x will be every number from 1 to 20; so x will be 1, then 2, then 3, etc. The line underneath, which is indented, says what to do about each x; it says to PRINT each x.
Whenever you write a program that contains the word FOR, you must say NEXT; so the bottom line says NEXT.
The indented line, which is between the FOR line and the NEXT line, is the line that the computer will do repeatedly; so the computer will repeatedly PRINT x. The first time the computer prints x, the x will be 1, so the computer will print:
The next time the computer prints x, the x will be 2, so the computer will print:
The computer will print every number from 1 up to 20.
When men meet women
Let’s make the computer print these lyrics:
To do that, type these lines —
and make x be every number from 2 up to 5:
At the top of the program, say CLS. At the end of the song, print the closing couplet:
That program makes the computer print the entire song.
Here’s an analysis:
Since the computer does the indented lines repeatedly, those lines form a loop. Here’s the general rule: the statements between FOR and NEXT form a loop. The computer goes round and round the loop, for x=2, x=3, x=4, and x=5. Altogether, it goes around the loop 4 times, which is a finite number. Therefore, the loop is finite.
If you don’t like the letter x, choose a different letter. For example, you can choose the letter i:
When using the word FOR, most programmers prefer the letter i; most programmers say “FOR i” instead of “FOR x”. Saying “FOR i” is an “old tradition”. Following that tradition, the rest of this book says “FOR i” (instead of “FOR x”), except in situations where some other letter feels more natural.
Print the squares
To find the square of a number, multiply the number by itself. The square of 3 is “3 times 3”, which is 9. The square of 4 is “4 times 4”, which is 16.
Let’s make the computer print the square of 3, 4, 5, etc., up to 20, like this:
To do that, type this line —
and make i be every number from 3 up to 20, like this:
Count how many copies
This program, which you saw before, prints “love” on every line of your screen:
That program prints “love” again and again, until you abort the program by pressing Ctrl with PAUSE/BREAK.
But what if you want to print “love” just 20 times? This program prints “love” just 20 times:
As you can see, FOR...NEXT resembles DO...LOOP but is smarter: while doing FOR...NEXT, the computer counts!
Poem This program, which you saw before, prints many copies of a poem:
It prints the copies onto paper. It prints each copy on a separate sheet of printer. It keeps printing until you abort the program — or the printer runs out of paper.
Here’s a smarter program, which counts the number of copies printed and stops when exactly 4 copies have been printed:
It’s the same as the DO...LOOP program, except that it counts (by saying “FOR i = 1 TO 4” instead of “DO”) and has a different bottom line (NEXT instead of LOOP).
Here’s an even smarter program, which asks how many copies you want:
When you run that program, the computer asks:
If you answer 5, then the n becomes 5 and so the computer prints 5 copies of the poem. If you answer 7 instead, the computer prints 7 copies. Print as many copies as you like!
That program illustrates this rule:
To make the FOR...NEXT loop flexible,
say “FOR i = 1 TO n” and let the human INPUT the n.
Count to midnight
The computer will print:
Semicolon Let’s put a semicolon at the end of the indented line:
The semicolon makes the computer print each item on the same line, like this:
If you want the computer to press the ENTER key before “midnight”, insert a PRINT line:
That extra PRINT line makes the computer press the ENTER key just before “midnight”, so the computer will print “midnight” on a separate line, like this:
Nested loops Let’s make the computer count to midnight 3 times, like this:
To do that, put the entire program between the words FOR and NEXT:
That version contains a loop inside a loop: the loop that says “FOR i” is inside the loop that says “FOR j”. The j loop is called the outer loop; the i loop is called the inner loop. The inner loop’s variable must differ from the outer loop’s. Since we called the inner loop’s variable “i”, the outer loop’s variable must not be called “i”; so I picked the letter j instead.
Programmers often think of the outer loop as a bird’s nest, and the inner loop as an egg inside the nest. So programmers say the inner loop is nested in the outer loop; the inner loop is a nested loop.
Earlier, we programmed a game where the human tries to guess the computer’s favorite color, pink. Here’s a fancier version of the game, in which the human gets just 5 guesses:
Line 2 warns the human that just 5 guesses are allowed. The FOR line makes the computer count from 1 to 5; to begin, i is 1. The INPUT line asks the human to guess the computer’s favorite color; the guess is called guess$.
If the guess is “pink”, the computer jumps down to the line numbered 10, prints “Congratulations!”, and tells how many guesses the human took. But if the guess is not “pink”, the computer will print “No, that’s not my favorite color” and go on to the NEXT guess.
If the human guesses 5 times without success, the computer proceeds to the line that prints “Sorry… You lose.”
For example, if the human’s third guess is “pink”, the computer prints:
If the human’s very first guess is “pink”, the computer prints:
Saying “1 guesses” is bad grammar but understandable.
That program contains a FOR...NEXT loop. The FOR line says the loop will normally be done five times. The line below the loop (which says to PRINT “Sorry”) is the loop’s normal exit. But if the human happens to input “pink”, the computer jumps out of the loop early, to line 10, which is the loop’s abnormal exit.
The FOR statement can be varied:
FOR i = 5 TO 17 STEP .1 The i will go from 5 to 17, counting by tenths.
So i will be 5, then 5.1, then 5.2, etc., up to 17.
FOR i = 5 TO 17 STEP 3 The i will be every third number from 5 to 17.
So i will be 5, then 8, then 11, then 14, then 17.
FOR i = 17 TO 5 STEP -3 The i will be every third number from 17 down to 5.
So i will be 17, then 14, then 11, then 8, then 5.
To count down, you must use the word STEP. To count from 17 down to 5, give this instruction:
This program prints a rocket countdown:
The computer will print:
This statement is tricky:
It says to start i at 5, and keep adding 3 until it gets past 16. So i will be 5, then 8, then 11, then 14. The i won’t be 17, since 17 is past 16. The first value of i is 5; the last value is 14.
In the statement FOR i = 5 TO 16 STEP 3, the first value or initial value of i is 5, the limit value is 16, and the step size or increment is 3. The i is called the counter or index or loop-control variable. Although the limit value is 16, the last value or terminal value is 14.
Programmers usually say “FOR i”, instead of “FOR x”, because the letter i reminds them of the word index.
Let’s make the computer print this message:
That message concerns this list of food: meat, potatoes, lettuce, tomatoes, honey, cheese, onions, peas. That list doesn’t change: the computer continues to love those foods throughout the entire program.
A list that doesn’t change is called DATA. So in the message about food, the DATA is meat, potatoes, lettuce, tomatoes, honey, cheese, onions, peas.
Whenever a problem involves DATA, put the DATA at the top of the program, just under the CLS, like this:
You must tell the computer to READ the DATA:
That READ line makes the computer read the first datum (“meat”) and call it a$. So a$ is “meat”.
Since a$ is “meat”, this shaded line makes the computer print “I love meat”:
Hooray! We made the computer handle the first datum correctly: we made the computer print “I love meat”.
To make the computer handle the rest of the data (potatoes, lettuce, etc.), tell the computer to READ and PRINT the rest of the data, by putting the READ and PRINT lines in a loop. Since we want the computer to READ and PRINT all 8 data items (meat, potatoes, lettuce, tomatoes, honey, cheese, onions, peas), put the READ and PRINT lines in a loop that gets done 8 times, by making the loop say “FOR i = 1 TO 8”:
Since that loop’s main purpose is to READ the data, it’s called a READ loop.
When writing that program, make sure the FOR line’s last number (8) is the number of data items. If the FOR line accidentally says 7 instead of 8, the computer won’t read or print the 8th data item. If the FOR line accidentally says 9 instead of 8, the computer will try to read a 9th data item, realize that no 9th data item exists, and gripe by saying:
Then press ENTER.
Let’s make the computer end by printing “Those are the foods I love”, like this:
To make the computer print that ending, put a PRINT line at the end of the program:
When writing that program, we had to count the DATA items and put that number (8) at the end of the FOR line.
Here’s a better way to write the program, so you don’t have to count the DATA items:
The third line (DATA end) is called the end mark, since it marks the end of the DATA. The READ line means:
READ a$ from the DATA;
but if a$ is the “end” of the DATA, then EXIT from the DO loop.
When the computer exits from the DO loop, the computer prints “Those are the foods I love”. So altogether, the entire program makes the computer print:
The routine that says:
is called the end routine, because the computer does that routine when it reaches the end of the DATA.
Henry the Eighth Let’s make the computer print this nursery rhyme:
If you own a jump rope, have fun: try to recite that poem while skipping rope!
This program makes the computer recite the poem:
Since the data’s too long to fit on a single line, I’ve put part of the data in line 2 and the rest in line 3. Each line of data must begin with the word DATA. In each line, put commas between the items. Do not put a comma at the end of the line.
The program resembles the previous one. The new line (IF a$ = “to wed” THEN PRINT) makes the computer leave a blank line underneath “to wed”, to mark the bottom of the first verse.
Pairs of data
Let’s throw a party! To make the party yummy, let’s ask each guest to bring a kind of food that resembles the guest’s name. For example, let’s have Sal bring salad, Russ bring Russian dressing, Sue bring soup, Tom bring turkey, Winnie bring wine, Kay bring cake, and Al bring Alka-Seltzer.
Let’s send all those people invitations, in this form:
Here’s the program:
The DATA comes in pairs. For example, the first pair consists of “Sal” and “salad”; the next pair consists of “Russ” and “Russian dressing”. Since the DATA comes in pairs, you must make the end mark also be a pair (DATA end,end).
Since the DATA comes in pairs, the READ line says to READ a pair of data (person$ and food$). The first time that the computer encounters the READ line, person$ is “Sal”; food$ is “salad”. Then the LPRINT lines print this message onto paper:
The LPRINT CHR$(12) makes the computer eject the paper from the printer.
Then the computer comes to the word LOOP, which sends the computer back to the word DO, which sends the computer to the READ line again, which reads the next pair of DATA, so person$ becomes “Russ” and food$ becomes “Russian dressing”. The LPRINT lines print onto paper:
The computer prints similar letters to all the people.
After all people have been handled, the READ statement comes to the end mark (DATA end,end), so that person$ and food$ both become “end”. Since person$ is “end”, the IF statement makes the computer EXIT DO, so the computer prints this message onto the screen:
In that program, you need two ends to mark the data’s ending, because the READ statment says to read two strings (person$ and food$).
Debts Suppose these people owe you things:
Mike a dime
Sue 2 golf balls
Harry a steak dinner at Mario’s
Mommy a kiss
Let’s remind those people of their debt, by writing them letters, in this form:
To start writing the program, begin by saying CLS and then feed the computer the DATA. The final program is the same as the previous program, except for the part I’ve shaded:
Triplets of data
Suppose you’re running a diet clinic and get these results:
Joe 273 pounds 219 pounds
Mary 412 pounds 371 pounds
Bill 241 pounds 173 pounds
Sam 309 pounds 198 pounds
This program makes the computer print a nice report:
Line 2 contains the DATA, which comes in triplets. The first triplet consists of Joe, 273, and 219. Each triplet includes a string (such as Joe) and two numbers (such as 273 and 219), so line 3’s end mark also includes a string and two numbers: it’s the word “end” and two zeros. (If you hate zeros, you can use other numbers instead; but most programmers prefer zeros.)
The READ line says to read a triplet: a string (person$) and two numbers (weight.before and weight.after). The first time the computer comes to the READ statement, the computer makes person$ be “Joe”, weight.before be 273, and weight.after be 219. The PRINT lines print this:
Examine this program:
The first READ makes the computer read the first datum (love), so the first PRINT makes the computer print:
The next READ would normally make the computer read the next datum (death); but the RESTORE 10 tells the READ to skip ahead to DATA line 10, so the READ line reads “chocolate” instead. The entire program prints:
So saying “RESTORE 10” makes the next READ skip ahead to DATA line 10. If you write a new program, saying “RESTORE 20” makes the next READ skip ahead to DATA line 20. Saying just “RESTORE” makes the next READ skip back to the beginning of the first DATA line.
Continents This program prints the names of the continents:
That program makes the computer print this message:
Let’s make the computer print that message twice, so the computer prints:
To do that, put the program in a loop saying “FOR i = 1 TO 2”, like this:
After that program says to PRINT “Those are the continents”, the program says to PRINT a blank line and then RESTORE. The word RESTORE makes the READ go back to the beginning of the DATA, so the computer can READ and PRINT the DATA a second time without saying “Out of DATA”.
Let’s make the computer translate colors into French. For example, if the human says “red”, we’ll make the computer say the French equivalent, which is:
Let’s make the computer begin by asking “Which color interests you?”, then wait for the human to type a color (such as “red”), then reply:
The program begins simply:
Next, we must make the computer translate the requested color into French. To do so, feed the computer this English-French dictionary:
That dictionary becomes the data:
The data comes in pairs; each pair consists of an English word (such as “white”) followed by its French equivalent (“blanc”). To make the computer read a pair, say:
To let the computer look at all the pairs, put that READ statement in a DO loop. Here’s the complete program:
Since the READ line is in a DO loop, the computer does the READ line repeatedly. So the computer keeps READing pairs of DATA, until the computer find the pair of DATA that the human requested. For example, if the human requested “red”, the computer keeps READing pairs of DATA until it finds a pair whose English word matches the requested word (“red”). When the computer finds that match, the english$ is equal to the request$, so the IF line makes the computer EXIT DO and PRINT:
So altogether, when you run the program the chat can look like this:
Here’s another sample run:
The computer says “Out of DATA” because it can’t find “pink” in the DATA.
Avoid “Out of DATA” Instead of saying “Out of DATA”, let’s make the computer say “I wasn’t taught that color”. To do that, put an end mark at the end of the DATA; and when the computer reaches the end mark, make the computer say “I wasn’t taught that color”:
In that program, the DO loop’s purpose is to search through the DATA, to find DATA that matches the INPUT. Since the DO loop’s purpose is to search, it’s called a search loop.
The typical search loop has these characteristics:
It starts with DO and ends with LOOP.
It says to READ a pair of data.
It includes an error trap saying what to do IF you reach the “end” of the data because no match found.
It says that IF you find a match (english$ = request$) THEN EXIT the DO loop.
Below the DO loop, say what to PRINT when the match is found.
Above the DO loop, put the DATA and tell the human to INPUT a search request.
Auto rerun At the end of the program, let’s make the computer automatically rerun the program and translate another color.
To do that, make the bottom of the program say GO back TO the INPUT line:
The word RESTORE, which is above the search loop, makes sure that the computer’s search through the DATA always starts at the DATA’s beginning.
Press Q to quit That program repeatedly asks “Which color interests you” until the human aborts the program (by pressing Ctrl with PAUSE/BREAK). But what if the human’s a beginner who hasn’t learned how to abort?
Let’s permit the human to stop the program more easily by pressing just the Q key to quit:
END, STOP, or SYSTEM That program’s shaded line ends by saying END. Instead of saying END, try saying STOP or SYSTEM.
While the program is running, here’s what the computer does when it encounters END, STOP, or SYSTEM:
STOP makes the program stop immediately. The screen becomes blue and shows the program’s lines.
END makes the computer say “Press any key to continue” and wait for the human to press a key (such as F4 or ENTER). When the human finally presses a key, the screen becomes blue and shows the program’s lines.
SYSTEM usually has the same effect as END. But if you saved the program onto the hard disk (using a name such as “french.bas”) and then ran the program from DOS (by saying “C:\>qbasic /run french”), SYSTEM makes the program stop immediately and makes the screen show “C:\>”.
Here are some hints to help you master programming.
Variables & constants
A numeric constant is a simple number, such as:
Another example of a numeric constant is 1.3E5, which means, “take 1.3, and move its decimal point 5 places to the right”.
A numeric constant does not contain any arithmetic. For example, since 7+1 contains arithmetic (+), it’s not a numeric constant. 8 is a numeric constant, even though 7+1 isn’t.
A string constant is a simple string, in quotation marks:
A constant is a numeric constant or a string constant:
A variable is something that stands for something else. If it stands for a string, it’s called a string variable and ends with a dollar sign, like this:
If the variable stands for a number, it’s called a numeric variable and lacks a dollar sign, like this:
So all these are variables:
Expressions A numeric expression is a numeric constant (such as 8) or a numeric variable (such as b) or a combination of them, such as 8+z, or 8*a, or z*a, or 8*2, or 7+1, or even z*a-(7+z)/8+1.3E5*(-524.6+b). A string expression is a string constant (such as “I love you”) or a string variable (such as a$) or a combination. An expression is a numeric expression or a string expression.
Statements At the end of a GOTO statement, the line number must be a numeric constant.
Right: GOTO 100 (100 is a numeric constant.)
Wrong: GOTO n (n is not a numeric constant.)
The INPUT statement’s prompt must be a string constant.
Right: INPUT "What is your name; n$ (“What is your name” is a constant.)
Wrong: INPUT q$; n$ (q$ is not a constant.)
In a DATA statement, you must have constants.
Right: DATA 8, 1.3E5 (8 and 1.3E5 are constants.)
Wrong: DATA 7+1, 1.3E5 (7+1 is not a constant.)
In the DATA statement, if the constant is a string, you can omit the quotation marks (unless the string contains a comma or a colon).
Right: DATA "Joe","Mary"
Also right: DATA Joe,Mary
Here are the forms of popular BASIC statements:
If you write and run your own program, it probably won’t work.
Your first reaction will be to blame the computer. Don’t!
The probability is 99.99% that the fault is yours. Your program contains an error. An error is called a bug. Your next task is to debug the program, which means get the bugs out.
Bugs are common; top-notch programmers make errors all the time. If you write a program that works perfectly on the first run and doesn’t need debugging, it’s called a gold-star program and means you should have tried writing a harder one instead!
It’s easy to write a program that’s nearly correct but hard to find the little bug fouling it up. Most time you spend at the computer will be devoted to debugging.
Debugging can be fun. Hunting for the bug is like going on a treasure hunt – or solving a murder mystery. Pretend you’re Sherlock Holmes. Your mission: to find the bug and squish it! When you squish it, have fun: yell out, “Squish!”
How can you tell when a roomful of programmers is happy? Answer: when you hear continual cries of “Squish!”
To find a bug, use three techniques:
Inspect the program.
Trace the computer’s thinking.
Shorten the program.
Here are the details.…
Inspect the program Take a good, hard look at the program. If you stare hard enough, maybe you’ll see the bug.
Usually, the bug will turn out to be just a typing error, a typo. For example.…
Maybe you typed the letter O instead of zero? Zero instead of the letter O?
Typed I instead of 1? Typed 1 instead of I?
Pressed the SHIFT key when you weren’t supposed to? Forgot to press it?
Typed an extra letter? Omitted a letter?
Typed a line you thought you hadn’t? Omitted a line?
You must put quotation marks around each string, and a dollar sign after each string variable:
Right: a$ = "jerk"
Wrong: a$ = jerk
Wrong: a = "jerk"
Here are three reasons why the computer might print too much:
1. You forgot to insert the word END or EXIT DO into your program.
2. Into a DO loop or FOR loop, you inserted a PRINT line that should be outside the loop.
3. When you started typing the program, you forgot to choose New from the file menu; so the computer is including part of the previous program.
Trace the computer’s thinking If you’ve inspected the program thoroughly and still haven’t found the bug, the next step is to trace the computer’s thinking. Pretend you’re the computer. Do what your program says. Do you find yourself printing the same wrong answers the computer printed? If so, why?
To help your analysis, make the computer print everything it’s thinking while it’s running your program. For example, suppose your program uses the variables b, c, and x$. Insert lines such as these into your program:
Then run the program. Those extra lines tell you what the computer is thinking about b, c, and x$ and also tell you how many times the computer reached lines 10 and 20. For example, if the computer prints what you expect in line 10 but prints strange values in line 20 (or doesn’t even get to line 20), you know the bug occurs after line 10 but before line 20.
Here’s a good strategy. Halfway down your program, insert a line that says to print all the values. Then run your program. If the line you inserted prints the correct values, you know the bug lies underneath that line; but if the line prints wrong values (or if the computer never reaches that line), you know the bug lies above that line. In either case, you know which half of your program contains the bug. In that half of the program, insert more lines, until you finally zero in on the line that contains the bug.
Shorten the program When all else fails, shorten the program.
Hunting for a bug in a program is like hunting for a needle in a haystack: the job is easier if the haystack is smaller. So make your program shorter: delete the last half of your program. Then run the shortened version. That way, you’ll find out whether the first half of your program is working the way it’s supposed to. When you’ve perfected the first half of your program, tack the second half back on.
Does your program contain a statement whose meaning you’re not completely sure of? Check the meaning by reading a book or asking a friend; or write a tiny experimental program that contains the statement, and see what happens when you run it.
Hint: before you shorten your program (or write tiny experimental ones), save the original version (by choosing Save from the file menu), even though it contains a bug. After you’ve played with the shorter versions, retrieve the original (by choosing Open from the file menu) and fix it.
To write a long, correct program easily, write a short program first and debug it, then add a few more lines and debug them, add a few more lines and debug them, etc. So start with a small program, perfect it, then gradually add perfected extras so you gradually build a perfected masterpiece. If you try to compose a long program all at once – instead of building it from perfected pieces – you’ll have nothing more than a mastermess – full of bugs.
Moral: to build a large masterpiece, start with a small masterpiece. To build a program so big that it’s a skyscraper, begin by laying a good foundation; double-check the foundation before you start adding the program’s walls and roof.
If the computer can’t obey your command, the computer will print an error message. The following error message are the most common.…
Syntax errors If you say “prind” instead of “print”, the computer will say:
That means the computer hasn’t the faintest idea of what you’re talking about!
If the computer says you have a syntax error, it’s usually because you spelled a word wrong, or forgot a word, or used a word the computer doesn’t understand. It can also result from wrong punctuation: check your commas, semicolons, and colons. It can also mean your DATA statement contains a string but your READ statement says to read a number instead; to fix that problem, change the READ statement by putting a dollar sign at the end of the variable’s name.
If you try to say PRINT 5 + 2 but forget to type the 2, the computer will say:
If you type a left parenthesis but forget to type the right parenthesis that matches it, the computer will say:
If you accidentally type extra characters (or an unintelligible word) at the end of the line, the computer will say:
Numeric errors If the answer to a calculation is a bigger number than the computer can handle, the computer will say:
To help the computer handle bigger numbers, remember to put a decimal point in any problem whose answer might be bigger than 32 thousand.
If you try to divide by zero, the computer will say:
If you feed the computer a number that’s inappropriate, the computer will say:
That’s what the computer will say if you try saying WIDTH 50 instead of WIDTH 40, or you try saying LPRINT CHR$(1200) instead of LPRINT CHR$(12).
Printer errors If your printer runs out of paper, the computer will say:
If your printer isn’t communicating well with the computer, the computer will say:
That means printer’s cable to the computer is unplugged or loose or defective or plugged into the wrong socket, or the printer is turned off, or the printer is off-line (because you pressed a button that turned off the printer’s ON LINE light), or the paper is jammed, or there’s no more ink left, or the printer broke.
Logic errors Some commands come in pairs.
The words DO and LOOP form a pair. If you say DO but no line says LOOP, the computer will gripe by saying:
If you say LOOP but no line says DO, the computer will say:
The words FOR and NEXT form another pair. If part of the pair is missing, the computer will say –
If a line’s first word is SELECT, you’re supposed to have a line below saying END SELECT. If you say SELECT but no line says END SELECT, the computer will say:
If you say END SELECT but no line’s first word is SELECT, the computer will say:
Between the SELECT and END SELECT lines, you’re supposed to have several lines saying CASE. If you say CASE but no line’s first word is SELECT, the computer will say:
If you say GOTO 10, the computer tries to find a line numbered 10. If you say GOTO joe, the computer tries to find a line named joe. If there’s no line numbered 10 or no line named joe, the computer will say:
Here are other messages about unmatched pairs, involving IF:
If you say READ but the computer can’t find any more DATA to read (because the computer has read all the DATA already), the computer will say:
The computer handles two major types of info: numbers and strings. If you feed the computer the wrong type of information – if you feed it a number when you should have fed it a string, or you feed it a string when you should have fed it a number – the computer will say:
When you feed the computer a string, you must put the string in quotation marks, and put a dollar sign after the string’s variable. If you forget to type the string’s quotation marks or dollar sign, the computer won’t realize it’s a string; the computer will think you’re trying to type a number instead; and if a number would be inappropriate, the computer will say “Type mismatch”. So when the computer says “Type mismatch”, it usually means you forgot a quotation mark or a dollar sign.
Magicians often say, “The hand is quicker than the eye.” The computer’s the ultimate magician: the computer can print information on the screen much faster than you can read it.
When the computer is printing faster than you can read, tap the PAUSE key. (If your keyboard is modern, that’s the last key in the top row. If your keyboard is old-fashioned, no key says PAUSE on it, so do this instead: while holding down the Ctrl key, tap the NUM LOCK key.)
Then the computer will pause, to let you read what’s on the screen.
When you’ve finished reading what’s on the screen and want the computer to stop pausing, press the ENTER key. Then the computer will continue printing rapidly, where it left off.
If your eyes are as slow as mine, you’ll need to use the PAUSE key often! You’ll want the computer to pause while you’re running a program containing many PRINT statements (or a PRINT statement in a loop).
You already learned that to run your program, you press SHIFT with F5; and while viewing the blue screen, you can peek at the black screen instead by pressing F4 (and then pressing F4 again to return to the blue screen). Here are other F keys you can press.…
F6 (immediate window) Near the bottom of QBASIC’s blue screen, you see the word “Immediate”. The area below that word is called the immediate window. The area above that word is called the program window.
Usually you type in the program window. That’s where you type your programs.
To use the immediate window, press the F6 key. That moves the cursor (blinking underline) down to the immediate window. Whatever you type afterwards will be in the immediate window.
Any command you type in the immediate window will be obeyed by the computer immediately. (The computer will not wait for you press SHIFT F5.)
For example, in the immediate window type this:
When you press the ENTER key at the end of that line, the computer obeys that line immediately; the computer immediately makes the screen turn black and prints the answer (6) near the bottom of the black screen. When you finish admiring the answer, press the F4 key to switch back to the blue screen.
The cursor will still be in the immediate window. Go ahead: type another PRINT line in the immediate window. When you press the ENTER key at the end of the line, the computer will print the answer on the black screen. Press F4 again, so you see the blue screen again.
You can use the immediate window to quickly PRINT the answers to calculations (so you can discard your calculator) and to explore advanced aspects of the PRINT command.
When you get tired of using the immediate window, press the F6 key again, which moves the cursor back up to the program window.
Try this experiment: in the program window, write a program and run it (by pressing SHIFT F5). When the program finishes running (or gets interrupted by an error), go down to the immediate window (by pressing F6) and tell the computer to PRINT the program’s variables. For example, if the program mentioned a variable called x, say this in the program window:
That makes the computer print the number that x stands for. That info will help you debug the program.
F9 (breakpoint) If you point at a line of your program (by using the arrow keys) and then press the F9 key, the line turns red. Try it! Make several lines in your program turn red.
So when pointing at a line, pressing F9 makes the line turn red; pressing F9 again makes the line turn back to blue.
Try this experiment: type a long program (containing 5 lines or more), and make two of the lines turn red. Make the red lines be in the middle of the program, instead of being the top or bottom lines.
When you tell the computer to run the program (by pressing SHIFT with F5), the computer starts running the program; but when the computer reaches a red line, it pauses at the beginning of that line and shows you the blue screen again.
While the computer pauses at the red line, do whatever you wish! For example:
You can peek at the black screen (by pressing F4 to see the black screen, then pressing F4 again to return to the blue screen).
You can use the immediate window (by pressing F6, then typing a PRINT command in the immediate window, then pressing F6 to return to the program window).
You can edit your program.
If you press F5, the computer will continue running the program: it will obey that red line and the lines underneath. If the computer comes to another red line, the computer will pause at that red line also.
Pressing F5 makes the computer continue where it left off. Pressing SHIFT with F5 makes the computer run the program from the beginning instead.
Each red line is called a breakpoint, because when the computer is running a program and encounters a red line, the computer breaks its train of thought and pauses.
If you’ve turned many lines red, here’s how to get rid of all the redness: choose “Clear All Breakpoints” from the Debug menu (by pressing Alt then D then C).
F7 (run to here) To have fun, make sure none of the lines in your program is red; then point at a line in the middle of your program (by using the arrow keys), and press F7.
The computer will temporarily turn the line red (so the line becomes a breakpoint). Then the computer will run the program up to that line. Then the computer will get rid of the red.
So if you point at a line and then press F7, the computer will run just the program’s beginning, up to that line.
Notice the contrast:
Pressing SHIFT with F5 runs the whole program.
Pressing F7 runs just the program’s beginning.
F8 (single step) Instead of telling the computer to run your entire program, you can tell the computer to run just one line at a time, as slowly as you wish. Here’s how: press the F8 key. Each time you press the F8 key, the computer will run one more line of your program. So if you press the F8 key three times, the computer will run three lines of your program.
Pressing F8 makes the computer run one more line, then show you the blue screen again. At the blue screen, do whatever you wish: you can press F4 (to peek at the black screen), or press F6 (to move to the immediate window), or edit your program, or press F8 again (to run the next line).
The first time you press F8, the computer typically runs the program’s first line; but if the computer was in the middle of running your program and was interrupted (by a red breakpoint line or a line saying STOP), pressing F8 makes the computer continue where it left off and do one more line.
Occasionally, jot a note to remind yourself what your program does and what the variables stand for. Slip the note into your program by putting an apostrophe before it:
When you run the program, the computer ignores everything that’s to the right of an apostrophe. So the computer ignores lines 1 & 2; in lines 4 & 5, the computer ignores the “because…”; in the bottom line, the computer ignores the comment about being unhaunted. Since c is 40, and h is 23, the bottom line makes the computer print:
Everything to the right of an apostrophe is called a comment (or remark). While the computer runs the program, it ignores the comments. But the comments remain part of the program; they appear on the blue screen with the rest of the program. Though the comments appear in the program, they don’t affect the run.
Here’s a strange program:
The third line (x = 4 + x) means: the new x is 4 plus the old x. So the new x is 4 + 9, which is 13. The bottom line prints:
Let’s look at that program more closely. The second line (x = 9) puts 9 into box x:
box x │ 9 │
When the computer sees the next line (x = 4 + x), it examines the equation’s right side and sees the 4 + x. Since x is 9, the 4 + x is 4 + 9, which is 13. So the line “x = 4 + x” means x = 13. The computer puts 13 into box x:
box x │ 13 │
The program’s bottom line prints 13.
Here’s another weirdo:
The third line (b = b + 1) says the new b is “the old b plus 1”. So the new b is 6 + 1, which is 7. The bottom line prints:
In that program, the second line says b is 6; but the next line increases b, by adding 1 to b; so b becomes 7. Programmers say that b has been increased or incremented. In the third line, the “1” is called the increase or the increment.
The opposite of “increment” is decrement:
The second line says j starts at 500; but the next line says the new j is “the old j minus 1”, so the new j is 500 - 1, which is 499. The bottom line prints:
In that program, j was decreased (or decremented). In the third line, the “1” is called the decrease (or decrement).
Counting Suppose you want the computer to count, starting at 3, like this:
This program does it, by a special technique:
In that program, c is called the counter, because it helps the computer count.
The second line says c starts at 3. The PRINT line makes the computer print c, so the computer prints:
The next line (c = c + 1) increases c by adding 1 to it, so c becomes 4. The LOOP line sends the computer back to the PRINT line, which prints the new value of c:
Then the computer comes to the “c = c + 1” again, which increases c again, so c becomes 5. The LOOP line sends the computer back again to the PRINT line, which prints:
The program’s an infinite loop: the computer will print 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, and so on, forever, unless you abort it.
Here’s the general procedure for making the computer count:
Start c at some value (such as 3).
Then write a DO loop.
In the DO loop, make the computer use c (such as by saying PRINT c) and increase c (by saying c = c + 1).
To read the printing more easily, put a semicolon at the end of the PRINT statement:
The semicolon makes the computer print horizontally:
This program makes the computer count, starting at 1:
The computer will print 1, 2, 3, 4, etc.
This program makes the computer count, starting at 0:
The computer will print 0, 1, 2, 3, 4, etc.
Quiz Let’s make the computer give this quiz:
What’s the capital of Nevada?
What’s the chemical symbol for iron?
What word means `brother or sister’?
What was Beethoven’s first name?
How many cups are in a quart?
To make the computer score the quiz, we must tell it the correct answers:
What’s the capital of Nevada? Carson City
What’s the chemical symbol for iron? Fe
What word means `brother or sister’? sibling
What was Beethoven’s first name? Ludwig
How many cups are in a quart? 4
So feed the computer this DATA:
In the DATA, each pair consists of a question and an answer. To make the computer READ the DATA, tell the computer to READ a question and an answer, repeatedly:
Here’s the complete program:
The lines underneath READ make the computer PRINT the question, wait for the human to INPUT a response, and check IF the human’s response matches the correct answer. Then the computer will either PRINT “Correct!” or PRINT “No” and reveal the correct answer. When the computer reaches the end of the DATA, the computer does an EXIT DO and prints “I hope you enjoyed the quiz!”
Here’s a sample run, where I’ve underlined the parts typed by the human:
To give a quiz about different topcs, change the DATA.
Let’s make the computer count how many questions the human answered correctly. To do that, we need a counter. As usual, let’s call it c:
At the beginning of the program, the human hasn’t answered any questions correctly yet, so the counter begins at 0 (by saying “c = 0”). Each time the human answers a question correctly, the computer does “c = c + 1”, which increases the counter. The program’s bottom line prints the counter, by printing a message such as:
It would be nicer to print —
or, if the quiz were changed to include 8 questions:
To make the computer print such a message, we must make the computer count how many questions were asked. So we need another counter. Since we already used c to count the number of correct answers, let’s use q to count the number of questions asked. Like c, q must start at 0; and we must increase q, by adding 1 each time another question is asked:
Summing Let’s make the computer imitate an adding machine, so a run looks like this:
Here’s the program:
The second line starts the sum at 0. The PRINT line prints the sum. The INPUT line asks the human what number to add to the sum; the human’s number is called x. The next line (s = s + x) adds x to the sum, so the sum changes. The LOOP line sends the computer back to the PRINT line, which prints the new sum. The program’s an infinite loop, which you must abort.
Here’s the general procedure for making the computer find a sum:
Start s at 0.
Then write a DO loop.
In the DO loop, make the computer use s (such as by saying PRINT s) and increase s (by saying s = s + the number to be added).
Checking account If your bank’s nasty, it charges you 20¢ to process each good check that you write, and a $15 penalty for each check that bounces; and it pays no interest on the money you’ve deposited.
This program makes the computer imitate such a bank.…
In that program, the total amount of money in the checking account is called the sum, s. The second line (s = 0) starts that sum at 0. The first PRINT line prints the sum. The next line asks the human to press “d” (to make a deposit) or “c” (to write a check).
If the human presses “d” (to make a deposit), the computer asks “How much money do you want to deposit?” and waits for the human to type an amount to deposit. The computer adds that amount to the sum in the account (s = s + d).
If the human presses “c” (to write a check), the computer asks “How much money do you want the check for?” and waits for the human to type the amount on the check. The computer adds the 20¢ check-processing fee to that amount (c = c + .2). Then the computer reaches the line saying “IF c <= s”, which checks whether the sum s in the account is big enough to cover the check (c). If c <= s, the computer says “Okay” and processes the check, by subtracting c from the sum in the account. If the check is too big, the computer says “That check bounced!” and decreases the sum in the account by the $15 penalty.
That program is nasty to customers:
That nasty program makes customers hate the bank — and hate the computer! The bank should make the program friendlier. Here’s how:
So if the bank is kind, it will make all those changes. But some banks complain that those changes are too kind! For example, if a customer whose account contains just 1¢ writes a million-dollar check (which bounces), the new program charges him just 1¢ for the bad check; $15 might be more reasonable.
Moral: the hardest thing about programming is choosing your goal — deciding what you WANT the computer to do.
|all content copyright © 2002 / web design by josh feingold|