Basic
A computer’s a useless hunk of metal & plastic until somebody feeds it a program, which is a list of commands teaching the computer how to perform a task. A person who writes a program is called a programmer. Now you’ll learn how to write programs, so you become a programmer.
You learned to buy & use programs such as Microsoft Office. Now you’ll learn how to invent your own programs, so you can become the computer’s master and make it do whatever you wish, not limited to the creations of other programmers.
Programming the computer can be easy. You’ll write your own programs just a few minutes from now, when you read the next page. Then on your résumé you can brag you’re a “programmer.” As you read farther, you’ll learn how to become a good programmer, by writing programs that are more sophisticated.
Learning to program is fun, an adventure that expands your mind and turns you into a brilliant thinker.
You learn the secret of computer life: how to take a computer — that hunk of metal and plastic — and teach it new skills by feeding it programs you invent. Your teaching and programs turn the computer into a thinking organism. You can teach the computer to become as smart as you and even imitate your personality. You become the computer’s God, able to make the computer do anything you wish. Ah, the power!
To program the computer, feed it a list of commands written in a computer language. Each computer language is a small part of English. The easiest popular computer language is Basic.
Basic was invented in New Hampshire by 2 Dartmouth College
professors
(John Kemeny & Tom
Kurtz) in 1964 and improved afterwards. Basic consists of words
such as “print”, “input”, and “if”. I’ll
explain how to program the computer by using those Basic words.
Different computers speak different dialects of Basic.
For example, a popular dialect was invented in 1975 by a 19-year-old kid, Bill Gates. Since he developed software for microcomputers, he called himself Microsoft and called his Basic dialect Microsoft Basic.
Since Microsoft Basic is so wonderful, all popular computer companies paid him to make their computers understand Microsoft Basic. IBM, Apple, and hundreds of other computer companies all had to pay off Bill. Microsoft Basic became so popular that he had to hire hundreds of employees to help him fill all the orders. Microsoft Incorporated became a multi-billion-dollar company, and Bill became a famous billionaire, the wealthiest person in the world.
Over the years, Bill improved Microsoft Basic. Some computers used old versions of Microsoft Basic; other computers used his later improvements.
One of the most popular versions of Microsoft Basic has been QBasic. It’s been popular because it works well and most people got it at no charge: free!
QBasic expected your operating system to be MS-DOS. You could force QBasic to run with some versions of Windows, and you could even download QBasic free from some Websites (by Microsoft and others), but now Microsoft has taken steps to stop you from doing so, since Microsoft wants you to use Visual Basic instead.
Previous editions of this book explained QB64 (pronounced “Q B sixty-four”), which imitated QBasic, ran well if you had Windows, and could be downloaded free from QB64.net. It was invented in Sydney, Australia by a guy whose name is “Rob” but whose nickname is “Galleon Dragon.” Unfortunately, QB.net has stopped allowing easy downloads.
A different dialect of Basic was invented in 1981 in England by the British Broadcasting Company (BBC) then greatly improved by Richard Russell, who’s amazingly brilliant. His newest and best version is called BBC Basic for Windows. In many ways, it’s better than Microsoft Basic. You can download it from his Website for free (unless you need advanced features that cost extra).
This chapter explains BBC Basic for Windows, because it’s the most pleasant programming language for beginners.
After reading this chapter, you can explore Visual Basic, which is explained in a later chapter. Visual Basic, invented by Microsoft, is harder than BBC Basic for Windows but more powerful: it lets you teach the computer to create windows & buttons and handle mouse clicks.
The commands of BBC Basic for Windows are explained on these pages:
Command What the computer will do Page Similar to
case a$ of analyze a$ to select a case from list below 492 endcase
circle 200,300,50 draw a circle at (200,300) with radius 50 509 ellipse
clg erase all graphics in the output window 510 cls, plot
cls erase everything in the output window 490 clg, print
colour 4 print in blue (color #4) instead of black 510 print
data meat,potatoes use this list of data: meat, potatoes 498 read
def proc_insult make the lines below define “insult” 524 proc_
dim x$(7) make x$ be a list of 7 strings 520 x =
draw 600,400 draw a line to pixel (600,400) 509 line, plot
ellipse 200,300,50,25 draw ellipse at (200,300), radii 50 & 25 509 circle
else do indented lines when “if” condition false 492 if, endif
end skip the rest of the program 491 stop, quit
endcase make this the bottom of “case” statement 492 case, when
endif make this the bottom of an “if” statement 492 if, else
endproc make this the bottom of a “def proc_” 524 def
exit repeat skip down to the line that’s under “until” 495 repeat
for x=1 to 20 repeat the indented lines, 20 times 495 next, repeat
gcol 9 make graphics red (color #9), not black 510 colour, clg
goto 10 skip to line 10 of the program 491 repeat
if age<18 print "kid" if age is less than 18, print “kid” 492 endif, else
input "What name";n$ ask “What name?” and get answer n$ 486 x=
line 200,300,500,350 draw a line from (200,300) to (500,350) 509 draw, plot
next make this the bottom line of a “for” loop 495 for
otherwise print "feel" if the “when” conditions false, print “feel” 492 case, when
plot 100,200 put a tiny dot at pixel (100,200) 510 line, draw
print 4+2 print the answer to 4+2 478 colour,@%=
proc_insult do the subprocedure named “insult” 524 def
quit skip rest of program; close output window 491 end, stop
read a$ get a string from the data and call it a$ 498 data
rectangle 200,300,8,5 draw rectangle at (200,300), sides 8 & 5 509 line
repeat do the indented lines below, repeatedly 489 until
restore 1 skip to line 1 of the data 501 read, data
sound 1,-15,4*25,20*3 make a loud sound for 3 seconds 510 print
stop skip rest of program and just print “STOP” 491 end, quit
until false make this the bottom line of “repeat” loop 489 repeat
vdu 2 copy the computer’s answers onto paper 481 print, cls
wait 600 wait 600 centiseconds 489 print
when "fine" print "g" if case is “fine”, print “g” 492 case
x=47 make x stand for the number 47 484 input
@%=131082+256*2 print 2 digits after each decimal point 510 print, x=
'Zoo program is fishy ignore this comment 505 print
The functions of BBC Basic for Windows are explained on these pages:
Function Meaning Value Page Similar to
abs(-3.89) absolute value of -3.89 3.89 512 sgn, int
acs(.5)*180/pi arccosine of .5, in degrees 60 519 sin, acs
asc("A") Ascii code number for “A” 65 517 chr$
asn(.5)*180/pi arcsine of .5, in degrees 30 519 sin, acs
atn(1)*180/pi arctangent of 1, in degrees 45 519 tan, asn
chr$(241) character whose code# is 241 “ñ” 517 asc
cos(60*pi/180) cosine of 60 degrees .5 519 sin, acs
exp(1) e raised to the first power 2.71828183 511 log, sqr
instr("needed","ed") position of “ed” in “needed” 3 518 len, mid$
int(3.89) round down to a lower integer 3 512 abs, sgn
left$("smart") leftmost character in “smart” “s” 517 right$, mid$
len("smart") length of “smart” 5 517 left$
ln(100000) logarithm base e of 100000 11.5129255 512 log, exp
log(100000) logarithm base 10 of 100000 5 511 ln, exp, sqr
mid$("smart",2) begin at the 2nd character “mart” 518 right$
right$("smart") rightmost character “t” 518 left$, mid$
rnd(4) random integer from 1 to 4 1, 2, 3, or 4 513 int
sgn(-3.89) sign of -3.89 -1 512 abs, int
sin(30*pi/180) sine of 30 degrees .5 519 cos, asn
sqr(9) square root of 9 3 511 exp, log, ln
str$(81.4) turn 81.4 into a string “ 81.4” 518 val
sum(x()) sum of numbers in array x varies 523 len
string$(20,"b") a string of 5 b’s “bbbbb” 518 str$
tan(45*pi/180) tangent of 45 degrees 1 519 sin, atn
val("52.6") remove the quotation marks 52.6 518 str$
Those are the best commands & functions for beginners, but BBC Basic for Windows includes many more!
Fun
Let’s have fun programming! If you have any difficulty, phone me at 603-666-6644 (day or night) for free help.
Get Basic
Here’s how to copy the nicest Basic (BBC Basic for Windows, version 6.14a) from the Internet to a Windows 10 or 11 computer, free (using Microsoft Edge):
Go to bbcbasic.co.uk/bbcwin/download.html. Tap “BBCWDEMO.EXE”.
You see a blue horizonal line get longer. When that line stops getting longer, tap the underlined down-arrow (which is above the blue line) then “Open file” then “Yes” then thrice “Next” then “Install” then “Finish”.
Close the Microsoft Edge window (by tapping its X). Close any other windows you have open, so you can start fresh.
Start Basic
Double-tap “BBC BASIC for Windows” (which is on the desktop screen). Tap “OK”.
You see the program window, titled “BBC BASIC for Windows 6.14a (trial)”.
To make your life easy (and follow the examples in this book), make sure the computer allows lowercase typing, by doing this:
Tap “Options”. Left of “Lowercase Keywords”, do you see a checkmark yet? If yes, just tap “Options” again; if no, tap “Lowercase Keywords”.
Type your program
Now you’re ready to type your first program!
For example, type this program:
print 4+2
Here’s how:
Type the word “print”. Then press the Space bar. Then type 4+2 (and remember to hold down the Shift key to type the symbol +).
At the end of that line, press the Enter key. (You must press the Enter key at the end of each line.) Pressing the Enter key makes the computer indent the line and makes the word “print” become orange.
A program is a list of commands that you want the computer to obey. The sample program you typed contains one command, which tells the computer to do some math: it tells the computer to compute 4+2, get the answer (6), and print the answer onto the screen.
Run your program
To make the computer obey the program you wrote, tap the “4” (which is green). That tells the
computer to run
the program: the computer will run through the program and obey any commands in
it. The computer obeys the “print 4+2” command and prints this answer onto the
output window:
6
Congratulations! You’ve written your first program! You’ve programmed the computer to compute the answer to 4+2! You’ve become a programmer! Now you can put on your résumé: “programmer!”
When you finish admiring the computer’s answer, close the output window, by tapping its X button.
Edit your program
After you’ve typed your program, try typing another one. For example, create a program that makes the computer print the answer to 79+2. To do that, make this program appear on the screen:
print 79+2
To make that program appear, just edit the program you typed previously (which said print 4+2). To edit, do this:
Move the cursor (vertical line) to the left edge of the character you want to change (which was the 4), by using the arrow keys (or clicking there with the mouse). Then delete that character (4) by pressing the Delete key. Then type the characters you want instead (79).
If you’ve edited the program successfully, the screen shows just the new program —
print 79+2
and you don’t see the old program anymore.
When you’ve finished editing the program, run it by tapping the green triangle. Then the computer will print the answer:
81
Your program can contain several lines. Each line is a separate command. For example, your program can be:
print 8+1
print 41+5
When you run that program (by tapping the green triangle), the computer will obey both commands, so the output window will show both answers:
9
46
While editing, use these tricks.…
To delete a character:
move the cursor (vertical line) to that character’s left edge by using the arrow keys (or clicking there with the mouse), then press the Delete key.
To delete SEVERAL characters:
move to the first character you want to delete,
then hold down the Delete key awhile.
To delete the LINE you typed recently:
tap the Undo icon (which is a curved arrow pointing backwards).
To delete A DIFFERENT LINE:
drag across that line then press the Delete key.
To INSERT A NEW LINE between two lines:
move to the beginning of the lower line, then press the Enter key.
Fix your errors
What happens if you misspell a computer word, such as “print”? For example, what happens if you accidentally say “primpt” instead of “print”?
Here’s the result:
When you run the program (by tapping the green triangle), the output window says “Mistake”. When you close the output window and see your bad program, the cursor is at the beginning of the bad line. Fix the error.
Abbreviation
Instead of typing the word “print”, you can abbreviate: type just the letter “p” and a period. When you press the Enter key at the end of the line, the computer will change the “p.” to “print”.
So instead of typing —
print 4+2
you can type just:
p. 4+2
Immediate mode
To make Basic do math, you’ve learned to type a program then make the computer run it (by tapping the green triangle), so the answer appears in the output window. But here’s a faster way: type directly in the output window! That technique is called immediate mode. Here’s how to do it.
Make the output window appear. If it hasn’t appeared yet, make it appear by using one of these methods:
Menu method While looking at the program window, tap “Run” then “Immediate Mode”.
Keyboard method While looking at the program window, tap the Keyboard icon (which looks like a keyboard and is at the far right).
Triangle method While looking at the program window, tap the green triangle. (That runs any program in the program window and shows you the output window.)
In the output window, you see this symbol:
>
Next to that symbol, type any command you wish, such as:
>print 4+2
At the end of that line, press the Enter key. The computer will obey that line immediately, so it will show:
6
Try it!
Math
This program makes the computer add 4+2:
print 4+2
When you run the program (by tapping the green triangle), the computer will print the answer:
6
If you want to subtract 3 from 7, type this command instead:
print 7-3
(When typing the minus sign, do not press the Shift key.) The computer will print:
4
You can use decimal points and negative numbers. For example, if you type this —
print -26.3+1
the computer will print:
-25.3
Multiplication To multiply, use an asterisk. So to multiply 2 by 6, type this:
print 2*6
The computer will print:
12
Division To divide, use a slash. So to divide 8 by 4, type this:
print 8/4
The computer will print:
2
To divide 2 by 3, type this:
print 2/3
The computer will round the answer and print just:
0.666666667
If you try to divide by 0, by typing —
print 5/0
the computer will refuse. Instead, it will print this gripe:
Division by zero
Avoid commas Do not put commas in big numbers. To write four million, do not write 4,000,000; instead, write 4000000.
E notation If the computer’s answer is huge (more than a million) or tiny (less than .0001), the computer might print an E in the answer. The E means “move the decimal point”.
For example, suppose the computer says the answer to a problem is:
8.516743297E12
The E means, “move the decimal point”. The plus sign means, “towards the right”. Altogether, the E12 means “move the decimal point towards the right, 12 places.” So look at 8.516743297 and move the decimal point towards the right, 12 places; you get 8516743297000.
So when the computer says the answer is 8.516743297E12, the computer really means the answer is 8516743297000, approximately. The exact answer might be 8516743297000.2 or 8516743297000.79 or some similar number, but the computer prints just an approximation.
Suppose your computer says the answer to a problem is:
9.23E-6
After the E, the minus sign means, “towards the left”. So look at 9.23 and move the decimal point towards the left, 6 places. You get:
.00000923
So when the computer says the answer is 9.23E-6, the computer really means the answer is:
.00000923
You’ll see E notation rarely: the computer uses it just if an answer is at least a billion (1,000,000,000) or tiny (tinier than .0001). But when the computer does use E notation, remember to move the decimal point!
If you want to write E notation yourself, you must capitalize the E.
Rounding To print a long number, the computer will round it and print just 9 significant digits.
The highest number The highest number the computer can handle well is about 1E4932, which is 1 followed by 4932 zeros. If an answer is much higher, the computer will say:
Number too big
The tiniest decimal The tiniest decimal the computer can handle easily is about 4E-4932, which is a decimal point followed by 4932 digits (4931 zeros then a 4). If you try to go much tinier, the computer will say 0.
Order of operations What does
“2 plus 3 times 4” mean? The answer depends on whom you ask.
To a clerk, it means “start
with 2 plus 3, then multiply by 4”; that makes 5 times 4, which is 20.
But to a scientist, “2 plus 3 times 4” means something different: it means “2
plus three fours”, which is
2+4+4+4, which is 14.
Since computers were invented by scientists, computers think like scientists. If you type —
print 2+3*4
the computer will think you mean “2 plus three fours”, so it will do 2+4+4+4 and print this answer:
14
The computer will not print the clerk’s answer, which is 20. So if you’re a clerk, tough luck!
Scientists and computers follow this rule: do multiplication and division before addition and subtraction. So if you type —
print 2+3*4
the computer begins by hunting for multiplication and division. When it finds the multiplication sign between the 3 and the 4, it multiplies 3 by 4 and gets 12, like this:
print 2+3*4
\ /
12
So the problem becomes 2+12, which is 14, which the computer prints.
For another example, suppose you type:
print 10-2*3+72/9*5
The computer begins by doing all the multiplications and divisions. So it does 2*3 (which is 6) and does 72/9*5 (which is 8*5, which is 40), like this:
print 10-2*3+72/9*5
\ / \ /
6 40
So the problem becomes 10-6+40, which is 44, which is the answer the computer prints.
You can use parentheses the same way as in algebra. For example, if you type —
print 5-(1+1)
the computer will compute 5-2 and print:
3
You can put parentheses inside parentheses. If you type —
print 10-(5-(1+1))
the computer will compute 10-(5-2), which is 10-3, and will print:
7
Strings
Let’s make the computer fall in love. Let’s make it say, “I love you”.
Type this program:
print "I love you"
Here’s how to type the second line:
Begin by typing the word “print”. Then type a blank space (by pressing the Space bar). Then type a quotation mark, but be careful: to type the quotation mark, you must hold down the Shift key. Then type these words: I love you. Then type another quotation mark.
At the end of that line, press the Enter key. Pressing the Enter key makes the computer analyze that line: the word “print” turns orange, “I love you” turns purple, and the whole line gets indented.
When you run that program (by tapping the green triangle), the computer will obey your command; it will print:
I love you
You can change the computer’s personality. For example, if you give this command —
print "I hate you"
the computer will reply:
I hate you
Notice that to make the computer print a message, you must put the message between quotation marks. The quotation marks make the computer copy the message without worrying about what the message means. For example, if you misspell “I love you”, and type —
print "aieee luf ya"
the computer will still copy the message (without worrying about what it means); the computer will print:
aieee luf ya
Jargon The word “joy” consists of 3 characters: j and o and y. Programmers say that the word “joy” is a string of 3 characters.
A string is any collection of characters, such as “joy” or “I love you” or “aieee luf ya” or “76 trombones” or “GO AWAY!!!” or “xypw exr///746”. The computer will print whatever string you wish, but remember to put the string in quotation marks.
Strings versus numbers The computer can handle two
types of expressions: strings
and numbers.
Put strings (such as “joy” and “I love you”) in quotation marks. Numbers (such
as
4+2) do not go in quotation marks.
Accidents Suppose you accidentally put the number 2+2 in quotation marks, like this:
print "2+2"
The quotation marks make the computer think “2+2” is a string instead of a number. Since the computer thinks “2+2” is a string, it copies the string without analyzing what it means; the computer will print:
2+2
It will not print 4.
Suppose you want the computer to print the word “love” but you accidentally forget to put the string “love” in quotation marks, and type this instead:
PRINT love
Since you forgot the quotation marks, the computer thinks love is a number instead of a string but doesn’t know which number, since the computer doesn’t know the meaning of love. Whenever the computer is confused, it gripes at you. In this particular example, when you run the program the computer will print this gripe:
No such variable
So if you incorrectly tell the computer to proclaim its love, it will say no.
Longer programs You can program the computer to say it’s madly in love with you!
Let’s make the computer say:
I love you.
You turned me on.
Let's get married!
To make the computer say all that, just run this program:
print "I love you."
print "You turned me on."
print "Let's get married!"
To run that program, type it then tap the green triangle. Try it!
To have even more fun, run this program:
print "I long"
print 2+2
print "U"
It makes the computer print “I long”, then print the answer to 2+2 (which is 4), then print “U”. So altogether, the computer prints:
I long
4
U
Yes, the computer says it longs for you!
Adding strings You can add strings together: “hot”+“dog” is the same as “hotdog”. If you say —
print "hot"+"dog"
the computer will print:
hotdog
Tricky printing
Printing can be tricky! Here are the tricks.
Indenting Suppose you want the computer to print this letter onto the screen:
Dear Joan,
Thank you for the beautiful
necktie. Just one problem--
I don't wear neckties!
Love,
Fred-the-Hippie
This program prints it:
print "Dear Joan,"
print " Thank you for the beautiful"
print "necktie. Just one problem--"
print "I don't wear neckties!"
print " Love,"
print " Fred-the-Hippie"
In the program, each line contains 2 quotation marks. To make the computer indent a line, put blank spaces AFTER the first quotation mark.
Blank lines Life consists sometimes of joy, sometimes of sorrow, and sometimes of a numb emptiness. To express those feelings, run this program:
Program What the computer will do
print "joy" Print “joy”.
print Print blank empty line, under “joy”.
print "sorrow" Print “sorrow”.
Altogether, the computer will print:
joy
sorrow
Semicolons Run this program:
print "fat";
print "her"
The top line, which makes the computer print “fat”, ends with a semicolon. The semicolon makes the computer print the next item on the same line; so the computer will print “her” on the same line, like this:
father
The next program shows what happens to an evil king on a boat:
print "sin";"king"
The computer will print “sin”, and will print “king” on the same line, like this:
sinking
Notice that in a print statement, you can type several items (such as “sin” and “king”). Between the items, type a semicolon.
Spaces around numbers To print a number, the computer wants to print 10 characters. If the number is shorter than 10 characters, the computer puts blank spaces before the number, to make the total number of characters be 10. Exception: if the “print” statement has a semicolon before the number, the computer does not put blank spaces before the number.
For example, “print 2+3” makes the computer print 5 with blank spaces before it —
5
but “print ;2+3” makes the computer print 5 without blank spaces before it:
5
Suppose you want the computer to print the answer to 2+2 and also the answer to 5+4, both on the same line. If you write —
print 2+2;5+4
the computer will print the answer to 2+2 (which is 4) and put blank spaces before it, then print the answer to 5+4 (which is 9) without blank spaces, like this:
49
To separate those two answers from each other, you can tell the computer to print a space between the numbers, like this:
print 2+2;" ";5+4
That makes the computer print:
4 9
This command is correct:
print "eat ";3+2;" apples"
The computer will print “eat ” (which includes a blank space in its ending), then 3+2 (which is 5), then “ apples” (which begins with a blank space), so the computer will print:
eat 5 apples
If you accidentally put no spaces in the strings, like this —
print "eat";3+2;"apples"
the computer will print no spaces in the answer, so it prints this jumble:
eat5apples
Double quotation marks Let’s make the computer print this:
You really "wow" me
To make the computer print quotation marks around “wow”,
put DOUBLE quotation marks
around that word:
print "You really ""wow"" me"
If you accidentally put just single quotation marks, like this —
print "You really "wow" me"
the computer will print “You really ” then complain it doesn’t know how to wow. The computer will print:
You really
No such variable
Copy program onto paper To print a copy of your program onto paper, make sure the printer is turned on. Then tap the Printer icon (which is above your program) then “OK”.
For example, if you program says —
print 4+2
the printer will print this copy onto paper:
print 4+2
The printer automatically underlines all orange words (such as “print”). It also prints today’s date on the paper’s bottom-right corner, so you can brag about when you printed it.
Copy answers onto paper To copy the computer’s answers onto paper, make the program’s top line say:
vdu 2
Make sure the printer is turned on, then run the program (by tapping the green triangle).
The answers will still appear in the ouput window, as usual; but afterwards, when you close the output window (by clicking its X), the printer will print a copy of the answers.
For example, if the program is —
print 4+2
the printer will print 6 onto paper (although the 6 won’t be quite as far to the right as you expect).
If you want the printer to copy just some of the answers, type “vdu 2” above the lines whose answers you want copied and type “vdu 3” below them. The “vdu 2” means “copy to paper”; “vdu 3” means “hide from paper”; but all printing gets delayed until you close the output window (or until the computer encounters a line saying “vdu 12”, which forces the printer to spit out the answers immediately).
Save
If you want the computer to copy the program onto drive C, tap the Save icon. (It’s above your program. It’s left of the Printer icon. It’s below the “U” in “Utilities”. It looks like a floppy disk, which is square.)
To make sure things stay simple, do this: tap “This PC” then double-tap “Documents”.
If you haven’t invented a name for the program yet, here’s what happens:
The computer says “Save As”.
Tap “This PC” then double-tap “Documents” (to emphasize you want the program to be stored in drive C’s main Documents folder).
Tap in the “File name” box. Invent a name for your program. Invent any name you wish. For example, the name can be Joe or Sue or Lover or poem4u. Pick a name that reminds you of the program’s purpose. When you finish typing the name, press the Enter key.
Then the computer automatically adds “.bbc” to the end of the program’s name and copies the program to drive C’s main “Documents” folder.
Exception: if the name you invented was already used by another program, the computer asks you, “Do you want to replace it?” Tap the “Yes” button if you want the new program to replace the old program, so the old program disappears. If you do not want the new program to replace the old program, tap the “No” button instead of “Yes” then invent a different name for your new program.
Suppose you’re creating a program that’s so long it takes you several hours to type. You’ll be upset if, after several hours of typing, your town suddenly has a blackout that makes the computer forget what you typed. To protect yourself against such a calamity, tap Save every 15 minutes. Then if your town has a blackout, you’ll lose just a few minutes of work; the rest of your work will have already been saved on the disk. Saving your program every 15 minutes protects you against blackouts and also “computer malfunction” and any careless errors you might make.
New When you’ve finished inventing and saving a program, here’s how to erase everything in the program window, so you can start writing a different program instead: tap “File” (which is near the program window’s top-left corner) then “New”.
(If you didn’t save the program you worked on, the computer asks, “Save current changes?” If you want to save the program you worked on, tap the “Yes” button; if you do not want to save the program you worked on, tap the “No” button instead.)
Here’s a faster way to erase everything in the program window:
While holding down the Ctrl key, tap the A key. Then press the Delete key.
Load If you saved a program onto the hard disk (drive C), here’s how to use it again: tap the Load icon. (It’s above your program. It looks like a file folder opening up, so it’s also called the Open icon. It’s below the “E” in “Edit”.) If the computer asks “Save current changes?” tap the “No” button (unless you really want “Yes”).
The computer says “Load”.
The first box should say:
> This PC > Documents >
If it doesn’t say that yet, do this:
Tap “This PC” then double-tap “Documents”.
Then you see a list of Basic programs (and other files) in drive C’s Documents folder. Double-tap the program you want.
Then the program appears in the program window. To run it, tap the green triangle.
Save As Suppose you’ve saved a program called Joe. Here’s how to create a variant of it, called Joe2, so your hard disk contains both versions, Joe and Joe2.
First, create Joe and save it. Then make sure the program window still shows Joe’s program lines. Edit those program’s lines, to create whatever variant you want. Then name that variant “Joe2” by doing this:
Tap “File” then “Save As”. Type “Joe2” and press the Enter key.
Exit
When you’ve finished using Basic, close its window (the program window) by tapping its X button.
(If you didn’t save the program you worked on, the computer asks, “Save current changes?” If you want to save the program you worked on, tap the “Yes” button; if you do not want to save the program you worked on, tap the “No” button instead.)
Then the computer will exit from Basic.
Line numbers
You can number the lines in your program. For example, instead of typing —
print "Let's munch”
print "sandwiches"
print "under the trees"
you can type:
1 print "Let's munch”
2 print "sandwiches"
3 print "under the trees"
Then when you’re discussing your program with another programmer, you can talk about “line 2” instead of having to talk about “the line that mentions sandwiches”.
Selective numbering You can number just the lines you’re planning to discuss.
For example, if you’re planning to discuss just lines 1 and 3, you can number just those lines:
1 print "Let's munch"
print "sandwiches"
3 print "under the trees"
Or if you prefer, number them like this:
1 print "Let's munch"
print "sandwiches"
2 print "under the trees"
(When you type an unnumbered line, the computer automatically indents it to look like that.)
Number by tens Instead of making line numbers be 1, 2, 3, etc., make the line numbers be 10, 20, 30, etc., like this:
10 print "Let's munch"
20 print "sandwiches"
30 print "under the trees"
Then you can insert an extra numbered line without changing your numbers:
10 print "Let's munch"
15 print "delicious"
20 print "sandwiches"
30 print "under the trees"
Number automatically Above your program, you see this icon:
10
20
30
If you click it and then press the Enter key (while letting the “First line” box say 10, the “Increment” box say 10, and the “Remove unused line numbers box” be blank), the computer will automatically number all the lines in your program (10, 20, 30, etc.).
Multi-statement line
In your program, a line can contain several statements separated by colons, like this:
print "I dream": print "of you"
When you run that program, the computer will print “I dream” then print “of you”, like this:
I dream
of you
If you want to number the line, put the number at the far left, like this:
10 print "I dream": print "of you"
Become an expert
Congratulations! You’ve learned how to program!
C’mon, write some programs! It’s easy! Try it. You’ll have lots of fun!
A person who writes a program is called a programmer. Congratulations: you’re a programmer!
Write several programs like the ones I’ve shown you already. Then you can put on your résumé that you have “a wide variety of programming experience”, and you can talk your way into a programming job!
The rest of this chapter explains how to become a good programmer.
Practice Programming the computer is like driving a
car:
the only way to become an
expert is to put your hands on that mean machine and try it yourself.
If you have a computer, put this book next to the computer’s keyboard. At the end of each paragraph, type the examples and look, look, see the computer run! Invent your own variations: try typing different numbers and strings. Invent your own programs: make the computer print your name or a poem; make it solve problems from your other courses and the rest of your life. The computer’s a fantastic toy. Play with it.
If you’re a student, don’t wait for your instructor to give lectures and assign homework. Act now. You’ll learn more from handling the computer than from lectures or readings. Experience counts.
Hang around your computer. Communicate with it every day. At first, that will be even harder than talking with a cat or a tree, because the computer belongs to a different species, a different kingdom; but keep trying. Get to know it as well as you know your best friend.
If you’re taking a French course, you might find French hard; and if you’re taking a computer course, you might find computers hard also. But even a stupid 3-year-old French kid can speak French, and even kindergarten kids can program the computer. They have just one advantage over you: practice!
Be bold In science fiction, computers blow up; in real life, they never do. No matter what keys you press, no matter what commands you type, you won’t hurt the computer. The computer is invincible! So go ahead and experiment. If it doesn’t like what you type, it will gripe at you, but so what?
Troubles When you try using the computer, you’ll have trouble — because you’re making a mistake, or the computer is broken, or the computer is weird and works differently from the majority computers discussed in this book. (Each computer has its own “personality”, its own quirks.)
Whenever you have trouble, laugh about it, and say, “Oh, boy! Here we go again!” (If you’re Jewish, you can say all that more briefly, in one word: “Oy!”) Then get some help.
Get help For help with your computer, read this book! For further help, read the manuals that came with your computer or ask the genie who got you the computer (your salesperson or parent or boss or teacher or friend).
If you’re sitting near computers in your office, school, or home, and other people are nearby, ask them for help. They’ll gladly answer your questions because they like to show off and because the way they got to know the answers was by asking.
Computer folks like to explain computers, just as priests like to explain religion. You’re joining a cult! Even if you don’t truly believe in “the power and glory of computers”, at least you’ll get a few moments of weird fun. Just play along with the weird computer people, boost their egos, and they’ll help you get through your initiation rite. Assert yourself and ask questions. “Shy guys finish last.” To get your money’s worth from a computer course, ask your teacher, classmates, lab assistants, and other programmers lots of questions!
Your town might have a computer club. (To find out, ask the local schools and computer stores.) Join the club and tell the members you’d like help with your computer. Probably some computer hobbyist will help you.
Call me anytime at 603-666-6644: I’ll help you, free!
Variables
A letter can stand for a number. For example, x can stand for the number 47, as in this program:
x=47
print x+2
The top line says x stands for the number 47; 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.
Jargon
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 “x=47” is called an assignment statement, because it assigns 47 to x.
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.
Undefined variable
In that program, if you forget to type “x=47”, here’s what happens:
The computer won’t know what x is, so x is undefined. When the computer tries to do “print x+2”, it will gripe by saying “No such variable”.
More examples
Here’s another example:
y=38
print y-2
The top 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.
Example:
b=8
print b*3
The top 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:
n=6
d= n+1
print n*d
The top 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:
k=4
k=9
print k*2
The top 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 top 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.
After that program runs, the computer will keep remembering k is 9. In the output window, if you type —
>print k
the computer will print 9. The computer will keep remembering k is 9, until you close the output window. Closing the output window makes the computer forget the values of all variables.
Hassles
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:
b=1
c=7
b=c
print b+c
The third 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:
b=1 b=1
c=7 c=7
b=c c=b
print b+c print b+c
In the left program (which you saw before), the third line changes b to 7, so both b and c are 7. The bottom line prints 14.
In the right program, the third 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).
Modifying itself A variable can modify itself:
d=5
d=d+2
print d
The top line says d is 5. The next line says d’s new value is what d was before, plus 2, so d is 5+2, which is 7. The bottom line prints 7.
Instead of typing “d=d+2”, you can type just “d+=2”, which means “d is increased by 2”.
Here are similar statements:
Statement Meaning Shortcut Meaning
d=d+2 new d is old d + 2 d+=2 d is increased by 2
d=d-2 new d is old d – 2 d-=2 d is decreased by 2
d=d*2 new d is old d*2 d*=2 d is multiplied by 2
d=d/2 new d is old d/2 d/=2 d is divided by 2
Example:
d=100
d=d/4 (or you can type just d/=4)
print d
The top line says d is 100. The next line says d’s new value is d’s old value divided by 4 (so d is divided by 4), so d becomes 25. The bottom line prints 25.
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:
print 1297.43*2
print 1297.43*.05
print 1297.43+483.19
print 1297.43*37
But that program’s silly, since it contains the number 1297.43 four times. This program’s briefer, because it uses a variable:
c=1297.43
print c*2
print c*.05
print c+483.19
print c*37
It’s also easier to update, if later your boss says you must change 1297.43 to a different number.
So whenever you need to use a number several times, turn the number into a variable, which will make your program briefer and easier to update.
String variables
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:
g$="down"
print g$
The top line says g$ stands for the string “down”. The bottom line prints:
down
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:
t$="They're laughing at you!"
print t$
print t$
print t$
The top line says t$ stands for the string “They’re laughing at you!” The later lines make the computer print:
They're laughing at you!
They're laughing at you!
They're laughing at you!
Spaces between strings
Examine this program:
s$="sin"
k$="king"
print s$;k$
The bottom line says to print “sin” and then “king”, so the computer will print:
sinking
Let’s make the computer leave a space between “sin” and “king”, so the computer prints:
sin king
To make the computer leave that space, choose one of these methods.…
Method 1 Instead of saying s$ = “sin”, make s$ include a space:
s$="sin "
Method 2 Instead of saying k$ = “king”, make k$ include a space:
k$=" king"
Method 3 Instead of saying —
print s$;k$
say to print s$ then a space then k$:
print s$;" ";k$
Nursery rhymes
The computer can recite nursery rhymes:
p$="Peas porridge "
print p$;"hot!"
print p$;"cold!"
print p$;"in the pot,"
print "Nine days old!"
The top line says p$ stands for “Peas porridge ”. The later lines make the computer print:
Peas porridge hot!
Peas porridge cold!
Peas porridge in the pot,
Nine days old!
This program prints a fancier rhyme:
h$="Hickory, dickory, dock!"
m$="THE MOUSE (squeak! squeak!) "
c$="THE CLOCK (tick! tock!) "
print h$
print m$;"ran up ";c$
print c$;"struck one"
print m$;"ran down"
print h$
Lines 1-3 define h$, m$, and c$. The later lines make the computer print:
Hickory, dickory, dock!
THE MOUSE (squeak! squeak!) ran up THE CLOCK (tick! tock!)
THE CLOCK (tick! tock!) struck one
THE MOUSE (squeak! squeak!) ran down
Hickory, dickory, dock!
Long variable names
A numeric variable’s name can be a letter (such as x) or a longer combination of characters, such as:
money_earned_in_November_2020_before_promotion
The variable’s name must begin with a letter. It can include small letters, capital letters, digits, and underlines. It can be as long as you wish!
It must not begin with a word that has a special meaning to the computer. For example, it cannot begin with the letters “print”.
If the variable stands for a string, it must end in a dollar sign.
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) but long variable names in long programs (so you can keep track of which variable is which).
Programmers employed at Microsoft capitalize each word’s first letter and can’t use underlines. So instead of writing —
money_earned_in_November_2020_before_promotion
they write:
MoneyEarnedInNovember2020BeforePromotion
That’s harder to read; but if you’re programming for Microsoft, you have no choice.
Input
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:
input "What is your name";n$
print "I adore anyone whose name is ";n$
When the computer sees that input line, the computer asks “What is your name?” 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:
I adore anyone whose name is Maria
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.…
Computer asks for your name: What is your name? Maria
Computer praises your name: I adore anyone whose name is Maria
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.…
Computer asks for your name: What is your name? Bud
Computer praises your name: I adore anyone whose name is Bud
When the computer asks for your name, if you say something weird, the computer will give you a weird reply.…
Computer asks: What is your name? none of your business!
Computer replies: I adore anyone whose name is none of your business!
Abbreviation
Instead of typing the word “input”, you can abbreviate: type just the letter “i” and a period. When you press the Enter key at the end of the line, the computer will change the “i.” to “input”.
So instead of typing —
input "What is your name";n$
you can type just:
i. "What is your name";n$
College admissions
This program prints a letter, admitting you to the college of your choice:
input "What college would you like to enter";c$
print "Congratulations!"
print "You have just been admitted to ";c$
print "because it fits your personality."
print "I hope you go to ";c$;"."
print " Respectfully yours,"
print " The Dean of Admissions"
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.…
Computer asks you: What college would you like to enter? Harvard
Computer admits you: Congratulations!
You have just been admitted to Harvard
because it fits your personality.
I hope you go to Harvard.
Respectfully yours,
The Dean of Admissions
You can choose any college you wish:
Computer asks you: What college would you like to enter? Hell
Computer admits you: Congratulations!
You have just been admitted to Hell
because it fits your personality.
I hope you go to Hell.
Respectfully yours,
The Dean of Admissions
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:
Once upon a time, there was a youngster named ____________
your name
who had a friend named ____________.
friend’s name
____________ wanted to ________________ ____________,
your name verb (such as “pat”) friend’s name
but ____________ didn’t want to ________________ ____________!
friend’s name verb (such as “pat”) your name
Will ____________ ________________ ____________?
your name verb (such as “pat”) friend’s name
Will ____________ ________________ ____________?
friend’s name verb (such as “pat”) your name
To find out, come back and see the next exciting episode
of ____________ and ____________!
your name friend’s name
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”:
input "What is your name";y$
input "What's your friend's name";f$
input "In 1 word, say something you can do to your friend";v$
Then make the computer print the story:
print "Here's my story...."
print "Once upon a time, there was a youngster named ";y$
print "who had a friend named ";f$;"."
print y$;" wanted to ";v$;" ";f$;","
print "but ";f$;" didn't want to ";v$;" ";y$;"!"
print "Will ";y$;" ";v$;" ";f$;"?"
print "Will ";f$;" ";v$;" ";y$;"?"
print "To find out, come back and see the next exciting episode"
print "of ";y$;" and ";f$;"!"
Here’s a sample run:
What's your name? Dracula
What's your friend's name? Madonna
In 1 word, say something you can do to your friend? bite
Here's my story....
Once upon a time, there was a youngster named Dracula
who had a friend named Madonna.
Dracula wanted to bite Madonna,
but Madonna didn't want to bite Dracula!
Will Dracula bite Madonna?
Will Madonna bite Dracula?
To find out, come back and see the next exciting episode
of Dracula and Madonna!
Here’s another run:
What's your name? Superman
What's your friend's name? King Kong
In 1 word, say something you can do to your friend? tickle
Here's my story....
Once upon a time, there was a youngster named Superman
Who had a friend named King Kong.
Superman wanted to tickle King Kong,
but King Kong didn't want to tickle Superman!
Will Superman tickle King Kong?
Will King Kong tickle Superman?
To find out, come back and see the next exciting episode
of Superman and King Kong!
Try it: put in your own name, the name of your friend, and something you’d like to do to your friend.
Contest
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:
input "What's your name";you$
input "What's your friend's name";friend$
input "What's the name of another friend";friend2$
input "Name a color";color$
input "Name a place";place$
input "Name a food";food$
input "Name an object";object$
input "Name a part of the body";part$
input "Name a style of cooking (such as baked or fried)";style$
print "Congratulations, ";you$;"!"
print "You've won the beauty contest, because of your gorgeous ";part$;"."
print "Your prize is a ";color$;" ";object$
print "plus a trip to ";place$;" with your friend ";friend$
print "plus--and this is the best part of all--"
print "dinner for the two of you at ";friend2$;"'s new restaurant,"
print "where ";friend2$;" will give you ";
print "all the ";style$;" ";food$;" you can eat."
print "Congratulations, ";you$;", today's your lucky day!"
print "Now everyone wants to kiss your award-winning ";part$;"."
Here’s a sample run:
What's your name? Long John Silver
What's your friend's name? the parrot
What's the name of another friend? Jim
Name a color? gold
Name a place? Treasure Island
Name a food? rum-soaked coconuts
Name an object? chest of jewels
Name a part of the body? missing leg
Name a style of cooking (such as baked or fried)? barbecued
Congratulations, Long John Silver!
You've won the beauty contest, because of your gorgeous missing leg.
Your prize is a gold chest of jewels
plus a trip to Treasure Island with your friend the parrot
plus--and this is the best part of all--
dinner for the two of you at Jim's new restaurant,
where Jim will give you all the barbecued rum-soaked coconuts you can eat.
Congratulations, Long John Silver, today's your lucky day!
Now everyone wants to kiss your award-winning missing leg.
Numeric input
This program makes the computer predict your future:
print "I predict what'll happen to you in the year 2030!"
input "In what year were you born";y
print "In the year 2030, you'll turn ";2030-y;" years old."
Here’s a sample run:
I predict what'll happen to you in the year 2030!
In what year were you born? 1972
In the year 2030, you'll turn 58 years old.
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:
input "How many tickets";t
print "The total price is $";t*2.79
This program tells you how much the “oil crisis” costs you when you drive your car:
input "How many miles do you want to drive"; m
input "How many pennies does a gallon of gas cost"; p
input "How many miles-per-gallon does your car get"; r
print "The gas for your trip will cost you $";m*p/(r*100)
Here’s a sample run:
How many miles do you want to drive? 400
How many pennies does a gallon of gas cost? 264.9
How many miles-per-gallon does your car get? 31
The gas for your trip will cost you $34.1806452
Conversion
This program converts feet to inches:
input "How many feet";f
print f;" feet = ";f*12;" inches"
Here’s a sample run:
How many feet? 3
3 feet = 36 inches
Trying to convert to the metric system? This program converts inches to centimeters:
input "How many inches"; i
print i;" inches = ";i*2.54;" centimeters"
Nice day today, isn’t it? This program converts the temperature from Celsius to Fahrenheit:
input "How many degrees Celsius"; c
print c;" degrees Celsius = ";c*1.8+32;" degrees Fahrenheit"
Here’s a sample run:
How many degrees Celsius? 20
20 degrees Celsius = 68 degrees Fahrenheit
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.
Going & stopping
You can control how your computer goes and stops.
Wait
A centisecond is a very short period of time: just a hundredth of a second!
If you say —
wait 600
the computer will wait for 600 centiseconds, which is 6 seconds. That’s how to make the computer pause for 6 seconds.
Give the 6-second pause before you reveal a joke’s punch line:
print "Human, your intelligence is amazing! You must be an M.D.";
wait 600
print "--Mentally Deficient!"
That program makes the computer print the joke’s setup (“Human, your intelligence is amazing! You must be an M.D.”), then pause for 6 seconds, then reveal the joke’s punch line, so the screen finally shows:
Human, your intelligence is amazing! You must be an M.D.--Mentally Deficient!
If you want the computer to pause for 9 seconds instead of 6, say “wait 900” instead of “wait 600”.
This program makes the computer brag, then confess:
print "We computers are smart for three reasons."
print "The first is our VERY GOOD MEMORY."
print "The other two reasons...";
wait 900
print "I forgot."
The computer begins by bragging:
We computers are smart for three reasons.
The first is our VERY GOOD MEMORY.
The other two reasons...
But then the computer pauses for 10 seconds and finally admits:
I forgot.
This program makes the computer change its feelings, in surprising ways:
print "I'm up";
wait 300
print "set! I want to pee";
wait 400
print "k at you";
wait 500
print "r ma";
wait 600
PRINT "nual."
The computer will print —
I'm up
then pause 3 seconds and change it to —
I'm upset! I want to pee
then pause 4 seconds and change it to —
I'm upset! I want to peek at you
then pause 5 seconds and change it to —
I'm upset! I want to peek at your ma
then pause 6 seconds and change it to:
I'm upset! I want to peek at your manual.
Experiment: invent your own jokes, and make the computer pause before printing the punch lines.
Repeat
This program makes the computer print the word “love” once:
print "love"
This fancier program makes the computer print the word “love” three times:
print "love"
print "love"
print "love"
When you run that program, the computer will print:
love
love
love
Let’s make the computer print the word “love” many times. To do that, we must make the computer obey this line repeatedly:
print "love"
To make the computer obey the line repeatedly, say “repeat” above the line, so the program looks like this:
repeat
print "love"
The computer automatically indents the print line for you, when you press the Enter key at that line’s end.
How often do you want the computer to repeat? Underneath all that, say “until false” (which means “forever”), so the program looks like this:
repeat
print "love"
until false
The computer automatically unindents the “until” for you, when you press the Enter key at that line’s end.
When you run that program, the computer will print “love” many times, so it will print:
love
love
love
love
love
love
love
love
love
etc.
The computer will print “love” on every line of the output window.
But even when the output window is full of “love”, the computer won’t stop: the computer will try to print even more loves onto your screen! The computer will lose control of itself and try to devote its entire life to making love! The computer’s mind will spin round and round, always circling back to the thought of making love again!
Since the computer’s thinking keeps circling back to the same thought, the computer is said to be in a loop. In that program, “repeat” means “repeat what’s underneath & indented”; “until false” means “do it forever”. The lines that say “repeat” and “until false” — and the lines between them — form a loop, which is called a repeat loop.
To stop the computer’s lovemaking madness, you must give the computer a “jolt” that will put it out of its misery and get it out of the loop. To jolt the computer out of the program, abort the program by using one of these methods:
Window method Close the output window (by tapping its X).
Keyboard method Press the Escape key. (It’s the first key on the keyboard. It says “Esc” on it.) That stops the program from running and makes the output window show the word “Escape”.
In that program, since the computer tries to go round and round the loop forever, the loop is called infinite. The only way to stop an infinite loop is to abort it.
Semicolon For more lovely fun, put a semicolon after “love”, so the program looks like this:
repeat
print "love";
until false
The semicolon makes the computer print “love” next to “love”, so the output window looks like this:
lovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelo
velovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelove
lovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelovelo
etc.
If you put a space after love, like this —
repeat
print "love ";
until false
the computer will put a space after each love:
love love love love love love love love love love love love love love love love l
ove love love love love love love love love love love love love love love love lo
ve love love love love love love love love love love love love love love love lov
e love love love love love love love love love love love love love love love love
etc.
Bigger loop Run this program:
repeat
print "dog";
print "cat";
until false
Lines 2 & 3 (which say print “dog” and print “cat”) make the computer print “dog” and then print “cat” next to it. Since those lines are between the words “repeat” and “until”, the computer does them repeatedly — print “dog”, then print “cat”, then print “dog” again, then print “cat” again — so the screen looks like this:
dogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcat
dogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcat
dogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcat
etc.
The computer will keep printing “dog” and “cat” until you abort the program.
Cls
To make the computer erase everything that was printed in the output window, type type “cls” (which means “CLear the Screen”).
You can type “cls” in the output window or make “cls” be a line in your program (so the computer will erase what’s in the output window). Typing “cls” lets you hide whatever naughty thing you put in the output window.
Blinking Let’s make the screen say “Stop pollution!” and make that message blink.
To do that, flash “Stop pollution!” onto the screen for 2 seconds, then turn that message off for 1 second (so the screen is blank), then flash that message on again. Here’s the program:
repeat
print "Stop pollution!"
wait 200
cls
wait 100
until false
Lines 2 & 3 (which say to print “Stop pollution!” and wait for 2 seconds) flash the message “Stop pollution!” onto the output window and keep it there for 2 seconds. The next pair of lines (cls and wait for 1 second) make the output window become blank for 1 second. Since those lines are all in a repeat loop, the computer does them repeatedly — flash message then blank, flash message then blank, flash message then blank — so your output window becomes a continually flashing sign. It will keep flashing until you abort the program.
Instead of saying “Stop pollution!”, edit that program so it flashes your favorite phrase instead, such as “Save the whales!” or “Marry me!” or “Keepa youse hands offa my computer!” or “Jesus saves — America spends!” or “In God we trust — all others pay cash” or “Please wait — Dr. Doom will be with you shortly” or “Let’s rock!” or whatever else turns you on. Make the computer say whatever you feel emotional about. Like a dog, the computer imitates its master’s personality. If your computer acts “cold and heartless”, it’s because you are!
In the program, you typed just a few lines; but since the top
line says “repeat” (and the bottom line says “until false”), the computer does
an infinite loop. By saying “repeat”, you can make the computer do an infinite
amount of work. Moral: the
computer can turn a finite amount of
human energy into an infinite amount of good. Putting it another
way:
the computer can multiply
your abilities by infinity.
Goto
This program makes the computer print the words “dog” and “cat” repeatedly:
repeat
print "dog";
print "cat";
until false
It makes the computer print:
dogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcat
dogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcat
dogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcatdogcat
etc.
This program does the same thing:
10 print "dog";
20 print "cat";
30 goto 10
The top line (which is numbered 10) makes the computer print “dog”. The next line makes the computer print “cat”. The bottom line makes the computer go back to line 10, so the computer will print “dog” again, then “cat again”, then go back to line 10 again, then print “dog” again, then “cat” again, etc. The computer will print “dog” and “cat” repeatedly, until you abort the program.
This program does the same thing:
(joe) print "dog";
print "cat";
goto joe
The top line (named “joe”) makes the computer print “dog”. The next line makes the computer print “cat”. The bottom line makes the computer go back to the line named “joe”. In that program, “joe” is called the top line’s label.
One word “goto” is one word. You’re supposed to type “goto”, not “go to”. If you accidentally type “go to” instead of “goto”, the computer will gripe by saying “Mistake” when you run the program.
Skip ahead Did you ever dream about having a picnic in the woods? This program expresses that dream:
print "Let's munch"
print "sandwiches under"
print "the trees!"
It makes the computer print:
Let's munch
sandwiches under
the trees!
Let’s turn that dream into a nightmare where we all become giant termites. To do that, insert the shaded items:
10 print "Let's munch"
20 goto 40
30 print "sandwiches under"
40 print "the trees!"
The computer begins by printing “Let’s munch”. Then the computer does goto 40, which makes the computer GO skip down TO line 40, which prints “the trees!” So the program makes the computer print just this:
Let's munch
the trees!
Is “goto” too powerful? The word “goto” gives you great power: if you say GO back TO line 10, the computer will create a loop (as if you’d said “repeat”if you say GO skip down TO line 40, the computer will skip over lines of your program.
Since the word “goto” is so powerful, programmers fear it! Programmers know that the slightest error in using that powerful word will make the programs act very bizarre! Programmers feel more comfortable using milder words instead (such as “repeat”), which are safer and rarely get botched up. Since the word “goto” is scary, many computer teachers prohibit students from using it, and many companies fire programmers who say “goto” instead of “repeat”.
But saying “goto” is fine when you’ve learned how to control the power! Though I’ll usually say “repeat” instead of “goto”, I’ll say “goto” in certain situations where saying “repeat” would be awkward.
Life as an infinite loop
A program that makes the computer repeat the same thing again and again forever is an infinite loop.
Some humans act just like computers. Those humans do the same thing again and again.
Every morning they goto work, and every evening they goto home. Goto work, goto home, goto work, goto home,… Their lives are sheer drudgery. They’re caught in an infinite loop.
Go to your bathroom, get your bottle of shampoo, and look at the instructions on the back. A typical bottle has three instructions:
Lather.
Rinse.
Repeat.
Those instructions say to lather, then rinse, then repeat — which means to lather again, then rinse again, then repeat again — which means to lather again, then rinse again, then repeat again.… If you follow those instructions, you’ll never finish washing your hair! The instructions are an infinite loop! The instructions are a program: they program you to use lots of shampoo! That’s how infinite loops help sell shampoo.
End
To make the computer skip the bottom part of your program, say “end”:
print "She smells"
end
print "of perfume"
When you run that program (by tapping the green triangle), the computer will print “She smells” and then end, without printing “of perfume”.
Suppose you write a program that prints a long message, and you want to run the program several times (so several of your friends get the message). If one of your friends would be offended by the end of your message, send that friend an abridged message! Here’s how: put “end” above the part of the message that you want the computer to omit — or skip past that part by saying “goto”.
Instead of writing “end”, you can write “stop” (which acts like “end” but also makes the computer print “STOP”) or write “quit” (which acts like “end” but also makes the computer close the output window).
Conditions
Here’s how to restrict the computer, so it performs certain lines only under certain conditions.…
If
Let’s write a program so that if the human is less than 18 years old, the computer will say:
You are still a minor.
Here’s the program:
input "How old are you";age
if age<18 print "You are still a minor"
The top line 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:
How old are you?
Try saying you’re 12 years old, by typing a 12, so the screen looks like this:
How old are you? 12
When you finish typing the 12 and press the Enter key at the end of it, the computer will reply:
You are still a minor
Try running that program again, but this time try saying you’re 50 years old instead of 12, so the screen looks like this:
How old are you? 50
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:
if age<18 print "You are still a minor"
In that line, “age<18” is the condition. The whole line is called a conditional statement. If the condition is true (if age is really less than 18), the computer does the action, which comes afterwards:
print "You are still a minor"
Else
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:
input "How old are you";age
if age<18 print "You are still a minor" else print "You are an adult"
In programs, the word “else” means “otherwise”. That program’s bottom line means: if the age is less than 18, 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 —
How old are you? 50
the computer will reply by saying:
You are an adult
Daddy’s always right 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:
input "What's your name";n$
input "What's 2 and 2";a
if n$="Daddy" print "Yes, Daddy is always right": end
if a=4 print "No, 2 and 2 is 22" else print "No, 2 and 2 is 4"
Multi-line if
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”:
if age<18 print "You are still a minor": print "Ah, the joys of youth"
Here’s a more sophisticated way to say the same thing:
if age<18 then
print "You are still a minor"
print "Ah, the joys of youth"
endif
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 multiline if:
The top line must say “if” and “then” (with nothing after “then”).
The computer automatically indents the middle lines, which are called the block and typically say “print”.
The bottom line must say “endif” (which means “end the multi-line if”). The computer automatically unindents it (when you’ve typed it and press the Enter key).
In the middle of a multi-line if, you can say “else”:
if age<18 then
print "You are still a minor"
print "Ah, the joys of youth"
else
print "You are an adult"
print "We can have adult fun"
endif
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”.
Case
Let’s turn your computer into a therapist!
To make the computer ask the patient, “How are you?”, begin the program like this:
input "How are you";a$
Make the computer continue the conversation by responding this way:
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, type this:
case a$ of
when "fine" print "That's good!"
when "lousy" print "Too bad!"
otherwise print "I feel the same way!"
endcase
Like a multi-line if, a case statement consumes several lines. The top line of that case statement tells the computer to analyze a$ and select one of the cases from the list underneath. That list is indented (automatically by the computer) and says:
In the case when a$ is “fine”, print “That’s good!”
In the case when a$ is “lousy”, print “Too bad!”
In the case when a$ is anything else, print “I feel the same way!”
Every case statement’s bottom line must say “endcase”.
Complete program Here’s the complete program:
input "How are you";a$
case a$ of
when "fine" print "That's good!"
when "lousy" print "Too bad!"
otherwise print "I feel the same way!"
endcase
print "I hope you enjoyed your therapy. Now you owe $50."
The top line makes the computer ask the patient, “How are you?” The next several lines are the case 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:
I hope you enjoyed your therapy. Now you owe $50.
In that program, try changing the strings to make the computer print smarter remarks, become a better therapist, and charge even more money.
Vertical case You can write the case statement vertically, like this:
case a$ of
when "fine"
print "That's good!"
when "lousy"
print "Too bad!"
otherwise
print "I feel the same way!"
endcase
That’s useful if you want the computer to print many things.
Error trap This program makes the computer discuss human sexuality:
1 input "Are you male or female";a$
case a$ of
when "male" print "So is Frankenstein!"
when "female" print “So is Mary Poppins!"
otherwise print "Please say male or female!": goto 1
endcase
Line 1 makes the computer ask, “Are you male or female?”
The remaining lines are a case 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 “otherwise”, which makes the computer say “Please say male or female!” and then go back to line 1, which makes the computer ask again, “Are you male or female?”
In that program, the “otherwise” 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 1).
In Basic, “goto” is used rarely: it’s 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 this way:
If human says “yes”, make 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 computer handle that error.
To accomplish all that, put the shaded lines into the program:
1 input "Are you male or female";a$
case a$ of
when "male" print "So is Frankenstein!"
when "female"
print "So is Mary Poppins!"
2 input "Do you like her";b$
case b$ of
when "yes" print "I like her too. She is my mother."
when "no" print "I hate her too. She owes me a dime."
otherwise print "Please say yes or no!": goto 2
endcase
otherwise print "Please say male or female!": goto 1
endcase
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:
1 input "Are you my friend";a$
case a$ of
when "yes" print "That's swell."
when "no" print "Go jump in a lake."
otherwise print "Please say yes or no.": goto 1
endcase
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. A sixth-grade girl wrote this program, to test your honesty:
print "FKGJDFGKJ*#K$JSLF*/#$()$&(IKJNHBGD52:?./KSDJK$E(EF$#/JIK(*"
print "FASDFJKL:JFRFVFJUNJI*&()JNE$#SKI#(!SERF HHW NNWAZ MAME !!!"
print "ZBB%%%%%##)))))FESDFJK DSFE N.D.JJUJASD EHWLKD******"
1 input "Do you understand what I said";a$
case a$ of
when "no" print “Sorry to have bothered you."
when "yes"
print "SSFJSLFKDJFL++++45673456779XSDWFEF/#$&**()--!!ZZXX"
print "###EDFHTG NVFDF MKJK ==+--*$&% #RHFS SES DOPE DSBS"
input "Okay, what did I say";b$
print "You are a liar, a liar, a big fat liar!"
otherwise print "Please say yes or no.": goto 1
endcase
When you run that program, the top 3 lines 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 conditions
You can make the “if” clause very fancy:
“If” clause Meaning
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 dictionary
if b$>"male" If b$ is a word that comes after “male” in dictionary
In the IF statement, the symbols =, <, >, <=, >=, and <> are called relations.
When writing a relation, mathematicians and computerists habitually put the equal sign last:
Right Wrong (but the computer understands it anway)
<= =<
>= =>
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”:
if x=7 or x=8 print "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.
Right: if x=7 or x=8 print "wonderful"
Right because “x=7” and “x=8” are conditions
Wrong: if x=7 or 8 print "wonderful"
Wrong because “8” is not a condition
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”:
if p>5 and p<10 print "tuna fish"
Here’s how to say, “If s is at least 60 and less than 65, print you almost failed”:
if s>=60 and s<65 print "you almost failed"
Here’s how to say, “If n is a number from 1 to 10, print that’s good”:
if n>=1 and n<=10 print "that's good"
Can a computer be President?
To become President of the United States, you need 4 basic skills:
First, you must be a good talker, so you can give effective speeches saying “Vote for me!”, express your views, and make folks do what you want.
But even if you’re a good
talker, you’re useless unless you’re also a
good listener.
You must be able to listen to people’s needs and ask, “What can I do to make
you happy and get you to vote for me?”
But even if you’re a good talker and listener, you’re still useless unless you can make decisions. Should you give more money to poor people? Should you bomb the enemy? Which actions should you take, and under what conditions?
But even if you’re a good talker and listener and decision maker, you still need one more trait to become President: you must be able to take the daily grind of politics. You must, again and again, shake hands, make compromises, and raise funds. You must have the patience to put up with the repetitive monotony of those chores.
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 4 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 4 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 4 magic words. The only question is: how? This book 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 4 concepts: “print”, “input”, “if”, and “goto”. Programming is the ultimate act of scientific reductionism: programmers reduce all of life scientifically to just 4 concepts.
The words that the computer understands are called keywords. The 4 essential keywords are “print”, “input”, “if”, and “goto”.
The computer also understands extra keywords, such as:
wait
repeat, until, false
cls
goto, end
if, else, then, endif
case, of, when, otherwise, endcase
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”, “wait”, “repeat”, 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 you do be explained in terms of “print”, “input”, “if”, and “goto”?
By the time you finish this book, you’ll know!
Exiting a loop
This program plays a guessing game, where the human tries to guess the computer’s favorite color, which is pink:
1 input "What's my favorite color";guess$
if guess$="pink" then
print "Congratulations! You discovered my favorite color."
else
print "No, that's not my favorite color. Try again!"
goto 1
endif
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:
Congratulations! You discovered my favorite color.
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 1, which asks the human again to try guessing the computer’s favorite color.
End Here’s how to write that program without saying “goto”:
repeat
input "What's my favorite color";guess$
if guess$="pink" then
print "Congratulations! You discovered my favorite color."
end
endif
print "No, that's not my favorite color. Try again!"
until false
That new version of the program contains a “repeat” loop. That loop makes the computer repeat 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 repeat Here’s another way to write that program without saying “goto”:
repeat
input "What's my favorite color";guess$
if guess$="pink" exit repeat
print "No, that's not my favorite color. Try again!"
until false
print "Congratulations! You discovered my favorite color."
That program’s “repeat” 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 “repeat” loop; then the computer proceeds to the line underneath the “repeat” loop. That line prints:
Congratulations! You discovered my favorite color.
Until condition Here’s a shorter way to program the guessing game:
repeat
print "You haven't guessed my favorite color yet!"
input "What's my favorite color";guess$
until guess$="pink"
print "Congratulations! You discovered my favorite color."
That program’s “repeat” 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 “until” 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 “until” 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 “until” line.
Saying —
until guess$="pink"
is just a briefer way of saying this pair of lines:
if guess$="pink" exit repeat
until false
For...next
Let’s make the computer print every number from 1 to 20, like this:
1
2
3
4
5
6
7
etc.
20
Here’s the program:
for x=1 to 20
print x
next
The top line (for x=1 to 20) says 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:
1
The next time the computer prints x, the x will be 2, so the computer will print:
2
The computer will print every number from 1 up to 20.
When men meet women
Let’s make the computer print these lyrics:
I saw 2 men
meet 2 women.
Tra-la-la!
I saw 3 men
meet 3 women.
Tra-la-la!
I saw 4 men
meet 4 women.
Tra-la-la!
I saw 5 men
meet 5 women.
Tra-la-la!
They all had a party!
Ha-ha-ha!
To do that, type these lines —
The first line of each verse: print "I saw ";x;" men"
The second line of each verse: print "meet ";x;" women."
The third line of each verse: print "Tra-la-la!"
Blank line under each verse: print
and make x be every number from 2 up to 5:
for x=2 to 5
print "I saw ";x;" men"
print "meet ";x;" women."
print "Tra-la-la!"
next
At the end of the song, print the closing couplet:
for x=2 to 5
print "I saw ";x;" men"
print "meet ";x;" women."
print "Tra-la-la!"
next
print "They all had a party!"
print "Ha-ha-ha!" x
That program makes the computer print the entire song.
Here’s an analysis:
for x=2 to 5
The computer will do the print "I saw ";x;" men"
indented lines repeatedly, print "meet ";x;" women."
for x=2, x=3, x=4, and x=5. print "Tra-la-la!"
next
Then the computer will print "They all had a party!"
print this couplet once. print "Ha-ha-ha!"
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:
for i=2 TO 5
print "I saw ";i;" men"
print "meet ";i;" women."
print "Tra-la-la!"
next
print "They all had a party!"
print "Ha-ha-ha!"
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:
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49
etc.
The square of 20 is 400
To do that, type this line —
print "The square of ";i;" is";i*i
and make i be every number from 3 up to 20, like this:
for i=3 to 20
print "The square of ";i;" is ";i*i
next
Count how many copies
This program, which you saw before, prints “love” on every line of your screen:
repeat
print "love"
until false
That program prints “love” again and again, until you abort the program (by closing the output window or pressing the Esc key).
But what if you want to print “love” just 20 times? This program prints “love” just 20 times:
for i=1 to 20
print "love"
next
As you can see, “for..next” resembles “repeat…until false” but is smarter: while doing for…next, the computer counts!
Count to midnight
This program makes the computer count to midnight:
for i=1 to 11
print i
next
print "midnight"
The computer will print:
1
2
3
4
5
6
7
8
9
10
11
midnight
Print horizontally Let’s make the computer print those numbers horizontally, like this:
1 2 3 4 5 6 7 8 9 10 11 midnight
Here’s the program:
for i=1 to 11
print ;i;" ";
next
print "midnight"
In the “print” line, the first semicolon prevents the computer from putting lots of spaces before each number. The " " makes the computer put a single space after each number. The final semicolon makes the computer print the output all on the same line instead of pressing the Enter key after each number.
If you want the computer to press the Enter key before “midnight”, insert a “print” line:
for i=1 to 11
print ;i;" ";
next
print "midnight"
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:
1 2 3 4 5 6 7 8 9 10 11
midnight
Nested loops Let’s make the computer count to midnight 3 times, like this:
1 2 3 4 5 6 7 8 9 10 11
midnight
1 2 3 4 5 6 7 8 9 10 11
midnight
1 2 3 4 5 6 7 8 9 10 11
midnight
To do that, put the entire program between the words “for” and “next”:
for j=1 to 3
for i=1 to 11
print ;i;" ";
next
print "midnight"
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.
Abnormal exit
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:
print "I'll give you 5 guesses...."
for i=1 to 5
input "What's my favorite color";guess$
if guess$="pink" goto 1
print "No, that's not my favorite color."
next
print "Sorry, your 5 guesses are up! You lose."
end
1 print "Congratulations! You discovered my favorite color."
print "It took you ";i;" guesses."
The top line 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 1, 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:
Congratulations! You discovered my favorite color.
It took you 3 guesses.
If the human’s very first guess is “pink”, the computer prints:
Congratulations! You discovered my favorite color.
It took you 1 guesses.
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 5 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 numbered 1, which is the loop’s abnormal exit.
Here’s how to write that program without saying “goto”:
print "I'll give you 5 guesses...."
for i=1 to 5
input "What's my favorite color";guess$
if guess$="pink" then
print "Congratulations! You discovered my favorite color."
print "It took you ";i;" guesses."
end
endif
print "No, that's not my favorite color."
next
print "Sorry, your 5 guesses are up! You lose."
Step
The “for” statement can be varied:
Statement Meaning
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 3rd 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 3rd 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:
FOR i = 17 TO 5 STEP -1
This program prints a rocket countdown:
for i=10 to 1 step -1
print i
next
print "Blast off!"
The computer will print:
10
9
8
7
6
5
4
3
2
1
Blast off!
This statement is tricky:
for i=5 to 16 step 3
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.
Round-off errors
If the step size is a decimal, the computer might make small errors (called round-off errors), which can add up to a result that’s very wrong.
For example, suppose you say:
for i=5 to 17 step .1
That means you want the last few values of i to be 16.8, 16.9, and 17; but the computer will accidentally make the step size be slightly more than .1, so the computer’s last few values of i will be about 16.80000000000000003 and 16. 90000000000000003. The computer will refuse to do the next number (which would be about 17. 00000000000000003), since you said not to go past 17; so the last i will be 16. 90000000000000003, which isn’t at all what you wanted for the last value!
To make the last i be about 17, make the limit value be slightly more than 17, like this —
for i = 5 to 17.01 step .1
or, better yet, avoid a decimal step size by using this pair of lines instead:
for j=50 to 170
i=j/10
That makes i indeed be 5 then 5.1 then 5.2, etc., up to 17.
Data…read
Let’s make the computer print this message:
I love meat
I love potatoes
I love lettuce
I love tomatoes
I love honey
I love cheese
I love onions
I love peas
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 program’s top, ike this:
data meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas
You must tell the computer to read the data:
data meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas
read a$
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”:
data meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas
read a$
print "I love ";a$
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”:
data meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas
for i=1 to 8
read a$
print "I love ";a$
next
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 no 9th data item exists, and gripe by saying:
Out of data
Let’s make the computer end by printing “Those are the foods I love”, like this:
I love meat
I love potatoes
I love lettuce
I love tomatoes
I love honey
I love cheese
I love onions
I love peas
Those are the foods I love
To make the computer print that ending, put a PRINT line at the end of the program:
data meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas
for i=1 TO 8
read a$
print "I love ";a$
next
print "Those are the foods I love"
End mark
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:
data meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas
data end
repeat
read a$: if a$="end" exit repeat
print "I love ";a$
until false
print "Those are the foods I love"
The second 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, exit from the “repeat” loop.
When the computer exits from the “repeat” loop, the computer prints “Those are the foods I love”. So altogether, the entire program makes the computer print:
I love meat
I love potatoes
I love lettuce
I love tomatoes
I love honey
I love cheese
I love onions
I love peas
Those are the foods I love
The routine that says:
if a$="end" exit repeat
is called the end routine, because the computer does that routine when it reaches the data’s end.
Henry the Eighth Let’s make the computer print this nursery rhyme:
I love ice cream
I love red
I love ocean
I love bed
I love tall grass
I love to wed
I love candles
I love divorce
I love kingdom
I love my horse
I love you
Of course, of course,
For I am Henry the Eighth!
If you own a jump rope, have fun: try to recite that poem while skipping rope!
This program makes the computer recite the poem:
data ice cream,red,ocean,bed,tall grass,to wed
data candles,divorce,my kingdom,my horse,you x
data end
repeat
read a$: if a$="end" exit repeat
print "I love ";a$
if a$="to wed" print
until false
print "Of course, of course," x
print "For I am Henry the Eighth!"
Since the data’s too long to fit on a single line, I’ve put part of the data in the top line and the rest in line 2. 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” print) makes the computer leave a blank line underneath “to
wed”, to mark the first verse’s bottom.
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:
Dear ____________,
person’s name
Let's party in the clubhouse at midnight!
Please bring ____________.
food
Here’s the program:
data Sal,salad,Russ,Russian dressing,Sue,soup,Tom,turkey
data Winnie,wine,Kay,cake,Al,Alka-Seltzer
data end,end
vdu 2
repeat
read person$,food$: if person$="end" exit repeat
print "Dear ";person$;","
print " Let's party in the clubhouse at midnight!"
print "Please bring ";food$;"."
vdu 12
until false
vdu 3
print "I've finished writing the letters."
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).
To make the output appear on paper, say “vdu 2”.
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 print lines print this message onto the screen and paper:
Dear Sal,
Let's party in the clubhouse at midnight!
Please bring salad.
The “vdu 12” makes the computer eject the paper from the printer.
Then the computer comes to “until false”, which sends the computer back to the word “repeat”, 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 “print” lines print onto paper:
Dear Russ,
Let's party in the clubhouse at midnight!
Please bring Russian dressing.
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 the “repeat” loop, so the computer does “vdu 3” (which turns off the printer’s output) and prints this message onto just the screen:
I've finished writing the letters.
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:
Person What the person owes
Bob $537.29
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:
Dear ____________,
person’s name
I just want to remind you...
that you still owe me ____________.
debt
To start writing the program, begin by feeding the computer the data. The final program is the same as the previous program, except for the part I’ve shaded:
data Bob,$537.29,Mike,a dime,Sue,2 golf balls
data Harry,a steak dinner at Mario's,Mommy,a kiss
data end,end
vdu 2
repeat
read person$,debt$: if person$="end" exit repeat
print "Dear ";person$;","
print " I just want to remind you..."
print "that you still owe me ";debt$;"."
vdu 12
until false
vdu 3
print "I've finished writing the letters."
Triplets of data
Suppose you’re running a diet clinic and get these results:
Person Weight before Weight after
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 on your screen:
data Joe,273,219,Mary,412,371,Bill,241,173,Sam,309,198
data end,0,0
repeat
read person$,weight_before,weight_after
if person$=”end” exit repeat
print person$;" weighed ";weight_before;
print " pounds before attending the diet clinic"
print "but weighed just ";weight_after;" pounds afterwards."
print "That's a loss of ";weight_before-weight_after;" pounds."
until false
print "Come to the diet clinic!"
The top line 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 the second line’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:
Joe weighed 273 pounds before attending the diet clinic
but weighed just 219 pounds afterwards.
That's a loss of 54 pounds.
Mary weighed 412 pounds before attending the diet clinic
but weighed just 371 pounds afterwards.
That's a loss of 41 pounds.
Bill weighed 241 pounds before attending the diet clinic
but weighed just 173 pounds afterwards.
That's a loss of 68 pounds.
Sam weighed 309 pounds before attending the diet clinic
but weighed just 198 pounds afterwards.
That's a loss of 111 pounds.
Come to the diet clinic!
Restore
Examine this program:
data love,death,war
1 data chocolate,strawberry
read a$
print a$
restore 1
read a$
print a$
The first “read” makes the computer read the first datum (love), so the first “print” makes the computer print:
love
The next “read” would normally make the computer read the next datum (death); but the ”restore 1” tells the “read” to skip ahead to the data line numbered 1, so the “read” line reads “chocolate” instead. The entire program prints:
love
chocolate
So saying “restore 1” makes the next “read” skip ahead to the data line numbered 1. If you write a new program, saying “restore 2” makes the next “read” skip ahead to data line numbered 2. 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:
data Europe,Asia,Africa,Australia,Antarctica,North America,South America
data end
repeat
read a$: if a$="end" exit repeat
print a$
until false
print "Those are the continents."
That program makes the computer print this message:
Europe
Asia
Africa
Australia
Antarctica
North America
South America
Those are the continents.
Let’s make the computer print that message twice, so the computer prints:
Europe
Asia
Africa
Australia
Antarctica
North America
South America
Those are the continents.
Europe
Asia
Africa
Australia
Antarctica
North America
South Ameruca
Those are the continents.
To do that, put the program in a loop saying “for i=1 to 2”, like this:
data Europe,Asia,Africa,Australia,Antarctica,North America,South America
data end
for i=1 to 2
repeat
read a$: if a$="end" exit repeat
print a$
until false
print "Those are the continents."
print x
restore
NEXT x
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 data’s beginning, so the computer can read and print the data a second time without saying “Out of data”.
Search loop
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:
rouge
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:
In French, it's rouge
The program begins simply:
input "Which color interests you";request$
Next, we must make the computer translate the requested color into French. To do so, feed the computer this English-French dictionary:
English French
white blanc
yellow jaune
orange orange
red rouge
green vert
blue bleu
brown brun
black noir
That dictionary becomes the data:
data white,blanc,yellow,jaune,orange,orange,red,rouge
data green,vert,blue,bleu,brown,brun,black,noir x
input "Which color interests you";request$
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:
read english$,french$
To let the computer look at all the pairs, put that “read” statement in a “repeat” loop. Here’s the complete program:
data white,blanc,yellow,jaune,orange,orange,red,rouge
data green,vert,blue,bleu,brown,brun,black,noir
input "Which color interests you";request$
repeat
read english$,french$
until english$=request$ x
print "In French, it's ";french$
Since the “read” line is in a “repeat” loop, the computer does the “read” line repeatedly. So the computer keeps reading pairs of data, until the computer find the pair of data 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 “until” line says to stop repeating. The computer proceeds to the next line, which makes the computer print:
In French, it's rouge
So altogether, when you run the program the chat can look like this:
Which color interests you? red
In French, it's rouge
Here’s another sample run:
Which color interests you? brown
In French, it's brun
Here’s another:
Which color interests you? pink
Out of data
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 data’s end; and when the computer reaches the end mark, make the computer say “I wasn’t taught that color”:
data white,blanc,yellow,jaune,orange,orange,red,rouge
data green,vert,blue,bleu,brown,brun,black,noir
data end,end
input "Which color interests you";request$
repeat
read english$,french$
if english$="end" print "I wasn't taught that color": end
until english$=request$
print "In French, it’s ";french$
In that program, the “repeat” loop’s purpose is to search through the data, to find data that matches the input. Since the “repeat” loop’s purpose is to search, it’s called a search loop.
The typical search loop has these characteristics:
It starts with “repeat” and ends with “until” and a match condition.
It says to read a pair of data.
It includes an error trap saying what to do if you reach the data’s end because no match found.
Below the loop, say what to print when the match is found.
Above the 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 program’s bottom say to go back to the “input” line:
data white,blanc,yellow,jaune,orange,orange,red,rouge
data green,vert,blue,bleu,brown,brun,black,noir
data end,end
1 input "Which color interests you";request$
restore
repeat
read english$,french$
if english$="end" print "I wasn't taught that color": goto 1
until english$=request$
print "In French, it’s ";french$
goto 1
The word “restore”, which is above the search loop, makes sure 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. But what if the human’s a beginner who hasn’t learned how to abort?
Let the human stop the program more easily by pressing just the Q key to quit:
data white,blanc,yellow,jaune,orange,orange,red,rouge
data green,vert,blue,bleu,brown,brun,black,noir
data end,end
1 input "Which color interests you (press q to quit)";request$
if request$="q" quit
restore
repeat
read english$,french$
if english$="end" print "I wasn't taught that color": goto 1
until english$=request$
print "In French, it’s ";french$
goto 1
Helpful hints
Here are some hints to help you master programming.
Constants & beyond
A numeric constant is a simple number, such as:
0 1 2 8 43.7 -524.6 .003
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 include any arithmetic. For example, since 7+1 includes 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:
"I love you" "76 trombones" "Go away!!!" "xypw exr///746"
A constant is a numeric constant or a string constant:
0 8 -524.6 1.3E5 "I love you" "xypw exr///746"
Variables 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:
a$ b$ y$ z$ my_job_before_promotion$
If the variable stands for a number, it’s called a numeric variable and lacks a dollar sign, like this:
a b y z profit_before_promotion
So all these are variables:
a$ b$ y$ z$ my_job_before.promotion$ a b y z profit_before_promotion
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 (such as “hot”+“dog”).
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 or numeric variable.
Right: goto 100 (100 is a numeric constant.)
Right: goto n (n is a numeric variable.)
Wrong: goto 2+3 (2+3 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 or numeric expressions.
Right: data 8,"Joe",2+4 (8 and “Joe” are constants. 2+4 is a numeric expression.)
Wrong: data "hot"+"dog" (“hot”+“dog” is not a constant or numeric expression.)
In the data statement, if the constant is a string, you can omit the quotation marks (unless the string contains a comma).
Right: DATA "Joe","Mary"
Also right: DATA Joe,Mary
Debugging
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 2 reasons why the computer might print too much:
1. You forgot to insert the word “end” or “exit repeat” into your program.
2. Into a “repeat” loop or “for” loop, you inserted a “print” line that should be outside the loop.
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:
10 print "I'm at line 10. Values are ";b;" ";c;" ";x$
20 print "I'm at line 20. Values are ";b;" ";c;" ";x$
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 containing 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 tappng the Save icon), even though the version contains a bug. After you’ve
played with the shorter versions, retrieve the original (by tapping the Load
icon) 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.
Error messages
If the computer can’t obey your command, the computer will print an error message. The following error message are the most common.…
If you say “prind” instead of “print”, the computer will say:
Mistake
That means the computer hasn’t the faintest idea of what you’re talking about!
If the computer says you have a “Mistake”, 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.
If you type a left parenthesis but forget to type the right parenthesis that matches it, the computer will say:
Missing )
If you try to say “print 5+2” but forget to type the 2, the computer will say:
Syntax error
Numeric errors If the answer to a calculation is a bigger number than the computer can handle, the computer will say:
Number too big
If you try to divide by zero, the computer will say:
Division by zero
Logic errors If you say “goto 10”, the computer tries to find a line numbered 10. If there’s no line numbered 10, the computer will say:
No such line
If a line says to use x (such as “print x” or “print 3+x” “y=3+x” or “goto x”) but you haven’t said how much x is yet, the computer will say:
No such variable
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:
Out of data
The computer handles 2 major types of info: numbers & strings. If you feed the computer the wrong type of info – 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:
Type mismatch
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 give that gripe. So when the computer gives that gripe, it usually means you forgot a quotation mark or a dollar sign.
Pause
Magicians often say, “The hand is quicker than the eye.” The computer’s the ultimate magician: the computer can print info on the output window much faster than you can read it.
When the computer is printing faster than you can read, make it pause. Here’s how.…
Tap the program window (which is partly hidden behind the output window). Then tap the Pause icon (which looks like “;”).
The computer will pause, to let you read what’s on the screen.
Tap the output window. Read what’s in it.
When you’ve finished reading what’s in the output window and want the computer to stop pausing, tap the Pause icon again. 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 icon 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).
Apostrophe
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:
'This program is a dumb example, written by Russ.
'It was written on Halloween, under a full moon.
c=40 'because Russ has 40 computers
h=23 'because 23 of his computers are haunted
print "Russ has ";c-h;" unhaunted computers”
When you run that program, the computer ignores everything that’s to the right of an apostrophe. So the computer ignores lines 1 & 2; in lines 3 & 4, the computer ignores the “because…”. Since c is 40, and h is 23, the bottom line makes the computer print:
Russ has 17 unhaunted computers
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 in the program window the rest of the program. Though the comments appear in the program, they don’t affect the run.
When the computer sees an apostrophe, it thinks the apostrophe marks the beginning of a comment (unless the apostrophe is in a string or “data” statement or “print” statement).
Loop techniques
Here’s a strange program:
x=9
x=4+x
print x
The second 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:
13
Let’s look at that program more closely. The top 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:
b=6
b=b+1
print b*2
The second 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:
14
In that program, the top 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:
j=500
j=j-1
print j
The top 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:
499
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:
3
4
5
6
7
8
etc.
This program does it, by a special technique:
c=3
repeat
print c
c=c+1
until false
In that program, c is called the counter, because it helps the computer count.
The top line says c starts at 3. The “print” line makes the computer print c, so the computer prints:
3
The next line (c=c+1) increases c by adding 1 to it, so c becomes 4. The “until” line sends the computer back to the “print” line, which prints the new value of c:
4
Then the computer comes to the “c=c+1” again, which increases c again, so c becomes 5. The “until” line sends the computer back again to the “print” line, which prints:
5
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 to make the computer count:
Start c at some value (such as 3).
Then write a “repeat” loop.
In the “repeat” loop, make the computer use c (such as by saying “print c”) and increase c (by saying “c=c+1).
This program makes the computer count, starting at 1:
c=1
repeat
print c
c=c+1
until false
The computer will print 1, 2, 3, 4, etc.
This program makes the computer count, starting at 0:
c=0
repeat
print c
c=c+1
until false
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:
Question Correct answer
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:
data What's the capital of Nevada,Carson City
data What's the chemical symbol for iron,Fe
data What word means 'brother or sister',sibling
data What was Beethoven's first name,Ludwig
data How many cups are in a quart,4
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:
repeat
read question$,answer$
until false
Here’s the complete program:
data What's the capital of Nevada,Carson City
data What's the chemical symbol for iron,Fe
data What word means 'brother or sister',sibling
data What was Beethoven's first name,Ludwig
data How many cups are in a quart,4
data end,end
repeat
read question$,answer$: if question$="end" exit repeat
print question$; x
input response$ x
if response$=answer$ then x
print "Correct!" x
else x
print "No, the answer is: ";answer$
endif x
until false
print "I hope you enjoyed the quiz!"
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 data’s end, the computer exits the “repeat: loop and prints “I hope you enjoyed the quiz!”
Here’s a sample run, where I’ve underlined the parts typed by the human:
What's the capital of Nevada? Las Vegas
No, the answer is: Carson City
What's the chemical symbol for iron??? Fe
Correct!
What word means 'brother or sister'? I give up
No, the answer is: sibling
What was Beethoven's first name? Ludvig
No, the answer is: Ludwig
How many cups are in a quart? 4
Correct!
I hope you enjoyed the quiz!
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:
data What's the capital of Nevada,Carson City
data What's the chemical symbol for iron,Fe
data What word means 'brother or sister',sibling
data What was Beethoven's first name,Ludwig
data How many cups are in a quart,4
data end,end
c=0
repeat
read question$,answer$: if question$="end" exit repeat
print question$;
input response$
if response$=answer$ then
print "Correct!"
c=c+1
else
print "No, the answer is: ";answer$
endif
until false
print "I hope you enjoyed the quiz!"
print "You answered ";c;" of the questions correctly."
At the program’s beginning, 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:
You answered 2 of the questions correctly.
It would be nicer to print —
You answered 2 of the 5 questions correctly.
Your score is 40 %
or, if the quiz were changed to include 8 questions:
You answered 2 of the 8 questions correctly.
Your score is 25 %
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:
data What's the capital of Nevada,Carson City
data What's the chemical symbol for iron,Fe
data What word means 'brother or sister',sibling
data What was Beethoven's first name,Ludwig
data How many cups are in a quart,4
data end,end
q=0
c=0
repeat
read question$,answer$: if question$="end" exit repeat
print question$;
q=q+1
input response$
if response$=answer$ then
print "Correct!"
c=c+1
else
print "No, the answer is: ";answer$
endif
until false
print "I hope you enjoyed the quiz!"
print "You answered ";c;" of the ";q;" questions correctly."
print "Your score is ";c/q*100;"%"
Summing Let’s make the computer imitate an adding machine, so a run looks like this:
Now the sum is 0
What number do you want to add to the sum? 5
Now the sum is 5
What number do you want to add to the sum? 3
Now the sum is 8
What number do you want to add to the sum? 6.1
Now the sum is 14.1
What number do you want to add to the sum? -10
Now the sum is 4.1
etc.
Here’s the program:
s=0
repeat
print "Now the sum is";s
input "What number do you want to add to the sum";x
s=s+x
until false
The top 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 “until” 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 to make the computer find a sum:
Start s at 0.
Then write a “repeat” loop.
In the “repeat” 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 you write, a $25 penalty for each check that bounces, and pays no interest on money you’ve deposited.
This program makes the computer imitate such a bank.…
s=0
repeat
print "Your checking account contains";s
1 input "Press d (to make a deposit) or c (to write a check)";a$
case a$ of
when "d"
input "How much money do you want to deposit";d
s=s+d
when "c"
input "How much money do you want the check for";c
c=c+.2
if c<=s then
print "Okay"
s=s-c
else
print "That check bounced!"
s=s-25
endif
otherwise
print "Please press d or c"
goto 1
endcase
until false
In that program, the total amount of money in the checking account is called the sum, s. The top 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 $25 penalty.
That program is nasty to customers:
For example, suppose you have $1 in your account, and you try to write a check for 85¢. Since 85¢ + the 20¢ service charge = $1.05, which is more than you have in your account, your check will bounce, and you’ll be penalized $25. That makes your balance become negative $24, and the bank will demand you pay the bank $24 — just because you wrote a check for 85¢!
Another nuisance is when you leave town permanently and want to close your account. If your account contains $1, you can’t get your dollar back! The most you can withdraw is 80¢, because 80¢ + the 20¢ service charge = $1.
That nasty program makes customers hate the bank — and hate the computer! The bank should make the program friendlier. Here’s how:
To stop accusing the customer of owing money, the bank should change any negative sum to 0, by inserting this line just under the word “repeat”:
if s<0 s=0
Also, to be friendly, the bank should ignore the 20¢ service charge when deciding whether a check will clear. So the bank should eliminate the line saying “c = c+.2”. On the other hand, if the check does clear, the bank should impose the 20¢ service charge afterwards, by changing the “s=s-c” to “s = s-c-.2”.
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; $25 might be more reasonable.
Moral: the hardest thing about programming is choosing your goal — deciding what you WANT the computer to do.
Series Let’s make the computer add together all the numbers from 7 to 100, so that the computer finds the sum of this series: 7 + 8 + 9 + ... + 100. Here’s how.
Start the sum at 0: s=0
Make i go from 7 to 100: for i=7 TO 100
Increase sum, by adding each i to it: s=s+i
next
Print the final sum (which is 5029): print s
Let’s make the computer add together the squares of all the numbers from 7 to 100, so that the computer finds the sum of this series: (7 squared) + (8 squared) + (9 squared) +… + (100 squared). Here’s how:
s=0
for i=7 to 100
s=s+i*i
next
print s
It’s the same as the previous program, except that indented line says to add i*i instead of i. The bottom line prints the final sum, which is 338259.
Data sums This program adds together the numbers in the data:
data 5,3,6.1,etc.
data 0
s=0
repeat
read x: if x=0 exit repeat
s=s+x
until false
print s
The “data” line contains the numbers to be added. The “data 0” is an end mark. The line saying “s=0” starts the sum at 0. The “read” statement reads an x from the data. The next line (s=s+x) adds x to the sum. The “until” line makes the computer repeat that procedure for every x. When the computer has read all the data and reaches the end mark (0), the x becomes 0, so the computer will exit the “repeat” loop and print the final sum, s.
Pretty output
Here’s how to make your output prettier.
Zones
The output window is divided into zones. Each zone is 10 characters wide. A comma makes the computer hop to the next zone:
print "sin","king"
That makes the computer print "sin" then hop to the next zone, where it prints “king”, like this:
sin king
Here are the words of a poet who drank too much and is feeling spaced out:
print "love","cries","out"
The computer will print “love” in the first zone, “cries” in the second zone, and “out” in the third zone, so the words are spaced out like this:
love cries out
This program tells a bad joke:
print "You're ugly!","I'm joking!"
The computer will print “You’re ugly!” That string has 12 characters. Its first 10 characters are in the first zone; its remaining 2 characters are in the second zone. Then the comma makes the computer hop to the next zone (the third zone), where the computer prints “I’m joking!”, like this:
You're ugly! I’m joking!
When you combine commas with semicolons, you can get weird results:
print "eat","me";"at";"ball","no";"w"
That line contains commas and semicolons. A comma makes the computer hop to a new zone, but a semicolon does not make the computer hop. The computer will print “eat”, then hop to the second zone, then print “me” and “at” and “ball”, then hop to the third zone, then print “no” and “w”. Altogether, the computer will print:
eat meatball now
Here’s a strange example:
print "underwater","ing"
The computer prints “underwater”, which contains 10 characters, so it fills up the first zone. Then the computer is supposed to print “ing” at the beginning of a new zone, but the computer’s already at the beginning of the second zone, so the computer prints:
Underwatering
Skip a zone You can make the computer skip over a zone:
print "Joe"," ","loves Sue"
The computer will print “Joe” in the first zone, a blank space in the second zone, and “loves Sue” in the third zone, like this:
Joe loves Sue
Numbers Compare these 4 “print” statements:
print 53
print 53;986
print 53;" ";986
print 53,986
The first “print” statement makes the computer print the number 53. The computer wants to make every number be 10 characters wide, so it puts 8 spaces before the digits, like this:
53
In the second “print” statement, the semicolon prevents the computer from putting blank spaces before the 986, so the computer prints:
53986
In the third “print” statement, the " " forces the computer to put a blank space before the 986, so the computer prints:
53 986
In the fourth “print” statement, the comma makes the computer go to the beginning of a new zone; but after printing the 53, the computer’s already at the beginning of the second zone, so the computer prints 986 without hopping to another zone. Since there’s no semicolon, the computer prints 986 as 10 characters, by putting 7 spaces before it, like this:
57 986
Tables This program prints a list of words and their opposites:
print "good","bad"
print "black","white"
print "parent","child"
print "he","she"
The top line makes the computer print “good”, then hop to the next zone, then print “bad”. Altogether, the computer will print:
good bad
black white
parent child
he she
The first zone contains a column of words; the second zone contains the opposites. Altogether, the computer’s printing looks like a table. So to make a table easily, use zones, by putting commas in your program.
Let’s make the computer print this table:
Number Square
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
Here’s the program:
print " Number Square"
for i=3 to 10
print i,i*i
next
In the “for…next” loop, the “print” line makes the computer print each number in the first zone and its square in the second zone. (The computer puts enough spaces before the digits to make each number consume 10 characters.) The top line makes the computer print the headings (“Number” and “Square”) with enough spaces so the headings are centered over the numbers below.
Tab
When the computer puts a line of information on your screen, the leftmost character in the line is said to be at position 0. The next character in the line is said to be at position 1. Then comes position 2.
This program makes the computer skip to position 6 and then print “hot”:
print tab(6);"hot"
The computer will print:
hot
Here’s a fancier example:
print tab(6);"hot";tab(13);"buns"
The computer will skip to position 6, then print “hot”, then skip to position 13, then print “buns”:
hot buns
Diagonal This program prints a diagonal line:
for i=0 to 8
print tab(i);"*"
next
The “for” line says to do the indented line many times. The first time the computer does the indented line, the i is 0, so the computer prints an asterisk at position 0:
*
The next time, the i is 1, so the computer skips to position 1 and prints an asterisk:
*
The next time, the i is 2, so the computer skips to position 2 and prints an asterisk:
*
Altogether, the program makes the computer print this picture:
*
*
*
*
*
*
*
*
*
2-dimensional tab In the output window, the top line is called line 0; underneath it is line 1; then comes line 2; etc.
To make the computer print the word “drown” so that “drown” begins at position 6 of line 2, type this:
print tab(6,2);"drown"
The computer will print the word’s first letter (d) at the 6th position of line 2. The computer will print the rest of the word afterwards, still on line 2.
If words were already printed on the output screen there,
“drown” will cover them up. Covering up can be done by a
2-dimensional tab, such as tab (6,2), but not by a plain tab, such as tab(6),
which refuses to erase previous typing.
Pixels
The image on screen is called the picture. If you stare at the picture closely, you’ll see the picture’s composed of thousands of tiny dots. Each dot, which is a tiny rectangle, is called a picture’s element, or pic’s el, or pixel, or pel.
Coordinates The dot in the output window’s bottom-left corner is called pixel (0,0). Just to the right of it is pixel (1,0). Then comes pixel (2,0), etc.
Above pixel (0,0) is pixel (0,1). Farther up is pixel (0,2).
Each pixel’s name consists of two numbers in parentheses. The
first number is the X
coordinate; the second number is the
Y coordinate.
For example, if you’re talking about pixel (4,3), its X coordinate is 4; its Y
coordinate is 3.
The X coordinate tells how far to the right the pixel is. The Y coordinate tells how far up. So pixel (4,3) is the pixel that’s 4 to the right and 3 up.
Circle This command draws a circle whose center is pixel (200,300) and radius is 50:
circle 200,300,50
Ellipse This command draws an ellipse (oval) whose center is pixel (200,300), horizontal radius is 50, and vertical radius is 25:
ellipse 200,300,50,25
Rectangle This command draws a rectangle (box) whose bottom-left corner is pixel (200,300), width is 80, and height is 50:
rectangle 200,300,80,50
To draw a square, give the rectangle command but don’t mention the rectangle’s height:
rectangle 200,300,80
The computer will assume you want the height to be the same as the width.
Fill If you say “circle fill” instead of “circle” or say
“ellipse fill”
instead of “ellipse” or say “rectangle
fill” instead of “rectangle”, the computer will draw the shape
but also fill in the shape’s middle (the shape’s interior).
For example, this command draws a circle whose center is pixel (200,300) and radius is 50 and will also fill the circle’s middle:
circle fill 200,300,50
Line This command draws a diagonal line from pixel (200,300) to pixel (500,350):
line 200,300,500,350
This command draws a diagonal line from the previous line’s end to pixel (600,400):
draw 600,400
Plot This command puts a tiny dot at pixel (100,200):
plot 100,200
Colors
Normally, the computer prints & graphs everything in dark black, but you can switch to a different color. You can use 16 colors:
0. dark black (pure black) 8. bright black (dark gray)
1. dark red 9. bright red
2. dark green 10. bright green
3. dark yellow (gold) 11. bright yellow (pure yellow)
4. dark blue 12. bright blue
5. dark magenta (dark purplish red) 13. bright magenta (bright purplish red)
6. dark cyan (dark greenish blue) 14. bright cyan (bright greenish blue)
7. dark white (light gray) 15. bright white (pure white)
This program prints “I’m sad” in dark blue (which is color #4):
colour 4
print "I'm sad"
Since BBC Basic was invented by the British, it wants you to write “colour”, not “color” (which is American). If you accidentally write “color”, BBC Basic will automatically change it to “colour” when you press the Enter key.
Once you pick a color, the computer will keep printing in that color until you switch to a different color (or close the output window).
This program prints “I love you” in bright red (which is color #9):
colour 9
print "I love you"
Background color Normally, the computer prints on a pure white background, but you can change the background color by adding 128. This program prints “I love you” in bright red on a bright yellow background:
colour 9: colour 11+128
print "I love you"
Graphics colors The “colour” command alters the colors of text, not graphics. To alter the colors of graphics (pixel pictures), say “gcol” instead of “colour”. To change the graphics’ background color, you must also say “clg” (which means “clear the graphics screen”). This program creates a bright red circle on a bright yellow background:
gcol 9: gcol 11+128: clg
circle 200,300,50
Sounds
This program produces a normal sound:
sound 1,-15,4*25,20*3
The sound is loud, middle C (on the piano), and lasts for 3 seconds. Try it: run that program!
Here’s what those shaded numbers mean.…
The “15” is how loud the sound will be.
If you switch the 15 to 1, the sound will be much softer.
You can pick any integer from 0 (which means “silent”) to 15 (which means “as loud as possible”).
You must put a minus sign before your number.
The “3” is how long the sound will last: how many seconds.
If you want the sound to last longer than 3 seconds, switch to a number bigger than 3.
For example, if you want the sound to last for 4 seconds, switch the 3 to a 4.
If you want the sound to last for 1 second, switch the 3 to a 1.
If you want the sound to last for half a second, switch the 3 to .5.
(The 20 is because BBC Basic measures the sound length in 20ths of a second.)
The “25” is the sound’s pitch (how high the note will be).
25 is the piano’s middle C.
26 is the piano’s next note (C sharp).
27 is the piano’s note after that (D).
24 is the piano’s note below middle C; it’s B.
23 is the piano’s note below that (B flat).
You can pick any number between .25 and 63.75.
(The 4 is because BBC Basic measures the pitch in quarters of a semitone.)
The “1” is the sound’s voice number. BBC Basic can produce 3-part harmony. This program makes the first voice sing middle C (pitch #25) while the second voice sings E (pitch #29) and the third voice sings G (pitch # 32), to produce a chord:
sound 1,-15,4*25,20*3
sound 2,-15,4*29,20*3
sound 3,-15,4*32,20*3
Decimal places
Suppose you want to add $12.47 to $1.03. The correct answer is $13.50. This almost works:
print 12.47+1.03
It makes the computer print:
13.5
But instead of 13.5, let’s make the computer print 13.50.
This Print
Format command makes the computer print
2 digits after each decimal point —
@%=131082+256*2
so this program makes the computer print 13.50:
@%=131082+256*2
print 12.47+1.03
The computer will print:
13.50
Here’s a contradiction:
@%=131082+256*2
print 86.239
The bottom line says to print 86.239, but the top line says to print just 2 digits after the decimal point, so the computer will round 86.239 and print:
86.24
In the Print Format command, the last digit (the 2) says how many digits to print after the decimal point. If you want 3 digits after the decimal point instead just 2, change the 2 to 3, like this:
@%=131082+256*3
The Print Format command affects all future printing, until you close the output window or give a different Print Format command or give this Cancel Print Format command —
@%=2314
which returns the printing to normal.
Fancy calculations
You can do fancy calculations — easily!
Pi
A circle’s circumference divided by its diameter is called “pi” (which Americans pronounce the same as the word “pie”). It’s approximately 3.14159265. This program makes the computer print 3.14159265:
print pi
Exponents
Try typing this program:
print 4^3
To type the symbol ^, do this: while holding down the Shift key, tap this key:
^ 6 |
That symbol (^) is called a caret.
In that program, the “4^3” makes the computer use the number 4, three times.
The computer will multiply together those three 4’s, like this: 4 times 4 times
4. Since
“4 times 4 times 4” is 64, the computer will print:
64
In the expression “4^3”, the 4 is called the base; the 3 is called the exponent.
Here’s another example:
print 10^6
The “10^6” makes the computer use the number 10, six times. The
computer will multiply together those six 10’s (like this:
10 times 10 times 10 times 10 times 10 times 10) and print the answer:
1000000
Here’s another example:
PRINT 3^2
The “3^2” makes the computer use the number 3, two times. The
computer will multiply together those two 3’s (like this:
3 times 3) and print the answer:
9
Order of operations The symbols +, -, *, /, and ^ are all called operations.
To solve a problem, the computer uses the three-step process taught in algebra and the “new math”. For example, suppose you say:
print 70-3^2+8/2*3
The computer will not begin by subtracting 3 from 70; instead, it will use the three-step process:
The problem is 70-3^2+8/2*3
Step 1: get rid of ^. Now the problem is 70- 9 +8/2*3
Step 2: get rid of * and /. Now the problem is 70- 9 + 12
Step 3: get rid of + and -. The answer is 73
In each step, it looks from left to right. For example, in step 2, it sees / and gets rid of it before it sees *.
Speed Though exponents are fun, the computer handles them slowly. For example, the computer handles 3^2 slower than 3*3. So for fast calculations, say 3*3 instead of 3^2.
Square roots What positive number, when multiplied by itself, gives 9? The answer is 3, because 3 times itself is 9.
3 squared is 9. 3 is called the square root of 9.
To make the computer deduce the square root of 9, type this:
print sqr(9)
The computer will print 3.
The symbol “sqr” is called a function. The number in parentheses (9) is called the function’s input (or argument or parameter). The answer, which is 3, is called the function’s output (or value).
The sqr(9) gives the same answer as 9^.5. The computer handles sqr(9) faster than 9^.5.
BBC Basic lets you omit the parentheses: instead of typing “sqr(9)”, you can type just “sqr9” or “sqr 9”, and the computer will still print the correct answer (which is 3).
Cube roots What number, when multiplied by itself and then multiplied by itself again, gives 64? The answer is 4, because 4 times 4 times 4 is 64. The answer (4) is called the cube root of 64.
Here’s how to make the computer find the cube root of 64:
print 64^(1/3)
The computer will print 4.
Exp The letter “e” stands for a special number, which is approximately 2.718281828459045. You can memorize that number easily, if you pair the digits:
2.7 18 28 18 28 45 90 45
That weird number is important in calculus, radioactivity, biological growth, and other areas of science. It’s calculated by this formula:
1 1 1 1 1 x
e = 1 + + + + + + ...
1 1*2 1*2*3 1*2*3*4 1*2*3*4*5
Therefore:
1 1 1 1 x
e = 1 + 1 + + + + + ...
2 6 24 120
Exp(x) means ex. For example, exp(3) means e3, which is e*e*e, which is:
2.718281828459045 * 2.718281828459045 * 2.718281828459045
Exp(4) means e4, which is e*e*e*e. Exp(3.1) means e3.1, which is more than e3 but less than e4.
Here’s a practical application. Suppose you put $800 in a savings account, and the bank promises to give you 5% annual interest “compounded continuously”. How much money will you have at the end of the year? The answer is 800*exp(.05).
Logarithms Suppose you write 1 with a lot of zeros afterwards, like this:
100000
The logarithm of that number is how many zeros you wrote. So if you say —
print log(100000)
the computer will count the zeros and print how many there are; the computer will print:
5
Here are more examples:
log(10) is 1
log(100) is 2
log(1000) is 3
log(10000) is 4
log(100000) is 5
How much is log(7852)? Since 7852 is between 1000 and 10000, its log is between 3 and 4. If you say —
print log(7852)
the computer will print a number between 3 and 4; it will print:
3.89498029
I’ve been explaining the common log, which is used in chemistry. It’s also called the log base 10. Mathematicians write it as “log10”. For example, they say log10 100000 is 5.
A different kind of log, used in calculus, is called the
natural log.
It’s also called the log
base e. Mathematicians write it as “loge” or “LN” or “ln”. It’s about
2.3 times the common log. For example, if you say —
print ln(100000)
the computer will print a number that’s about 2.3 times log(100000), so it will print about “2.3 times 5”, which is 11.5. It will print:
11.5129255
Here are some powers of 2:
x 2x
1 2
2 4
3 8
4 16
5 32
6 64
To compute the logarithm-base-2 of a number, find the number in the right-hand column; the answer’s in the left column. For example, the logarithm-base-2 of 32 is 5. The logarithm-base-2 of 15 is slightly less than 4.
The logarithm-base-2 of 64 is 6. That fact is written:
log2 64 is 6
It’s also written:
log 64
is 6
log 2
To make the computer find the logarithm-base-2 of 64, say:
print log(64)/log(2)
The computer will print 6.
Contrasts
The computer’s notation resembles that of arithmetic and algebra, but beware of these contrasts.…
Multiplication To make the computer multiply, you must type an asterisk:
Traditional notation Computer notation
2n 2*n
5(n+m) 5*(n+m)
nm n*m
Exponents Put an exponent in parentheses, if it contains an operation:
Traditional notation Computer notation
xn+2 x^(n+2)
x3n x^(3*n)
52/3 5^(2/3)
4
23 2^(3^4)
Fractions Put a fraction’s numerator in parentheses, if it contains addition or subtraction:
Traditional notation Computer notation
a+b
(a+b)/c
c
k-20
(k-20)/6
6
Put a denominator in parentheses, if it contains addition, subtraction, multiplication, or division:
Traditional notation Computer notation
5 x
5/(3+x)
3+x
5a3
5*a^3/(4*b)
4b
Mixed numbers A mixed number is a number that contains a fraction. For example, 9½ is a mixed number. When you write a mixed number, put a plus sign before its fraction:
Traditional notation Computer notation
9½ 9+1/2
If you’re using the mixed number in a further calculation, put the mixed number in parentheses:
Traditional notation Computer notation
7 - 2¼ 7-(2+1/4)
Stripping
Sometimes the computer prints too much info: you wish the computer would print less, to save yourself the agony of reading excess info irrelevant to your needs. Whenever the computer prints too much info about a numerical answer, say “abs”, “int”, or “sgn”.
Abs removes any minus sign. For example, the abs of -3.89 is 3.89. So if you say print abs(-3.89), the computer will print just 3.89.
Int rounds the number DOWN to an integer that’s LOWER. For example, the int of 3.89 is 3 (because 3 is an integer that’s lower than 3.89); the int of -3.89 is -4 (because -4 is lower than -3.89).
Sgn removes ALL the digits and replaces them with a 1 — unless the number is 0. For example, the sgn of 3.89 is 1. The sgn of -3.89 is -1. The SGN of 0 is just 0.
Abs, int, and sgn are called stripping functions or strippers or diet functions or diet pills, because they strip away the number’s excess fat and reveal just the fundamentals that interest you.
Here are more details about those three functions.…
Abs To find the absolute value of a negative number, just omit the number’s minus sign. For example, the absolute value of -7 is 7.
The absolute value of a positive number is the number itself. For example, the absolute value of 7 is 7. The absolute value of 0 is 0.
To make the computer find the absolute value of -7, type this:
print abs(-7)
The computer will print:
7
Like sqr, abs is a function: you’re supposed to put parentheses after the “abs”, though in BBC Basic the parentheses are optional.
Since abs omits the minus sign, abs turns negative numbers into positive numbers. Use abs whenever you insist that an answer be positive.
For example, abs helps solve math & physics problems about “distance”, since the “distance” between two points is always a positive number and cannot be negative.
This program computes the distance between two numbers:
print "I will find the distance between two numbers."
input "What's the first number";x
input "What's the second number";y
print "The distance between those numbers is";abs(x-y)
When you run that program, suppose you say that the first number is 4 and the second number is 7. Since x is 4, and y is 7, the distance between those two numbers is abs(4-7), which is abs(-3), which is 3.
If you reverse those two numbers, so x is 7 and y is 4, the distance between them is abs(7-4), which is abs(3), which is still 3.
Int Int turns a number into an integer (a number without decimal digits).
Int rounds a number down to an integer that’s lower. For example:
The int of 3.9 is 3 (because 3 is an integer that’s lower than 3.9).
The int of -3.9 is -4 (because a temperature of -4 is lower and colder than a temperature of -3.9).
The int of 7 is simply 7.
To explore further the mysteries of rounding, run this program:
input "What's your favorite number";x
print "Your number rounded down is";int(x)
print "Your number rounded up is"; -int(-x)
print "Your number rounded to the nearest integer is"; int(x+.5)
The top line asks you to type a number x.
The next line prints your number rounded down. For example, if you input 3.9, the computer prints 3.
The next line, PRINT -INT(-x), prints your number rounded up. For example if you input 3.9, the computer prints 4.
The bottom line prints your number rounded to the nearest integer. For example, if you input 3.9, the computer will print 4.
Here’s the rule: if x is a number, int(x) rounds x down; -int(-x) rounds x up; int(x+.5) rounds x to the nearest integer.
Rounding down and rounding up are useful in the supermarket:
Suppose some items are marked “30¢ each”, and you have just two dollars. How many can you buy? Two dollars divided by 30¢ is 6.66667; rounding down to an integer, you can buy 6.
Suppose some items are marked “3 for a dollar”, and you want to buy just one of them. How much will the supermarket charge you? One dollar divided by 3 is 33.3333¢; rounding up to an integer, you will be charged 34¢.
By using int, you can do fancier kinds of rounding:
to round x to the nearest thousand, ask for int(x/1000+.5)*1000
to round x to the nearest thousandth, ask for int(x/.001+.5)*.001
This program rounds a number, so that it will have just a few digits after the decimal point:
input "What's your favorite number";x
input "How many digits would you like after its decimal point";d
b=10^-d
print "Your number rounded is ";int(x/b+.5)*b
Here’s a sample run:
What's your favorite number? 4.28631
How many digits would you like after its decimal point? 2
Your number rounded is 4.29
Sgn If a number is negative, its sign is -1. For example, the sign of -546 is -1.
If a number is positive, its sign is +1. For example the sign of 8231 is +1.
The sign of 0 is 0.
The computer’s abbreviation for “sign” is “sgn”. So if you say —
print sgn(-546)
the computer will print the sign of -546; it will print -1.
If you say —
PRINT sgn(8231)
the computer will print the sign of 8231; it will print 1.
If you say —
print sgn(0)
the computer will print the sign of 0; it will print 0.
Sgn is the opposite of abs. Let’s see what both functions do to -7.2. Abs removes the minus sign, but leaves the digits:
abs(-7.2) is 7.2
Sgn removes the digits, but leaves the minus sign:
sgn(-7.2) is -1
The Latin word for sign is signum. Most mathematicians prefer to
talk in Latin — they say “signum” instead of “sign” — because the English word
“sign” sounds too much like the trigonometry word “sine”.
So mathematicians call sgn the
signum function.
Random numbers
Usually, the computer is predictable: it does exactly what you say. But sometimes, you want the computer to be unpredictable.
For example, if you’re going to play a game of cards with the computer and tell the computer to deal, you want the cards dealt to be unpredictable. If the cards were predictable — if you could figure out exactly which cards you and the computer would be dealt — the game would be boring.
In many other games too, you want the computer to be unpredictable, to “surprise” you. Without an element of surprise, the game would be boring.
Being unpredictable increases the pleasure you derive from games — and from art. To make the computer act artistic, and create a new original masterpiece that’s a “work of art”, you need a way to make the computer get a “flash of inspiration”. Flashes of inspiration aren’t predictable: they’re surprises.
Here’s how to make the computer act unpredictably.…
Random integers This program makes the computer print an unpredictable number from 1 to 5:
print rnd(5)
Unpredictable numbers are called random numbers. That program makes the computer print a random number from 1 to 5, so the computer will print 1, 2, 3, 4, or 5. The computer’s choice will be a surprise.
For example, when you run that program, the computer might
print 3. If you run the program a second time, the computer might print a
different number
(1 or 2 or 4 or 5), or it might print the same number (3). You can’t predict
which number the computer will print. The only thing you can be sure of is: the
number will be from 1 to 5.
To make the computer print many such random numbers, say “goto”:
1 print rnd(5)
goto 1
The computer will print many numbers, like this:
3
2
4
4
1
3
5
2
2
5
etc.
Each number will be 1 or 2 or 3 or 4 or 5. The order in which the computer prints them is unpredictable. The pogram’s an infinite loop: it won’t stop until you abort it. If you run the program again, the pattern will be different; for example, it might be:
1
4
3
3
2
5
1
1
2
etc.
When you run that program, the numbers will fly up the screen faster than you can read. To make the numbers easier to read, make the computer pause after each number, by telling the computer to wait a second (100 centiseconds):
1 print rnd(5)
wait 100
goto 1
Guessing game This program plays a guessing game:
print "I'm thinking of a number from 1 to 10."
computer_number=rnd(10)
1 input "What do you think my number is";guess
if guess<computer_number print "Your guess is too low.": goto 1
if guess>computer.number print "Your guess is too high.": goto 1
print "Congratulations! You found my number!"
The top line makes the computer say:
I'm thinking of a number from 1 to 10.
The next line makes the computer think of a random number from 1 to 10; the computer’s number is called “computer_number”. The “input” line asks the human to guess the number.
If the guess is less than the computer’s number, the first “if” line makes the computer say “Your guess is too low” and then goto 1, which lets the human guess again. If the guess is greater than the computer’s number, the bottom “if” line makes the computer say “Your guess is too high” and then goto 1.
When the human guesses correctly, the computer arrives at the bottom line, which prints:
Congratulations! You found my number!
Here’s a sample run:
I'm thinking of a number from 1 to 10.
What do you think my number is? 3
Your guess is too low.
What do you think my number is? 8
Your guess is too high.
What do you think my number is? 5
Your guess is too low.
What do you think my number is? 6
Congratulations! You found my number!
Dice This program makes the computer roll a pair of dice:
print "I'm rolling a pair of dice"
a=rnd(6)
print "One of the dice says ";a
b=rnd(6)
print "The other says ";b
print "The total is ";a+b
Line 2 makes the computer say:
I'm rolling a pair of dice
Each of the dice has 6 sides. The next line, a=rnd(6), rolls one of the dice, by picking a number from 1 to 6. The line saying “b=rnd(6)” rolls the other. The bottom line prints the total.
Here’s a sample run:
I'm rolling a pair of dice
One of the dice says 3
The other says 5
The total is 8
Here’s another run:
I'm rolling a pair of dice
One of the dice says 6
The other says 4
The total is 10
Coin flipping This program makes the computer flip a coin:
if rnd(2)=1 print "heads" else print "tails"
Rnd(2) is a random number from 1 to 2, so it’s either 1 or 2. If it’s 1, the program makes the computer say “heads”; if it’s 2 instead, the program makes the computer say “tails”.
Until you run the program, you won’t know which way the coin will flip; the choice is random. Each time you run the program, the computer will flip the coin again; each time, the outcome is unpredictable.
Here’s how to let the human bet on whether the computer will say “heads” or “tails”:
1 input "Do you want to bet on heads or tails";bet$x
if bet$<>"heads" and bet$<>"tails" print "Please say heads or tails": goto 1
if rnd(2)=1 coin$="heads" else coin$="tails"
print "The coin says ";coin$
if coin$=bet$ print "You win" else print "You lose"
The top line makes the computer ask:
Do you want to bet on heads or tails?
The next line makes sure the human says “heads” or “tails”: if the human’s answer isn’t “heads” and isn’t “tails”, the computer gripes. The bottom three lines make the computer flip a coin and determine whether the human won or lost the bet.
Here’s a sample run:
Do you want to bet on heads or tails? heads
The coin says tails
You lose
Here’s another:
Do you want to bet on heads or tails? tails
The coin says tails
You win
Here’s another:
Do you want to bet on heads or tails? tails
The coin says heads
You lose
Here’s how to let the human use money when betting:
bankroll=100
repeat
print "You have ";bankroll;" dollars"
1 input "How many dollars do you want to bet";stake
if stake>bankroll print "You don't have that much! Bet less!": goto 1
if stake<0 print "You can't bet less than nothing!": goto 1
if stake=0 print "I guess you don't want to bet anymore": goto 3
2 input "Do you want to bet on heads or tails";bet$
if bet$<>"heads" and bet$<>"tails" print "Please say heads or tails": goto 2
if rnd(2)=1 coin$="heads" else coin$="tails"
print "The coin says ";coin$
if coin$=bet$ then
print "You win ";stake;" dollars"
bankroll=bankroll+stake
else
print "You lose ";stake;" dollars"
bankroll=bankroll-stake
endif
until bankroll=0
print "You're broke! Too bad!"
3 print "Thanks for playing with me! You were fun to play with!"
print "I hope you play again sometime!"
The top line gives the human a $100 bankroll, so the human starts with $100. The third line makes the computer say:
You have 100 dollars
The next line makes the computer ask:
How many dollars do you want to bet?
The number that the human inputs (the number of dollars that the human bets) is called the human’s stake. The next three lines (which say “if stake”) make sure the stake is reasonable.
The line numbered 2 gets the human to bet on heads or tails. The next few lines flip the coin, determine whether the human won or lost the bet, and then send the computer back for another round (if the human isn’t broke yet). The bottom three lines say good-bye to the human.
Here’s a sample run:
You have 100 dollars
How many dollars do you want to bet? 120
You don't have that much! Bet less!
How many dollars do you want to bet? 75
Do you want to bet on heads or tails? heads
The coin says tails
You lose 75 dollars
You have 25 dollars
How many dollars do you want to bet? 10
Do you want to bet on heads or tails? tails
The coin says tails
You win 10 dollars
You have 35 dollars
How many dollars do you want to bet? 35
Do you want to bet on heads or tails? tails
The coin says heads
You lose 35 dollars
You're broke! Too bad!
Thanks for playing with me! You were fun to play with!
I hope you play again sometime!
Daily horoscope This program predicts what will happen to you today:
print "You will have a ";
case rnd(5) of
when 1 print "wonderful";
when 2 print "fairly good";
when 3 print "so-so";
when 4 print "fairly bad";
when 5 print "terrible";
endcase
print " day today!"
The computer will say —
You will have a wonderful day today!
or —
You will have a terrible day today!
or some in-between comment. That’s because the “case” line makes the computer pick a random integer from 1 to 5.
For inspiration, run that program when you get up in the morning. Then notice whether your day turns out the way the computer predicts!
Random decimals You’ve seen that rnd(5) is a random number from 1 to 5: it’s 1 or 2 or 3 or 4 or 5. To get a random decimal between 0 and 1, say “rnd(1)” instead of “rnd(5)”.
The decimal that rnd(1) produces is at least 0 and is less than 1, so it can be any decimal from 0.00000000 to 0.99999999. For example, the decimal might be 0.28459187.
Suppose you want the computer to maybe print “love”. Here’s how to make the probability of printing “love” be 37 percent:
if rnd(1)<.37 print "love"
Character codes
You can use these code numbers:
64 @ 96 ` 160 192 À 224 à
33 ! 65 A 97 a 161 ¡ 193 Á 225 á
34 " 66 B 98 b 162 ¢ 194 Â 226 â
35 # 67 C 99 c 163 £ 195 Ã 227 ã
36 $ 68 D 100 d 164 ¤ 196 Ä 228 Σ
37 % 69 E 101 e 165 ¥ 197 Å 229 å
38 & 70 F 102 f 166 ¦ 198 Æ 230 æ
39 ' 71 G 103 g 167 § 199 Ç 231 ç
40 ( 72 H 104 h 168 ¨ 200 È 232 è
41 ) 73 I 105 I 169 © 201 É 233 é
42 * 74 J 106 j 170 ª 202 Ê 234 ê
43 + 75 K 107 k 171 « 203 Ë 235 ë
44 , 76 L 108 l 172 ¬ 204 Ì 236 ì
45 - 77 M 109 m 173 205 Í 237 í
46 . 78 N 110 n 174 ® 206 Î 238 &
47 / 79 O 111 o 175 ¯ 207 Ï 239 ï
48 0 80 P 112 p 176 ° 208 Ð 240 ð
49 1 81 Q 113 q 145 ‘ 177 ± 209 Ñ 241 ñ
50 2 82 R 114 r 146 ’ 178 ² 210 Ò 242 ò
51 3 83 S 115 s 179 ³ 211 Ó 243 ó
52 4 84 T 116 t 180 ´ 212 ╘ 244 ô
53 5 85 U 117 u 181 µ 213 Õ 245 õ
54 6 86 V 118 v 182 ¶ 214 Ö 246 ö
55 7 87 W 119 w 183 · 215 × 247 ÷
56 8 88 X 120 x 184 ¸ 216 Ø 248 ø
57 9 89 Y 121 y 185 ¹ 217 Ù 249 1
58 : 90 Z 122 z 186 º 218 Ú 250 ú
59 ; 91 [ 123 { 187 » 219 Û 251 û
60 < 92 \ 124 | 188 ¼ 220 Ü 252 ü
61 = 93 ] 125 } 189 ½ 221 Ý 253 ý
62 > 94 ^ 126 ~ 190 ¾ 222 Þ 254 þ
63 ? 95 _ 127 191 ¿ 223 ß 255 ÿ
Alt key Here’s how to type the symbol ñ, whose code number is 241. Hold down the Alt key; and while you keep holding down the Alt key, type 0241 by using the numeric keypad (the number keys on the far right side of the keyboard). When you finish typing 0241, lift your finger from the Alt key, and you’ll see ñ on your screen!
The Alt key works for all numbers in that chart. Remember to type 0 before the number.
You can use the Alt key in your program. For example, try typing this program:
print "In Spanish, tomorrow is mañana"
While typing that program, make the symbol ñ by typing 0241 on the numeric keypad while holding down the Alt key. When you run that program, the computer will print:
In Spanish, tomorrow is mañana
The Alt key works well in Windows 10, such as when you’re typing in the program window, but not if you’re typing weirdly (such typing in the output window).
Chr$ Here’s another way to type the symbol ñ:
print chr$(241)
When you run that program, the computer will print the character whose code number is 241. The computer will print:
ñ
This program makes the computer print “In Spanish, tomorrow is mañana”:
print "In Spanish, tomorrow is ma";chr$(164);"ana"
That makes the computer print “In Spanish, tomorrow is ma”, then print character 164 (which is ñ), then print “ana”.
This program prints, on your screen, all the symbols in the chart:
for i= 33 TO 255
print chr$(i);
next
Low codes Codes below 33 do special things.
In a “print” statement, chr$(7) makes the computer play a 3-note melody. Try it! Run this program:
print chr$(7)
Chr$(32) is a blank space. It’s the same as “ ”.
Chr$(12) erases the entire screen. Saying —
print chr$(12);
has the same effect as saying:
cls
Chr$(10) make the computer move down on the screen. Saying —
print "hot";chr$(10);"dog"
makes the computer print “hot” then move down then print “dog”, so you see:
hot
dog
Asc The code numbers from 33 to 126 are for characters that you can type on the keyboard easily. Established by a national committee, those code numbers are called the American Standard Code for Information Interchange, which is abbreviated Ascii, which is pronounced “ass key”.
Programmers say, “the Ascii code number for A is 65”. If you say —
print asc("A")
the computer will print the Ascii code number for “A”. It will print:
65
If you say to print asc(“B”), the computer will print 66. If you say to print asc(“b”), the computer will print 98.
If you say to print asc(“ñ”), the computer will print 241 (which is the code number for ñ), even though ñ isn’t an Ascii character.
String analysis
Let’s analyze the word “smart”.
Length Since “smart” has 5 characters in it, the length of “smart” is 5. If you say —
print len("smart")
the computer will print the length of “smart”; it will print:
5
Left, right, middle The leftmost character in “smart” is “s”. If you say —
print left$("smart")
the computer will print:
s
Try this program:
a$="smart"
print left$(a$)
The top line says a$ is “smart”. The bottom line says to print the leftmost character in a$, which is “s”. The computer will print:
s
If a$ is “smart”, here are the consequences.…
len(a$) is the length of a$. It is 5.
left$(a$) is the leftmost character in a$. It is “s”.
left$(a$,2) is the left 2 characters in a$. It is “sm”.
right$(a$) is the rightmost character in a$. It is “t”.
right$(a$,2) is the right 2 characters in a$. It is “rt”.
mid$(a$,2) begins in the middle of a$, at the 2nd character. It is “mart”.
mid$(a$,2,3) begins at 2nd character and includes 3 characters. It is “mar”.
You can change a string’s left part, like this:
a$="bunkers"
left$(a$)="hoo"
print a$
The top line says a$ is “bunkers”. The left$ line changes the left part of a$ to “hoo”. The “hoo” covers up the “bun”, so the bottom line prints:
hookers
Here’s a variation:
a$="bunkers"
left$(a$,2)="hoo"
print a$
The top line says a$ is “bunkers”. The left$ line steals the left 2 characters from “hoo”, so it steals “ho”. The “ho” covers up “bu”, so the bottom line prints:
honkers
You can change a string’s right part, like this:
a$="bunkers"
right$(a$,4)="tingly"
print a$
The top line says a$ is “bunkers”. The right$ line changes the right 4 characters of “bunkers”, by stealing them from the beginning of “tingly”, which is “ting”. The “ting” covers up “kers”, so the bottom line prints:
bunting
You can change a string’s middle, like this:
a$="bunkers"
mid$(a$,2)="owl"
print a$
The top line says a$ is “bunkers”. The mid$ line changes the middle of a$ to “owl”; the change begins at the 2nd character of a$. The bottom line prints:
bowlers
Here’s a variation:
a$="bunkers"
mid$(a$,2)="ad agency"
print a$
The top line says a$ is “bunkers”. The mid$ line says to change the middle of a$, beginning at the 2nd character of a$. But “ad agency” is too long to become part of “bunkers”. The computer uses as much of “ad agency” as will fit in “bunkers”. The computer will print:
bad age
Another variation:
a$="bunkers"
mid$(a$,2,1)="owl"
print a$
The top line says a$ is “bunkers”. The mid$ line says to change the middle of a$, beginning at the 2nd character of a$. But the “,1” makes the computer use just 1 letter from “owl”. The bottom line prints:
bonkers
Adding strings You can add strings together, to form a longer string:
a$="fat"+"her"
print a$
The top line says a$ is “father”. The bottom line makes the computer print:
father
Searching in a string You can make the computer search in a string to find another string. To make the computer search in the string “needed” to find “ed”, say:
print instr("needed","ed")
Since “ed” begins at the third character of “needed”, the computer will print:
3
If you say —
print instr("needed","ey")
the computer will search in the string “needed” for “ey”. Since “ey” is not in “needed”, the computer will print:
0
If you say —
print instr("needed","ed",4)
the computer will hunt in the string “needed” for “ed”; but the hunt will begin at the 4th character of “needed”. The computer finds the “ed” that begins at the 5th character of “needed”. The computer will print:
5
String-number conversion This program converts a string to a number:
a$="52.6"
b=val(a$)
print b+1
The top line says a$ is the string “52.6”. The next line says b is the numeric value of a$, so b is the number 52.6. The bottom line prints:
53.6
Val converts a string to a number. The opposite of val is str$, which converts a number to a string. For example, str$(-7.2) is the string “-7.2”. Str$(81.4) is the string “81.4”.
Repeating characters Suppose you love the letter b (because it stands for big, bold, and beautiful) and want to print “bbbbbbbbbbbbbbbbbbbb”. Here’s a short-cut:
print string$(20,"b")
That tells the computer to print a string of 20 b’s.
This makes the computer print “fat” 10 times:
print string$(10,"fat")
The computer will print:
fatfatfatfatfatfatfatfatfatfat
Let’s make the computer draw a dashed line containing 50 dashes, like this:
--------------------------------------------------
Here’s how: just say print string$(50, “-”).
Let’s make the computer print this triangle:
*
**
***
****
*****
******
*******
********
*********
**********
***********
************
To do that, we want the computer to print 1 asterisk on the first line, then 2 asterisks on the next line, then 3 asterisks on the next line, and so on, until it finally prints 12 asterisks on the bottom line. Here’s the program:
for i=1 to 12
print string$(i,"*")
next
The “for” line makes i be 1, then 2, then 3, and so on, up to 12. When i is 1, the “print” line makes the computer print one asterisk, like this:
*
When i is 2, the “print” line makes the computer print a line of 2 asterisks, like this:
**
The “for” line makes i be every number from 1 up to 20, so computer will print 1 asterisk, then underneath print a line of 2 asterisks, then underneath print a line of 3 asterisks, and so on, until the entire triangle is printed.
Trigonometry
The study of triangles is called trigonometry — and the computer can do it for you!
For example, look at this triangle:
In that triangle, the left angle is 30°, the bottom-right angle is 90°, and the longest side (the hypotenuse) is 1 inch long.
The side opposite the 30° angle is called the sine of 30°; the remaining side is called the cosine of 30°:
How long is the sine of 30°? How long is the cosine of 30°?
Since the longest side (the hypotenuse) is 1 inch long, and since the sine and the cosine are shorter sides, the sine and the cosine must each be shorter than 1 inch. So the lengths of the sine and cosine are each less than 1. But which decimals are they?
To find out, you can use a ruler. You’ll discover that the sine is half an inch long, and the cosine is nearly seven-eighths of an inch long. But a faster and more accurate way to measure the sine and cosine is to let the computer do it! Yes, the computer can calculate triangles in its mind!
This program makes the computer measure the sine and cosine of 30°:
d=pi/180
print sin(30*d)
print cos(30*d)
The top line is a special formula that defines d to mean degrees. The first “print” line prints the sine of 30 degrees:
.5
The bottom line prints the cosine of 30°, which is a decimal that’s slightly less than .87.
The computer can measure the sine and cosine of any size angle. Try it! For example, to make the computer print the sine and cosine of a 33° angle, say:
d=pi/280
print sin(33*d)
print cos(33*d)
If you choose an angle of -33° instead of 33°, the triangle will dip down instead of rising up, and so the sine will be a negative number instead of positive.
In those “print” lines, the “*d” is important: it tells the computer that you want the sine of 33 degrees. If you accidentally omit the “*d”, the computer will print the sine of 33 radians instead. (A radian is larger than a degree. A radian is about 57.3 degrees. More precisely, a radian is 180/p degrees.)
Tangent The sine divided by the cosine is called the tangent. For example, to find the tangent of 33°, divide the sine of 33° by the cosine of 33°.
To make the computer print the tangent of 33°, you could tell the computer to print sin(33*d)/cos(33*d). But to find the tangent more quickly and easily, say just print tan(33*d).
Arc functions The opposite of the sine is called the arcsine:
the sine of 30° is .5
the arcsine of .5 is 30°
Similarly, the opposite of the cosine is called the arccosine, and the opposite of the tangent is called the arctangent.
This program prints the the arcsine of .5, the arccosine of .87, and the arctangent of .58:
d=pi/180
print asn(.5)/d
print acs(.87)/d
print atn(.58)/d
Line 2 prints the arcsine of .5, in degrees. (If you omit the “/ degrees”, the computer will print the answer in radians instead of degrees.) Line 3 prints the arccosine of .87. Line 4 prints the arctangent of .58. The answer to each of the three problems is about 30 degrees.
Subscripts
Instead of being a single string, x$ can be a whole list of strings, like this:
"love"
"hate"
"kiss"
x$= "kill"
"peace"
"war"
"why"
Here’s how to make x$ be that list of strings.…
Begin your program by saying:
dim x$(7)
That line says x$ will be a list of 7 strings. DIM means dimension; the line says the dimension of x$ is 7.
Next, tell the computer what strings are in x$. Type these lines:
x$(1)="love"
x$(2)="hate"
x$(3)="kiss"
x$(4)="kill"
x$(5)="peace"
x$(6)="war"
x$(7)="why"
That says x$’s first string is “love”, x$’s second string is “hate”, etc.
If you want the computer to print all those strings, type this:
for i=1 to 7
print x$(i)
next
That means: print all the strings in x$. The computer will print:
love
hate
kiss
kill
peace
war
why
That program includes a line saying x$(1)=“love”. Instead of saying x$(1), math books say:
x1
The “1” is called a subscript.
Similarly, in the line saying x$(2)=“hate”, the number 2 is a subscript. Some programmers pronounce that line as follows: “x string, subscripted by 2, is hate”. Hurried programmers just say: “x string 2 is hate”.
In that program, x$ is called an array (or matrix). Definition: an array (or matrix) is a variable that has subscripts.
Each item in an array is called an element of the array. For example, “love” is an element of that x$, and so is “hate”.
Subscripted data
That program said x$(1) is “love”, and x$(2) is “hate”, and so on. This program does the same thing, more briefly:
dim x$(7)
data love,hate,kiss,kill,peace,war,why
for i=1 to 7
read x$(i)
next
for i=1 to 7
print x$(i)
next
The “dim” line says x$ will be a list of 7 strings. The “data” line contains a list of 7 strings. The first “for…next” loop makes the computer read those strings and call them x$. The bottom “for…next” loop makes the computer print those 7 strings.
In that program, the first 3 lines say:
dim
data
for i
Most practical programs begin with those 3 lines.
Let’s lengthen the program, so the computer prints all this:
love
hate
kiss
kill
peace
war
why
why love
why hate
why kiss
why kill
why peace
why war
why why
That consists of two verses. The second verse resembles the first, except each line of the second verse begins with “why”.
To make the computer print all that, just add the shaded lines to the program:
dim x$(7)
data love,hate,kiss,kill,peace,war,why
for i=1 to 7
read x$(i)
next
for i = 1 TO 7
print x$(i)
next
print x
for i=1 to 7 x
print "why ";x$(i)
next x
The shaded “print” line leaves a blank line between the first verse and the second. The shaded “for…next” loop, which prints the second verse, resembles the “for…next” loop that printed the first verse but prints “why” before each x$(i).
Let’s add a third verse, which prints the words in reverse order:
why
war
peace
kill
kiss
hate
love
Before printing that third verse, print a blank line:
Then print the verse itself. To print the verse, you must print x$(7), then print x$(6), then print x$(5), etc. To do that, you could say:
print x$(7)
print x$(6)
print x$(5)
etc.
But this way is shorter:
for i=7 to 1 step -1
print x$(i)
next
Numeric arrays
Let’s make y be this list of five numbers: 100, 94, 201, 8.3, and -7. To begin, tell the computer that y will consist of five numbers:
dim y(5)
Next, tell the computer what the six numbers are:
data 100,94,201,8.3,-7
Make the computer read all that data:
for i=1 to 5
read y(i)
next
To make the computer print all that data, type this:
for i=1 to 5
print y(i)
next
If you want the computer to add those 5 numbers together and print their sum, say:
print y(1)+y(2)+y(3)+y(4)+y(5)
Strange example
Getting tired of x and y? Then pick another letter! For example, you can play with z:
Silly, useless program What the program means
dim z(5) z will be a list of 5 numbers
for i=2 to 5
z(i)=i*100 z(2)=200; z(3)=300; z(4)=400; z(5)=500
next
z(1)=z(2)-3 z(1) is 200 - 3, so z(1) is 197
z(3)=z(1)-2 z(3) changes to 197 - 2, which is 195
for i=1 to 5
print z(i) print z(1), z(2), z(3), z(4), and z(5)
next
The computer will print:
197
200
195
400
500
Problems and solutions
Suppose you want to analyze 20 numbers. Begin your program by saying:
dim x(20)
Then type the 20 numbers as data:
data etc.
Tell the computer to read the data:
for i=1 to 20
read x(i)
next
Afterwards, do one of the following, depending on which problem you want to solve.…
Print all x values Solution:
for i=1 to 20
print x(i)
next
Print all x values, in reverse order Solution:
for i=20 to 1 step -1
print x(i)
next
Print the sum of all x values In other words, print x(1)+x(2)+x(3)+…+x(20). Solution: start the sum at 0 —
s=0
and then increase the sum, by adding each x(i) to it:
for i=1 to 20
s=s+x(i)
next
Finally, print the sum:
print "The sum of all the numbers is";s
Find the average of x In other words, find the average of the 20 numbers. Solution: begin by finding the sum —
s=0
for i=1 to 20
s=s+x(i)
next
then divide the sum by 20:
print "The average is";s/20
Find whether any x value is 79.4 In other words, find out whether 79.4 is a number in the list. Solution: if x(i) is 79.4, print “Yes” —
for i=1 to 20
if x(i)=79.4 print "Yes, 79.4 is in the list": end
next
otherwise, print “No”:
print "No, 79.4 is not in the list"
In x’s list, count how often 79.4 appears Solution: start the counter at zero —
counter=0
and increase the counter each time you see the number 79.4:
for i=1 to 20
if x(i)=79.4 counter=counter+1
next
Finally, print the counter:
print "The number 79.4 appears ";counter;" times"
Print all x values that are negative In other words, print all the numbers that have minus signs. Solution: begin by announcing your purpose —
print "Here are the values that are negative:"
then print the values that are negative; in other words, print each x(i) that’s less than 0:
for i=1 to 20
if x(i)<0 print x(i)
next
Print all x values that are above average Solution: find the average —
s=0
for i=1 to 20
s=s+x(i)
next
average=s/20
then announce your purpose:
print "The following values are above average:"
Finally, print the values that are above average; in other words, print each x(i) that’s greater than average:
for i=1 to 20
if x(i)>average print x(i)
next
Find x’s biggest value In other words, find which of the 20 numbers is the biggest. Solution: begin by assuming that the biggest is the first number —
biggest=x(1)
but if you find another number that’s even bigger, change your idea of what the biggest is:
for i=2 to 20
if x(i)>biggest biggest=x(i)
next
Afterwards, print the biggest:
print "The biggest number in the list is"; biggest
Find x’s smallest value In other words, find which of the 20 numbers is the smallest. Solution: begin by assuming that the smallest is the first number —
smallest=x(1)
but if you find another number that’s even smaller, change your idea of what the smallest is:
for i=2 to 20
if x(i)<smallest smallest=x(i)
next
Afterwards, print the smallest:
print "The smallest number in the list is";smallest
Check whether x’s list is in strictly increasing order In other words, find out whether the following statement is true: x(1) is a smaller number than x(2), which is a smaller number than x(3), which is a smaller number than x(4), etc. Solution: if x(i) is not smaller than x(i + 1), print “No” —
for i=1 to 19
if x(i)>=x(i+1) then
print "No, the list is not in strictly increasing order"
end
endif
next
otherwise, print “Yes”:
print "Yes, the list is in strictly increasing order"
Test yourself: look at those problems again, and see whether you can figure out the solutions without peeking at the answers.
Multiple arrays
Suppose your program involves three lists. Suppose the first list is called a$ and consists of 18 strings; the second list is called b and consists of 57 numbers; and the third list is called c$ and consists of just 3 strings. To say all that, begin your program with this statement:
dim a$(18),b(57),c$(3)
Double subscripts
You can make x$ be a table of strings, like this:
"dog" "cat" "mouse"
x$=
"hotdog" "catsup" "mousetard"
Here’s how to make x$ be that table.…
Begin by saying:
dim x$(2,3)
That says x$ will be a table having 2 rows and 3 columns.
Then tell the computer what strings are in x$. Type these lines:
x$(1,1)="dog"
x$(1,2)="cat"
x$(1,3)="mouse"
x$(2,1)="hotdog"
x$(2,2)="catsup"
x$(2,3)="mousetard"
That says the string in x$’s first row and first column is “dog”, the string in x$’s first row and second column is “cat”, etc.
If you’d like the computer to print all those strings, type this:
for i=1 to 2
for j=1 to 3
print x$(i,j),;
next
next
That means: print all the strings in x$. The computer will print:
dog cat mouse
hotdog catsup mousetard
Most programmers follow this tradition: the row’s number is called i, and the column’s number is called j. That program obeys that tradition. The “for i=1 to 2” means “for both rows”; the “for j=1 to 3” means “for all 3 columns”.
Notice i comes before j in the alphabet; i comes before j in x(i,j); and “for i” comes before “for j”. If you follow the i-before-j tradition, you’ll make fewer errors.
At the end of the first “print” line, the comma makes the
computer print each column in a separate zone; the semicolon makes the computer
keep printing on the same line. The other “print” line makes the computer press
the Enter key at the end of each row. The x$ is called a table or 2-dimensional array or
doubly subscripted array.
The sum of all numbers in the table is sum(x()).
Multiplication table
This program prints a multiplication table:
dim x(10,5)
for i=1 to 10
for j=1 to 5
x(i,j)=i*j
next
next
for i=1 to 10
for j=1 to 5
print x(i,j);
next
next
The top line says x will be a table having 10 rows and 4 columns.
The line saying “x(i,j)=i*j” means the number in row i and column j is i*j. For example, the number in row 3 and column 4 is 12. Above that line, the program says “for i=1 to 10” and “for j=1 to 4”, so that x(i,j)=i*j for every i and j, so every entry in the table is defined by multiplication.
The computer prints the whole table:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
7 14 21 28 35
8 16 24 32 40
9 18 27 36 45
10 20 30 40 50
Instead of multiplication, you can have addition, subtraction, or division: just change the line saying “x(i,j)=i*j”.
Summing a table
Suppose you want to analyze this table:
32.7 19.4 31.6 85.1
-8 402 -61 0
5106 -.2 0 -1.1
36.9 .04 1 11
777 666 55.44 2
1.99 2.99 3.99 4.99
50 40 30 20
12 21 12 21
0 1000 2 500
Since the table has 9 rows and 4 columns, begin your program by saying:
dim x(9,4)
Each row of the table becomes a row of the data:
data 32.7,19.4,31.6,85.1
data -8,402,-61,0
data 5106,-.2,0,-1.1
data 36.9,.04,1,11
data 777,666,55.44,2
data 1.99,2.99,3.99,4.99
data 50,40,30,20
data 12,21,12,21
data 0,1000,2,500
Make the computer read the data:
for i=1 to 9
for j=1 to 4
read x(i,j)
next
next
To make the computer print the table, say this:
for i=1 to 9
for j=1 to 4
print x(i,j);
next
next
Here are some problems, with solutions.…
Find the sum of all the numbers in the table Solution: start the sum at 0 —
s=0
and then increase the sum, by adding each x(i,j) to it:
for i=1 to 9
for j=1 to 4
s=s+x(i,j)
next
next
Finally, print the sum:
print "The sum of all the numbers is ";s
The computer will print:
The sum of all the numbers is 8877.84
Find the sum of each row In other words, make the computer print the sum of the numbers in the first row, then the sum of the numbers in the second row, then the sum of the numbers in the third row, etc. Solution: the general idea is —
for i=1 to 9
print the sum of row i
next
Here are the details:
for i=1 to 9
s=0
for j=1 to 4
s=s+x(i,j)
next
print "The sum of row ";i;" is ";s
next
The computer will print:
The sum of row 1 is 168.8
The sum of row 2 is 333
The sum of row 3 is 5104.7
etc.
Find the sum of each column In other words, make the computer print the sum of the numbers in the first column, then the sum of the numbers in the second column, then the sum of the numbers in the third column, etc. Solution: the general idea is —
for j=1 to 4
print the sum of column j
next
Here are the details:
for j =1 to 4
s=0
for i=1 to 9
s=s+x(i,j)
next
print "The sum of column ";j;" is ";s
next
The computer will print:
The sum of column 1 is 6008.59
The sum of column 2 is 2151.23
The sum of column 3 is 75.03
The sum of column 4 is 642.99
In all the other examples, “for i” came before “for j”; but in this unusual example, “for i” comes after “for j”.
Secrets about subscripts
When you say “dim x(4)”, the computer creates x(1), x(2), x(3), and x(4) but also secretly creates x(0), which you can use the same way as the other elements, so altogether the array has 5 elements.
The computer secretly makes all 5 of those elements be temporarily 0, until you change them, by giving commands such as x(2)=9.4.
You can change all 5 of them fast by giving a command such as:
x()=138,2049,9.4,-4997,120
That makes x(0) be 138, x(1) by 2049, x(2) be 9.4, x(3) be -4997, and x(4) be 120.
To make all 5 of them be 9.4, you can say just:
x()=9.4
The sum of all 5 numbers is automatically called sum(x()), so to print their sum you can say just:
print sum(x))
That’s much easier than computing the sum by writing a “for…next” loop.
Similarly, saying “dim x$(4)” creates an array of 5 strings, beginning with x$(0). The computer makes all 5 of those strings be temporarily “” (which is an empty string), until you give commands such as x$(2)=“grape”. You can change all 5 of them fast by giving a command such as”
x$()="lemon”,"lime","grape","cherry","banana"
To make all 5 of them be “grape”, say x$()=”grape”. The sum of all 5 strings is called sum(x$()), which you can print by saying:
print sum(x$())
The sum is computed using string arithmetic: “hot”+”dog” is “hotdog”.
Saying “dim x(2,3)” creates a table that includes 2 rows and 3 columns but also secretly includes a row #0 and column #0, so altogether the table has 3 rows and 4 columns, a total of 12 elements. All numbers in the table are temporarily 0, until you change them. You can change all of them fast by giving a command such as:
x()=1,2,3,4,5,6,7,8,9,10,11,12
That makes:
x(0,0) be 1, x(0,1) be 2, x(0,2) be 3, x(0,3) be 4
x(1,0) be 5, x(1,1) be 6, x(1,2) be 7, x(1,3) be 8
x(2,0) be 9, x(2,1) be 10, x(2,2) be 11, x(2,3) be 12
Proc
Here’s a sick program:
print "We all know..."
print "You are stupid!"
print "You are ugly!"
print "...and yet we love you."
It makes the computer print this message:
We all know...
You are stupid!
You are ugly!
...and yet we love you.
So the computer prints “We all know...”, then insults the human (“You are stupid! You are ugly!”), then prints “...and yet we love you.”
Here’s a more sophisticated way to write that program:
print "We all know..."
proc_insult
print "...and yet we love you."
end
def proc_insult
print "You are stupid!"
print "You are ugly!"
endproc
In the sophisticated version, the top 3 lines tell the computer to print “We all know...”, then do a procedure to insult the human, then print “...and yet we love you.” But the computer doesn’t know how to insult yet.
The bottom 4 lines teach the computer how to insult: they say “insult” means to print “You are stupid!” and “You are ugly!” Those bottom 4 lines define the word insult; they’re the definition of insult.
That program is divided into two procedures. The top 4 lines are called the main procedure (or main routine or main module). The bottom 4 lines (which just define “proc_insult”) are called the subprocedure (or subroutine or submodule).
The subprocedure’s first line (“def proc_insult”) means “here’s the definition of proc_insult”. The subprocedure’s bottom line (“endproc”) means “this is the end of the subprocedure”.
The main procedure’s bottom line (“end”) means “this is the end of the main procedure”.
When you run the program, the computer will say:
We all know...
You are stupid!
You are ugly!
...and yet we love you.
Refrains
This is chanted by boys playing tag — and protesters fearing dictators:
The lion is a-coming near.
He'll growl and sneer
And drink our beer.
The lion never brings us cheer.
He'll growl and sneer
And drink our beer.
The lion is the one we fear.
He'll growl and sneer
And drink our beer.
Gotta stop the lion!
In that chant, this refrain is repeated:
He'll growl and sneer
And drink our beer.
This program prints the entire chant:
print "The lion is a-coming near."
proc_refrain
print "The lion never brings us cheer."
proc_refrain
print "The lion is the one we fear."
proc_refrain
print "Gotta stop the lion!"
end
def proc_refrain
print " He'll growl and sneer"
print " And drink our beer."
endproc
Big love
This program prints a love poem:
print "The most beautiful thing in the world is"
print "LOVE"
print "The opposite of war is"
print "LOVE"
print "And when I look at you, I feel lots of"
print "LOVE"
In that program, many of the lines make the computer print the word LOVE. Let’s make those lines print the word LOVE bigger, like this:
* * * * * * * * *
* * * * * *
* * * * * * * *
* * * * * *
* * * * * * * * * * * *
To make LOVE be that big, run this version of the program:
print "The most beautiful thing in the world is"
proc_big_love
print "The opposite of war is"
proc_big_love
print "And when I look at you, I feel lots of"
proc_big_love
end
def proc_big_love
print "* * * * * * * * *"
print "* * * * * *"
print "* * * * * * * *"
print "* * * * * *"
print "* * * * * * * * * * * *"
endproc
In that version, the lines say proc_big_love instead of print “LOVE”. The subprocedure teaches the computer how to make big_love.
Changed variable
Suppose you run this program:
x=4
proc_joe
print x
end
def proc_joe
x=x+1
endproc
The computer begins by doing the main procedure, which says x is 4. Then the computer does procedure joe, which adds 1 to x, so x becomes 5. Then the computer finishes the main procedure, which says to print x, so the computer prints:
5
Style
To become a good programmer, write your programs using a good style. Here’s how.…
Design a program
First, decide on your ultimate goal. Be optimistic. Maybe you’d like the computer to play the perfect game of chess? or translate every English sentence into French?
Research the past Whatever you want the computer to do, someone else probably thought of the same idea already and wrote a program for it.
Find out. Ask your friends. Ask folks in nearby schools, computer stores, computer centers, companies, libraries, and bookstores. Look through books and magazines. There are even books that list what programs have been written. Ask the company you bought your computer from.
Even if you don’t find exactly the program you’re looking for, you may find one that’s close enough to be okay, or that will work with just a little fixing or serve as part of your program or at least give you a clue as to where to begin. In a textbooks or magazines, you’ll probably find a discussion of the problem you’re trying to solve and the pros and cons of various solutions to it — some methods are faster than others.
If you keep your head in the sand and don’t look at what other programmers have done already, your programming effort may turn out to be a mere exercise, useless to the rest of the world.
Simplify Too often, programmers embark on huge projects and never get them done. Once you have an idea of what’s been done before and how hard your project is, simplify it.
Instead of making the computer play a perfect game of chess, how about settling for a game in which the computer plays unremarkably but at least doesn’t cheat? Instead of translating every English sentence into French, how about translating just English colors? (We wrote that program already.)
So pick a less ambitious, more realistic goal, which if achieved will please you and be a steppingstone to your ultimate goal.
Finding a bug in a program is like finding a needle in a haystack: removing the needle is easier if the haystack is small than if you wait until more hay’s been piled on.
Specify the I/O Make your new, simple goal more precise. That’s called specification. One way to be specific is to draw a picture, showing what your screen will look like if your program’s running successfully.
In that picture, find the lines typed by the computer. They become your program’s “print” statements. Find the lines typed by the human: they become the “input” statements. Now you can start writing your program: write the “print” and “input” statements on paper, with a pencil, and leave blank lines between them. You’ll fill in the blanks later.
Suppose you want the computer to find the average of two numbers. Your picture will look like this:
What's the first number? 7
What's the second number? 9
The average is 8
Your program at this stage will be:
input "What's the first number";a
input "What's the second number";b
etc.
print "The average is ";c
All you have left to do is figure out what the “etc.” is. Here’s the general method.…
Choose your statements Suppose you didn’t have a computer. Then how would you get the answer?
Would you have to use a mathematical formula? If so, put the formula into your program, but remember that the equation’s left side must have just one variable. For example, if you’re trying to solve a problem about right triangles, you might have to use the Pythagorean formula a²+b²=c²; but the left side of the equation must have just one variable, so your program must say a=sqr(c^2-b^2), or b=sqr(c^2-a^2), or c=sqr(a^2+b^2), depending on whether you’re trying to compute a, b, or c.
Would you have to use a memorized list, such as an English-French dictionary or the population of each state or the weight of each chemical element? If so, that list becomes your data, and you must read it. If it would be helpful to have the data numbered — so the first piece of data is called x(1), the next piece of data is called x(2), etc. — use the “dim” statement.
Subscripts are particularly useful if one long list of information will be referred to several times in the program.
Does your reasoning repeat? That means your program should have a loop. If you know how many times to repeat, say “for…next”. If you’re not sure how often, say “repeat...until”. If the thing to be repeated isn’t repeated immediately, but just after several other things have happened, make the repeated part be a subprocedure.
At some point in your reasoning, do you have to make a decision? Do you have to choose among several alternatives? To choose between 2 alternatives, say “if”. To choose among 3 or more alternatives, say “case”. If you want the computer to make the choice arbitrarily, “by chance” instead of for a reason, say “if rnd”.
Do you have to compare two things? The way to say “compare x with y” is: “if x=y”.
Write pseudocode Some English teachers say that before you write a paper, you should make an outline. Some computer teachers give similar advice about writing programs.
The “outline” can look like a program in which some of the lines are written in plain English instead of computerese. For example, one statement in your outline might be:
a = the average of the 12 values of x
Such a statement, written in English instead of in computerese, is called pseudocode. Later, when you fill in the details, expand that pseudocode to this:
s=0
for i=1 to 12
s=sum+x(i)
next
average=s/12
Organize yourself Keep the program’s over-all organization simple. That will make it easier for you to expand the program and find bugs. Here’s some folklore, handed down from generation to generation of programmers, that will simplify your organization.…
Use top-down programming. That means write a one-sentence description of your program; then ejxpand that sentence to several sentences; then expand each of those sentences to several more sentences; and so on, until you can’t expand any more. Then turn each of those new sentences into lines of program. Then your program will be in the same order as the English sentences, therefore organized the same way as an English-speaking mind.
A variation is to use subprocedures. That means writing the essence of the program as a very short main procedure; instead of filling in the grubby details immediately, replace each piece of grubbiness by a subprocedure. Your program will be like a good book: your main procedure will move swiftly, and the annoying details will be relegated to the appendices at the back; the appendices are the subprocedures. Make each procedure brief — no more than 30 lines — so the entire procedure can fit on the screen; if it starts getting longer and grubbier, replace each piece of grubbiness by another subprocedure.
Avoid “goto”. It’s hard for a human to understand a program that’s a morass of “goto” statements. It’s like trying to read a book where each paragraph says to turn to a different page! When you must say “goto”, try to go forward instead of backwards and not go too far.
Use variables After you’ve written some lines of your program, you may notice that your reasoning “almost repeats”: several lines bear a strong resemblance to each other. You can’t use “repeat…until” or “for...next” unless the lines repeat exactly. To make the repetition complete, use a variable to represent the parts that are different.
For example, suppose your program contains these lines:
print 29.34281+9.876237*sqr(5)
print 29.34281+9.876237*sqr(7)
print 29.34281+9.876237*sqr(9)
print 29.34281+9.876237*sqr(11)
print 29.34281+9.876237*sqr(13)
print 29.34281+9.876237*sqr(15)
print 29.34281+9.876237*sqr(17)
print 29.34281+9.876237*sqr(19)
print 29.34281+9.876237*sqr(21)
Each of those lines says to print 29.3428+9.87627*sqr(a number). The number keeps changing, so call it x. All those “print” lines can be replaced by this loop:
for x=5 to 21 step 2
print 29.34281+9.876237*sqr(x)
next
Here’s a harder example to fix:
print 29.34281+9.876237*sqr(5)
print 29.34281+9.876237*sqr(97.3)
print 29.34281+9.876237*sqr(8.62)
print 29.34281+9.876237*sqr(.4)
print 29.34281+9.876237*sqr(200)
print 29.34281+9.876237*sqr(12)
print 29.34281+9.876237*sqr(591)
print 29.34281+9.876237*sqr(.2)
print 29.24281+9.876237*sqr(100076)
Again, let’s use x. All those “print” lines can be combined like this:
data 5,97.3,8.62,.4,200,12,591,.2,100076
for i=1 to 9
read x
print 29.34281+9.876237*sqr(x)
next
This one’s even tougher:
print 29.34281+9.876237*sqr(a)
print 29.34281+9.876237*sqr(b)
print 29.34281+9.876237*sqr(c)
print 29.34281+9.876237*sqr(d)
print 29.34281+9.876237*sqr(e)
print 29.34281+9.876237*sqr(f)
print 29.34281+9.876237*sqr(g)
print 29.34281+9.876237*sqr(h)
print 29.34281+9.876237*sqr(i)
Let’s assume a, b, c, d, e, f, g, h, and i have been computed earlier in the program. The trick to shortening those lines is to change the names of the variables. Throughout the program, say x(1) instead of a, say x(2) instead of b, say x(3) instead of c, etc. Say dim x(9) at the beginning of your program. Then replace all those “print” lines by this loop:
for i=1 to 9
print 29.34281+9.876237*sqr(x(i))
next
Make it efficient
Your program should be efficient. That means it should use as little of the computer’s time and memory as possible.
To use less of the computer’s memory, make your dimensions as small as possible. Try writing the program without any arrays at all; if that turns out to be terribly inconvenient, use the smallest and fewest arrays possible.
To use less of the computer’s time, avoid having the computer do the same thing more than once.
These lines force the computer to compute sqr(8.2*n+7) three times:
print sqr(8.3*n+7)+2
print sqr(8.3*n+7)/9.1
print 5-sqr(8.3*n+7)
You should change them to:
k=sqr(8.3*n+ 7)
print k+2
print k/9.1
print 5-k
These lines force the computer to compute x^9+2 a hundred times:
for i=1 to 100
print (x^9+2)/i
next
You should change them to:
k=x^9+2
for i=1 to 100
print k/i
next
These lines force the computer to count to 100 twice:
s=0
for i=1 to 100
s=s+x(i)
next
print "The sum of the x's is ";s
product=1
for i=1 to 100
product=product*x(i)
next
print "The product of the x's is ";product
You should combine the two “for...next” loops into a single “for...next” loop, so the computer counts to 100 just once. Here’s how:
s=0
product=1
for i=1 to 100
s=s+x(i)
product=product*x(i)
next
print "The sum of the x's is ";sum
print "The product of the x's is"; product
Instead of exponents, use multiplication, which is faster:
slow: y=x^2
faster: y=x*x
Test it
When you’ve written a program, test it: run it and see whether it works.
If the computer does not gripe, your tendency will be to say “Whoopee!” Don’t cheer too loudly. The answers the computer prints might be wrong. Even if its answers look reasonable, don’t assume they’re right: the computer’s errors can be subtle. Check some of its answers by computing them with a pencil.
Even if the answers the computer prints are correct, don’t cheer. Maybe you were just lucky. Type different input, and see whether your program still works. Probably you can input something that will make your program go crazy or print a wrong answer. Your mission: to find input that will reveal the existence of a bug.
Try 6 kinds of input.…
Try simple input Type in simple integers, like 2 and 10, so the computation is simple, and you can check the computer’s answers easily.
Try input that increases See how the computer’s answer changes when the input changes from 2 to 1000.
Does the change in the computer’s answer look reasonable? Does the computer’s answer go up when it should go up, and down when it should go down?… and by a reasonable amount?
Try input testing each “if” For a program that says —
if x<7 goto 10
input an x less than 7 (to see whether line 10 works), then an x greater than 7 (to see whether the line underneath the “if” line works), then an x equal to 7 (to see whether you really want “<” instead of “<=”), then an x very close to 7, to check round-off error.
For a program that says —
if x^2+y<z goto 10
input an x, y, and z that make x^2+y less than z. Then try inputs that make x^2+y very close to z.
Try extreme input What happens if you input:
a huge number, like 45392000000 or 1E35?
a tiny number, like .00000003954 or 1E-35?
a trivial number, like 0 or 1?
a typical number, like 45.13?
a negative number, like -52?
Find out.
If the input is supposed to be a string, what happens if you input aaaaa or zzzzz? What happens if you capitalize the input? If there are supposed to be two inputs, what happens if you input the same thing for each?
Try input making a line act strange If your program contains division, try input that will make the divisor be zero or a tiny decimal close to zero. If your program contains the square root of a quantity, try input that will make the quantity be negative. If your program says “for i=x to y”, try input that will make y be less than x, then equal to x. If your program mentions x(i), try input that will make i be zero or negative or greater than the dim.
Try input that causes round-off error: for a program that says “x-y” or says “if x=y”, try input that will make x almost equal y.
Try garbage Computers often print wrong answers. A computer can print a wrong answer because its circuitry is broken or because a program has a bug. But the main reason why computers print wrong answers is incorrect input. Incorrect input is called garbage and has several causes.…
The user’s finger slips. Instead of 400, he inputs 4000. Instead of 27, he inputs 72. Trying to type .753, he leaves out the decimal point.
The user got wrong info. He tries to input the temperature, but his thermometer is leaking. He tries to input the results of a questionnaire, but everybody who filled out his questionnaire lied.
The instructions aren’t clear, so the user isn’t sure what to input.
If the program asks “How far did the ball fall?” should the user type the distance in feet or in meters? Is time to be given in seconds or minutes? Are angles to be measured in degrees or radians?
Can the user input “y” instead of “yes”?
Maybe the user isn’t clear about whether to insert commas, quotation marks, and periods. If several items are to be typed, should they be typed on the same line or on separate lines? If your program asks “How many brothers and sisters do you have?” and the user has 2 brothers & 3 sisters, should he type “5” or “2,3” or “2 brothers and 3 sisters”?
If the program asks “What is your name?” should the user type “Joe Smith” or “Smith,Joe” or just “Joe”? For a quiz that asks “Who was the first U.S. President?” what if the user answers “George Washington” or simply “Washington” or “washington” or “G. Washington” or “General George Washington” or “President Washington” or “Martha’s husband”? Make the instructions clearer:
Who was the first U.S. President (give just his last name)?
The user tries to joke or sabotage. Instead of inputting his name, he types an obscene comment. When asked how many brothers and sisters he has, he says 275.
Responsibility! As a programmer, it’s your duty to include clear directions for using your program, and you must make the program reject ridiculous input.
For example, if your program is supposed to print weekly paychecks, it should refuse to print checks for more than $10000. Your program should contain these lines:
1 input "How much money did the employee earn";e
if e>10000 then
print e; " is quite a big paycheck! I don't believe you."
print "Please retype your request."
goto 1
endif
That “if” line is called an error trap (or error-handling routine). Your program should contain several, to prevent printing checks that are too small (2¢?) or negative or otherwise ridiculous ($200.73145?)
To see how your program reacts to input that’s either garbage or unusual, ask a friend to run your program. That person might input something you never thought of.
Document it
Write an explanation that helps other people understand your program.
An explanation is called documentation. When you write an explanation, you’re documenting the program.
You can write the documentation on a separate sheet of paper, or you can make the computer print the documentation when the user runs or lists the program.
A popular device is to begin the program by making the computer ask the user:
Do you need instructions?
You need two kinds of documentation: how to use the program, and how the program was written.
How to use the program Your explanation of using the program should include:
the program’s name
how to get the program from the disk
the program’s purpose
a list of other programs that must be combined with this program, to make a workable combination
the correct way to type the input and data (show an example)
the correct way to interpret the output
the program’s limitations (input it can’t handle, a list of error messages that might be printed, round-off error)
a list of bugs you haven’t fixed yet
How the program was written An explanation of how you wrote the program will help other programmers borrow your ideas, and help them expand your program to meet new situations. It should include:
your name
the date you finished it
the computer you wrote it for
the language you wrote it in (probably BBC Basic)
the name of the method you used (“solves quadratic equations by using the quadratic formula”)
the name of the book or magazine where you found the method
the name of any program you borrowed ideas from
an informal explanation of how program works (“It loops until x>y, then computes the weather forecast.”)
the purpose of each subprocedure
the meaning of each variable
the significance of reaching a line (for a program saying “if x<60 goto 1000”, say “Reaching line 1000 means the student flunked.”)