Whatís a variable?

A letter can stand for a number. For example, x can stand for the number 47, as in this program:

CLS

x = 47

PRINT x + 2

The second line says x stands for the number 47. In other words, x is a name for the number 47.

The bottom line says to print x + 2. Since x is 47, the x + 2 is 49; so the computer will print 49. Thatís the only number the computer will print; it will not print 47.

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.

Faster typing

Instead of typing ó

x = 47

you can type just this:

x=47

At the end of that line, when you press the ENTER key, the computer will automatically put spaces around the equal sign.

Youíve learned that the computer:

automatically capitalizes computer words (such as CLS)

automatically puts spaces around symbols (such as + and =)

lets you type a question mark instead of the word PRINT

So you can type just this:

cls

x=47

?x+2

When you press ENTER at the end of each line, the computer will automatically convert your typing to this:

CLS

x = 47

PRINT x + 2

More examples

Hereís another example:

CLS

y = 38

PRINT y - 2

The second line says y is a numeric variable that stands for the number 38.

The bottom line says to print y - 2. Since y is 38, the y - 2 is 36; so the computer will print 36.

Example:

CLS

b = 8

PRINT b * 3

The second line says b is 8. The bottom line says to print b * 3, which is 8 * 3, which is 24; so the computer will print 24.

One variable can define another:

CLS

n = 6

d = n + 1

PRINT n * d

The second line says n is 6. The next line says d is n + 1, which is 6 + 1, which is 7; so d is 7. The bottom line says to print n * d, which is 6 * 7, which is 42; so the computer will print 42.

Changing a value

A value can change:

CLS

k = 4

k = 9

PRINT k * 2

The second line says kís value is 4. The next line changes kís value to 9, so the bottom line prints 18.

When you run that program, hereís what happens inside the computerís RAM. The second line (k = 4) makes the computer put 4 into box k:

┌─────────────┐

box k │ 4 │

└─────────────┘

The next line (k = 9) puts 9 into box k. The 9 replaces the 4:

┌─────────────┐

box k │ 9 │

└─────────────┘

Thatís why the bottom line (PRINT k * 2) prints 18.

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 Not allowed Not allowed

d = n + 1 d - n = 1 1 = d - n

­ ­ ­ ­

one variable two variables 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:

CLS

b = 1

c = 7

b = c

PRINT b + c

The fourth line changes b, to make it equal c; so b becomes 7. Since both b and c are now 7, the bottom line prints 14.

"b = c" versus "c = b" Saying "b = c" has a different effect from "c = b". Thatís because "b = c" changes the value of b (but not c); saying "c = b" changes the value of c (but not b).

Compare these programs:

CLS CLS

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 fourth line changes b to 7, so both b and c are 7. The bottom line prints 14.

In the right program, the fourth line changes c to 1, so both b and c are 1. The bottom line prints 2.

While you run those programs, hereís what happens inside the computerís RAM. For both programs, the second and third lines do this:

┌─────────────┐

box b │ 1 │

└─────────────┘

┌─────────────┐

box c │ 7 │

└─────────────┘

In the left program, the fourth line makes the number in box b become 7 (so both boxes contain 7, and the bottom line prints 14). In the right program, the fourth line makes the number in box c become 1 (so both boxes contain 1, and the bottom line prints 2).

When to use variables

Hereís a practical example of when to use variables.

Suppose youíre selling something that costs $1297.43, and you want to do these calculations:

multiply $1297.43 by 2

multiply $1297.43 by .05

add $1297.43 to $483.19

divide $1297.43 by 37

subtract $1297.43 from $8598.61

multiply $1297.43 by 28.7

To do those six calculations, you could run this program:

CLS

PRINT 1297.43 * 2; 1297.43 * .05; 1297.43 + 483.19; 1297.43 / 37

PRINT 8598.61-1297.43; 1297.43 * 28.7

But that programís silly, since it contains the number 1297.43 six times. This programís briefer, because it uses a variable:

CLS

c = 1297.43

PRINT c * 2; c * .05; c + 483.19; c / 37; 8598.61 - c; c * 28.7

So whenever you need to use a number several times, turn the number into a variable, which will make your program briefer.

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:

CLS

g$ = "down"

PRINT g$

The second 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:

CLS

t$ = "They're laughing at you!"

PRINT t$

PRINT t$

PRINT t$

The second 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:

CLS

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$

Since the computer will automatically insert the semicolons, you can type just this ó

PRINT s$ " " k$

or even type just this:

PRINT s$" "k$

or even type just this:

?s$" "k$

When you press the ENTER key at the end of that line, the computer will automatically convert it to:

PRINT s$; " "; k$

Nursery rhymes

The computer can recite nursery rhymes:

CLS

p$ = "Peas porridge "

PRINT p$; "hot!"

PRINT p$; "cold!"

PRINT p$; "in the pot,"

PRINT "Nine days old!"

The second 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:

CLS

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 2-4 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!

Undefined variables

If you donít define a numeric variable, the computer assumes itís zero:

CLS

PRINT r

Since r hasnít been defined, the bottom line prints zero.

The computer doesnít look ahead:

CLS

PRINT j

j = 5

When the computer encounters the second line (PRINT j), it doesnít look ahead to find out what j is. As of the second line, j is still undefined, so the computer prints zero.

If you donít define a string variable, the computer assumes itís blank:

CLS

PRINT f$

Since f$ hasnít been defined, the "PRINT f$" makes the computer print a line that says nothing; the line the computer prints is blank.

Long variable names

A numeric variableís name can be a letter (such as x) or a longer combination of characters, such as:

profit.in.1996.before.November.promotion

For example, you can type:

CLS

profit.in.1996.before.November.promotion = 3497.18

profit.in.1996 = profit.in.1996.before.November.promotion + 6214.27

PRINT profit.in.1996

The computer will print:

9711.45

The variableís name can be quite long: up to 40 characters!

The first character in the name must be a letter. The remaining characters can be letters, digits, or periods.

The name must not be a word that has a special meaning to the computer. For example, the name cannot be "print".

If the variable stands for a string, the name can have up to 40 characters, followed by a dollar sign, making a total of 41 characters, like this:

my.job.in.1996.before.November.promotion$

Beginners are usually too lazy to type long variable names, so beginners use variable names that are short. But when you become a pro and write a long, fancy program containing hundreds of lines and hundreds of variables, you should use long variable names to help you remember each variableís purpose.

In this book, Iíll use short variable names in short programs (so you can type those programs quickly), and long variable names in long programs (so you can keep track of which variable is which).

Programmers employed at Microsoft capitalize the first letter of each word and omit the periods. So instead of writing:

my.job.in.1996.before.November.promotion$

those programmers write:

MyJobIn1996BeforeNovemberPromotion$

Thatís harder to read; but since Microsoft is headed by Bill Gates, whoís the richest person in America, he can do whatever he pleases!

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:

CLS

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?" and then waits for you to answer the question. Your answer will be called n$. For example, if you answer Maria, then n$ is Maria. The bottom line makes the computer print:

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.Ö

The computer asks for your name: What is your name? Maria

The 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.Ö

The computer asks for your name: What is your name? Bud

The 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.Ö

The computer asks for your name: What is your name? none of your business!!!

The computer replies: I adore anyone whose name is none of your business!!!

College admissions

This program prints a letter, admitting you to the college of your choice:

CLS

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.Ö

The computer asks you: What college would you like to enter? Harvard

The 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:

The computer asks you: What college would you like to enter? Hell

The 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:

CLS

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:

CLS

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

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.

This run describes the contest that brought Ronald Reagan to the White House:

What's your name? Ronnie Reagan

What's your friend's name? Nancy

What's the name of another friend? Alice

Name a color? red-white-and-blue

Name a place? the White House

Name a food? jelly beans

Name an object? cowboy hat

Name a part of the body? cheeks

Name a style of cooking (such as baked or fried)? steamed

Congratulations, Ronnie Reagan!

You've won the beauty contest, because of your gorgeous cheeks.

Your prize is a red-white-and-blue cowboy hat

plus a trip to the White House with your friend Nancy

plus--and this is the best part of all--

dinner for the two of you at Alice's new restaurant,

where Alice will give you all the steamed jelly beans you can eat.

Congratulations, Ronnie Reagan, today's your lucky day!

Now everyone wants to kiss your award-winning cheeks.

Bills

If youíre a nasty bill collector, youíll love this program:

CLS

INPUT "What is the customer's first name"; first.name$

INPUT "What is the customer's last name"; last.name$

INPUT "What is the customer's street address"; street.address$

INPUT "What city"; city$

INPUT "What state"; state$

INPUT "What ZIP code"; zip.code$

PRINT

PRINT first.name$; " "; last.name$

PRINT street.address$

PRINT city$; " "; state$; " "; zip.code$

PRINT

PRINT "Dear "; first.name$; ","

PRINT " You still haven't paid the bill."

PRINT "If you don't pay it soon, "; first.name$; ","

PRINT "I'll come visit you in "; city$

PRINT "and personally shoot you."

PRINT " Yours truly,"

PRINT " Sure-as-shootin'"

PRINT " Your crazy creditor"

Can you figure out what that program does?

Numeric input

This program makes the computer predict your future:

CLS

PRINT "I predict what'll happen to you in the year 2000!"

INPUT "In what year were you born"; y

PRINT "In the year 2000, you'll turn"; 2000 - y; "years old."

Hereís a sample run:

I predict what'll happen to you in the year 2000!

In what year were you born? 1962

In the year 2000, you'll turn 38 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:

CLS

INPUT "How many tickets"; t

PRINT "The total price is $"; t * 2.79

This program tells you how much the "energy crisis" costs you, when you drive your car:

CLS

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? 95.9

How many miles-per-gallon does your car get? 31

The gas for your trip will cost you $ 12.37419

Conversion

This program converts feet to inches:

CLS

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:

CLS

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:

CLS

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.

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:

CLS

INPUT "How old are you"; age

IF age < 18 THEN PRINT "You are still a minor"

Line 2 makes the computer ask "How old are you" and wait for the human to type an age. Since the symbol for "less than" is "<", the bottom line says: if the age is less than 18, then print "You are still a minor".

Go ahead! Run that program! The computer begins the conversation by asking:

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 THEN PRINT "You are still a minor"

That line contains the words IF and THEN. Whenever you say IF, you must also say THEN. Do not put a comma before THEN. What comes between IF and THEN is called the condition; in that example, the condition is "age < 18". If the condition is true (if age is really less than 18), the computer does the action, which comes after the word THEN and is:

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:

CLS

INPUT "How old are you"; age

IF age < 18 THEN 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, then print "You are still a minor"; otherwise (if the age is not less than 18), print "You are an adult". So the computer will print "You are still a minor" or else print "You are an adult", depending on whether the age is less than 18.

Try running that program! If you say youíre 50 years old, so the screen looks like this ó

How old are you? 50

the computer will reply by saying:

You are an adult

 

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 THEN 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"

END IF

That sophisticated way (in which you type 4 short lines instead of a single long line) is called a multi-line IF (or a block IF).

In a multi-line IF:

The top line must say IF and THEN (with nothing after THEN).

The middle lines should be indented; theyíre called the block and typically say PRINT.

The bottom line must say END IF.

In the middle of a multi-line IF, you can say ELSE:

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"

END IF

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".

ELSEIF

Letís say this:

If age is under 18, print "Youíre a minor".

If age is not under 18 but is under 100, print "Youíre a typical adult".

If age is not under 100 but is under 125, print "Youíre a centenarian".

If age is not under 125, print "Youíre a liar".

Hereís how:

IF age < 18 THEN

PRINT "You're a minor"

ELSEIF age < 100 THEN

PRINT "You're a typical adult"

ELSEIF age < 125 THEN

PRINT "You're a centenarian"

ELSE

PRINT "You're a liar"

END IF

One word In QBASIC, "ELSEIF" is one word. Type "ELSEIF", not "ELSE IF". If you accidentally type "ELSE IF", the computer will gripe.

SELECT

Letís turn your computer into a therapist!

To make the computer ask the patient, "How are you?", begin the program like this:

CLS

INPUT "How are you"; a$

Make the computer continue the conversation by responding as follows:

If the patient says "fine", print "Thatís good!"

If the patient says "lousy" instead, print "Too bad!"

If the patient says anything else instead, print "I feel the same way!"

To accomplish all that, you can use a multi-line IF:

IF a$ = "fine" THEN

PRINT "That's good!"

ELSEIF a$ = "lousy" THEN

PRINT "Too bad!"

ELSE

PRINT "I feel the same way!"

END IF

Instead of typing that multi-line IF, you can type this SELECT statement instead, which is briefer and simpler:

SELECT CASE a$

CASE "fine"

PRINT "That's good!"

CASE "lousy"

PRINT "Too bad!"

CASE ELSE

PRINT "I feel the same way!"

END SELECT

Like a multi-line IF, a SELECT statement consumes several lines. The top line of that SELECT statement tells the computer to analyze a$ and SELECT one of the CASEs from the list underneath. That list is indented and says:

In the case where a$ is "fine", print "Thatís good!"

In the case where a$ is "lousy", print "Too bad!"

In the case where a$ is anything else, print "I feel the same way!"

The bottom line of every SELECT statement must say END SELECT.

Complete program

Hereís a complete program:

CLS

INPUT "How are you"; a$

SELECT CASE a$

CASE "fine"

PRINT "That's good!"

CASE "lousy"

PRINT "Too bad!"

CASE ELSE

PRINT "I feel the same way!"

END SELECT

PRINT "I hope you enjoyed your therapy. Now you owe $50."

Line 2 makes the computer ask the patient, "How are you?" The next several lines are the SELECT statement, which makes the computer analyze the patientís answer and print "Thatís good!" or "Too bad!" or else "I feel the same way!"

Regardless of what the patient and computer said, that programís bottom line always makes the computer end the conversation by printing:

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.

Error trap

This program makes the computer discuss human sexuality:

CLS

10 INPUT "Are you male or female"; a$

SELECT CASE a$

CASE "male"

PRINT "So is Frankenstein!"

CASE "female"

PRINT "So is Mary Poppins!"

CASE ELSE

PRINT "Please say male or female!"

GOTO 10

END SELECT

The second line (which is numbered 10) makes the computer ask, "Are you male or female?"

The remaining lines are a SELECT statement that analyzes the humanís response. If the human claims to be "male", the computer prints "So is Frankenstein!" If the human says "female" instead, the computer prints "So is Mary Poppins!" If the human says anything else (such as "not sure" or "super-male" or "macho" or "none of your business"), the computer does the CASE ELSE, which makes the computer say "Please say male or female!" and then go back to line 10, which makes the computer ask again, "Are you male or female?"

In that program, the CASE ELSE is called an error handler (or error-handling routine or error trap), since its only purpose is to handle human error (a human who says neither "male" nor "female"). Notice that the error handler begins by printing a gripe message ("Please say male or female!") and then lets the human try again (GOTO 10).

In QBASIC, the GOTO statements are used rarely: theyíre used mainly in error handlers, to let the human try again.

Do you like Mary Poppins? Letís extend that programís conversation. If the human says "female", letís make the computer say "So is Mary Poppins!", then ask "Do you like her?", then continue the conversation as follows:

If human says "yes", make the computer say "I like her too. She is my mother."

If human says "no", make computer say "I hate her too. She owes me a dime."

If human says neither "yes" nor "no", make the computer handle that error.

To accomplish all that, insert the shaded lines into the program:

CLS

10 INPUT "Are you male or female"; a$

SELECT CASE a$

CASE "male"

PRINT "So is Frankenstein!"

CASE "female"

PRINT "So is Mary Poppins!"

20 INPUT "Do you like her"; b$

SELECT CASE b$

CASE "yes"

PRINT "I like her too. She is my mother."

CASE "no"

PRINT "I hate her too. She owes me a dime."

CASE ELSE

PRINT "Please say yes or no!"

GO TO 20

END SELECT

CASE ELSE

PRINT "Please say male or female!"

GOTO 10

END SELECT

Weird programs

The computerís abilities are limited only by your own imagination ó and your weirdness. Here are some weird programs from weird minds.Ö

Friends Like a human, the computer wants to meet new friends. This program makes the computer show its true feelings:

CLS

10 INPUT "Are you my friend"; a$

SELECT CASE a$

CASE "yes"

PRINT "That's swell."

CASE "no"

PRINT "Go jump in a lake."

CASE ELSE

PRINT "Please say yes or no."

GO TO 10

END SELECT

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."

Watch TV The most inventive programmers are kids. This program was written by a girl in the sixth grade:

CLS

10 INPUT "Can I come over to your house to watch TV"; a$

SELECT CASE a$

CASE "yes"

PRINT "Thanks. I'll be there at 5PM."

CASE "no"

PRINT "Humph! Your feet smell, anyway."

CASE ELSE

PRINT "Please say yes or no."

GO TO 10

END SELECT

When you run that program, the computer asks to watch your TV. If you say "yes", the computer promises to come to your house at 5. If you refuse, the computer insults your feet.

Honesty Another sixth-grade girl wrote this program, to test your honesty:

CLS

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******"

10 INPUT "Do you understand what I said"; a$

SELECT CASE a$

CASE "no"

PRINT "Sorry to have bothered you."

CASE "yes"

PRINT "SSFJSLFKDJFL++++45673456779XSDWFEF/#$&**()---==!!ZZXX"

PRINT "###EDFHTG NVFDF MKJK ==+--*$&% #RHFS SES DOPEKKK DSBS"

INPUT "Okay, what did I say"; b$

PRINT "You are a liar, a liar, a big fat liar!"

CASE ELSE

PRINT "Please say yes or no."

GO TO 10

END SELECT

When you run that program, lines 2-4 print nonsense. Then the computer asks whether you understand that stuff. If youíre honest and answer "no", the computer will apologize. But if you pretend that you understand the nonsense and answer "yes", the computer will print more nonsense, challenge you to translate it, wait for you to fake a translation, and then scold you for lying.

Fancy IF conditions

A Daddy wrote a program for his five-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:

CLS

INPUT "What's your name"; n$

INPUT "What's 2 and 2"; a

IF n$ = "Daddy" THEN PRINT "Yes, Daddy is always right": END

IF a = 4 THEN PRINT "No, 2 and 2 is 22" ELSE PRINT "No, 2 and 2 is 4"

Different relations

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 the dictionary

IF b$ > "male" If b$ is a word that comes after "male" in the dictionary

In the IF statement, the symbols =, <, >, <=, >=, and <> are called relations.

When writing a relation, mathematicians and computerists habitually put the equal sign last:

Right Wrong

<= =<

>= =>

When you press the ENTER key at the end of the line, the computer will automatically put your equal signs last: the computer will turn any "=<" into "<="; it will turn any "=>" into "<=".

To say "not equal to", say "less than or greater than", like this: <>.

OR

The computer understands the word OR. For example, hereís how to say, "If x is either 7 or 8, print the word wonderful":

IF x = 7 OR x = 8 THEN 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 THEN PRINT "wonderful" ("x = 7" and "x = 8" are conditions.)

Wrong: IF x = 7 OR 8 THEN PRINT "wonderful" ("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 THEN 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 THEN 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 THEN PRINT "that's good"

Can a computer be President?

To become President of the United States, you need four 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 four qualities the computer has! The word PRINT turns the computer into a good speech-maker: by using the word PRINT, you can make the computer write whatever speech you wish. The word INPUT turns the computer into a good listener: by using the word INPUT, you can make the computer ask humans lots of questions, to find out who the humans are and what they want. The word IF turns the computer into a decision maker: the computer can analyze the IF condition, determine whether that condition is true, and act accordingly. Finally, the word GOTO enables the computer to perform loops, which the computer will repeat patiently.

So by using the words PRINT, INPUT, IF, and GOTO, you can make the computer imitate any intellectual human activity. Those four magic words ó PRINT, INPUT, IF, and GOTO ó are the only concepts you need, to write whatever program you wish!

Yes, you can make the computer imitate the President of the United States, do your companyís payroll, compose a beautiful poem, play a perfect game of chess, contemplate the meaning of life, act as if itís falling in love, or do whatever other intellectual or emotional task you wish, by using those four magic words. The only question is: how? The Secret Guide to Computers teaches you how, by showing you many examples of programs that do those remarkable things.

 

What programmers believe Yes, we programmers believe that all of life can be explained and programmed. We believe all of life can be reduced to just those four concepts: PRINT, INPUT, IF, and GOTO. Programming is the ultimate act of scientific reductionism: programmers reduce all of life scientifically to just four concepts.

The words that the computer understands are called keywords. The four essential keywords are PRINT, INPUT, IF, and GOTO.

The computer also understands extra keywords, such as CLS, LPRINT, WIDTH, SYSTEM, SLEEP, DO (and LOOP), END, SELECT (and CASE), and words used in IF statements (such as THEN, ELSE, ELSEIF, OR, AND). Those extra keywords arenít necessary: if they hadnít been invented, you could still write programs without them. But they make programming easier.

A BASIC programmer is a person who translates an ordinary English sentence (such as "act like the President" or "do the payroll") into a series of BASIC statements, using keywords such as PRINT, INPUT, IF, GOTO, CLS, etc.

The mysteries of life Letís dig deeper into the mysteries of PRINT, INPUT, IF, GOTO, and the extra keywords. The deeper we dig, the more youíll wonder: are you just a computer, made of flesh instead of wires? Can everything that you do be explained in terms of PRINT, INPUT, IF, and GOTO?

By the time you finish The Secret Guide to Computers, youíll know!

Exiting a DO loop

This program plays a guessing game, where the human tries to guess the computerís favorite color, which is pink:

CLS

10 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 10

END IF

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 10, which asks the human again to try guessing the computerís favorite color.

END

Hereís how to write that program without saying GOTO:

CLS

DO

INPUT "What's my favorite color"; guess$

IF guess$ = "pink" THEN

PRINT "Congratulations! You discovered my favorite color."

END

END IF

PRINT "No, that's not my favorite color. Try again!"

LOOP

That new version of the program contains a DO loop. That loop makes the computer do this repeatedly: ask "Whatís my favorite color?" and then PRINT "No, thatís not my favorite color."

The only way to stop the loop is to guess "pink", which makes the computer print "Congratulations!" and END.

EXIT DO

Hereís another way to write that program without saying GOTO:

CLS

DO

INPUT "What's my favorite color"; guess$

IF guess$ = "pink" THEN EXIT DO

PRINT "No, that's not my favorite color. Try again!"

LOOP

PRINT "Congratulations! You discovered my favorite color."

That programís DO loop makes the computer do this repeatedly: ask "Whatís my favorite color?" and then PRINT "No, thatís not my favorite color."

The only way to stop the loop is to guess "pink", which makes the computer EXIT from the DO loop; then the computer proceeds to the line underneath the DO loop. That line prints:

Congratulations! You discovered my favorite color.

LOOP UNTIL

Hereís another way to program the guessing game:

CLS

DO

PRINT "You haven't guessed my favorite color yet!"

INPUT "What's my favorite color"; guess$

LOOP UNTIL guess$ = "pink"

PRINT "Congratulations! You discovered my favorite color."

That programís DO loop makes the computer do this repeatedly: say "You havenít guessed my favorite color yet!" and then ask "Whatís my favorite color?"

The LOOP line makes the computer repeat the indented lines again and again, UNTIL the guess is "pink". When the guess is "pink", the computer proceeds to the line underneath the LOOP and prints "Congratulations!".

Achieving the goal The LOOP UNTILís condition (guess$ = "pink") is called the loopís goal. The computer does the loop repeatedly, until the loopís goal is achieved. Hereís how.Ö

The computer does the indented lines, then checks whether the goal is achieved yet. If the goal is not achieved yet, the computer does the indented lines again, then checks again whether the goal is achieved. The computer does the loop again and again, until the goal is achieved. Then the computer, proud at achieving the goal, does the programís finale, which consists of any lines under the LOOP UNTIL line.

UNTIL versus EXIT Saying ó

LOOP UNTIL guess$ = "pink"

is just a briefer way of saying this pair of lines:

IF guess$ = "pink" THEN EXIT DO

LOOP

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:

CLS

FOR x = 1 TO 20

PRINT x

NEXT

The second line (FOR x = 1 TO 20) says that x will be every number from 1 to 20; so x will be 1, then 2, then 3, etc. The line underneath, which is indented, says what to do about each x; it says to PRINT each x.

Whenever you write a program that contains the word FOR, you must say NEXT; so the bottom line says NEXT.

The indented line, which is between the FOR line and the NEXT line, is the line that the computer will do repeatedly; so the computer will repeatedly PRINT x. The first time the computer prints x, the x will be 1, so the computer will print:

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!"

PRINT

NEXT

 

At the top of the program, say CLS. At the end of the song, print the closing couplet:

CLS

FOR x = 2 TO 5

PRINT "I saw"; x; "men"

PRINT "meet"; x; "women."

PRINT "Tra-la-la!"

PRINT

NEXT

PRINT "They all had a party!"

PRINT "Ha-ha-ha!"

That program makes the computer print the entire song.

Hereís an analysis:

CLS

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!"

PRINT

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:

CLS

FOR i = 2 TO 5

PRINT "I saw"; i; "men"

PRINT "meet"; i; "women."

PRINT "Tra-la-la!"

PRINT

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:

CLS

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:

CLS

DO

PRINT "love"

LOOP

That program prints "love" again and again, until you abort the program by pressing Ctrl with PAUSE/BREAK.

But what if you want to print "love" just 20 times? This program prints "love" just 20 times:

CLS

FOR i = 1 TO 20

PRINT "love"

NEXT

As you can see, FOR...NEXT resembles DO...LOOP but is smarter: while doing FOR...NEXT, the computer counts!

Poem This program, which you saw before, prints many copies of a poem:

CLS

DO

LPRINT "I'm having trouble"

LPRINT "With my nose."

LPRINT "The only thing it does is:"

LPRINT "Blows!"

LPRINT CHR$(12);

LOOP

It prints the copies onto paper. It prints each copy on a separate sheet of printer. It keeps printing until you abort the program ó or the printer runs out of paper.

Hereís a smarter program, which counts the number of copies printed and stops when exactly 4 copies have been printed:

CLS

FOR i = 1 TO 4

LPRINT "I'm having trouble"

LPRINT "With my nose."

LPRINT "The only thing it does is:"

LPRINT "Blows!"

LPRINT CHR$(12);

NEXT

Itís the same as the DO...LOOP program, except that it counts (by saying "FOR i = 1 TO 4" instead of "DO") and has a different bottom line (NEXT instead of LOOP).

Hereís an even smarter program, which asks how many copies you want:

CLS

INPUT "How many copies of the poem do you want"; n

FOR i = 1 TO n

LPRINT "I'm having trouble"

LPRINT "With my nose."

LPRINT "The only thing it does is:"

LPRINT "Blows!"

LPRINT CHR$(12);

NEXT

When you run that program, the computer asks:

How many copies of the poem do you want?

If you answer 5, then the n becomes 5 and so the computer prints 5 copies of the poem. If you answer 7 instead, the computer prints 7 copies. Print as many copies as you like!

That program illustrates this rule:

To make the FOR...NEXT loop flexible,

say "FOR i = 1 TO n" and let the human INPUT the n.

Count to midnight

This program makes the computer count to midnight:

CLS

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

Semicolon Letís put a semicolon at the end of the indented line:

CLS

FOR i = 1 TO 11

PRINT i;

NEXT

PRINT "midnight"

The semicolon makes the computer print each item on the same line, like this:

1 2 3 4 5 6 7 8 9 10 11 midnight

If you want the computer to press the ENTER key before "midnight", insert a PRINT line:

CLS

FOR i = 1 TO 11

PRINT i;

NEXT

PRINT

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:

CLS

FOR j = 1 TO 3

FOR i = 1 TO 11

PRINT i;

NEXT

PRINT

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:

CLS

PRINT "I'll give you 5 guesses...."

FOR i = 1 TO 5

INPUT "What's my favorite color"; guess$

IF guess$ = "pink" THEN GO TO 10

PRINT "No, that's not my favorite color."

NEXT

PRINT "Sorry, your 5 guesses are up! You lose."

END

10 PRINT "Congratulations! You discovered my favorite color."

PRINT "It took you"; i; "guesses."

Line 2 warns the human that just 5 guesses are allowed. The FOR line makes the computer count from 1 to 5; to begin, i is 1. The INPUT line asks the human to guess the computerís favorite color; the guess is called guess$.

If the guess is "pink", the computer jumps down to the line numbered 10, prints "Congratulations!", and tells how many guesses the human took. But if the guess is not "pink", the computer will print "No, thatís not my favorite color" and go on to the NEXT guess.

If the human guesses 5 times without success, the computer proceeds to the line that prints "SorryÖ You lose."

For example, if the humanís third guess is "pink", the computer prints:

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 five times. The line below the loop (which says to PRINT "Sorry") is the loopís normal exit. But if the human happens to input "pink", the computer jumps out of the loop early, to line 10, which is the loopís abnormal exit.

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 third number from 5 to 17.

So i will be 5, then 8, then 11, then 14, then 17.

FOR i = 17 TO 5 STEP -3 The i will be every third number from 17 down to 5.

So i will be 17, then 14, then 11, then 8, then 5.

To count down, you must use the word STEP. To count from 17 down to 5, give this instruction:

FOR i = 17 TO 5 STEP -1

This program prints a rocket countdown:

CLS

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.

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 top of the program, just under the CLS, like this:

CLS

DATA meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas

You must tell the computer to READ the DATA:

CLS

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":

CLS

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":

CLS

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 that no 9th data item exists, and gripe by saying:

Out of DATA

Then press ENTER.

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:

CLS

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:

CLS

DATA meat,potatoes,lettuce,tomatoes,honey,cheese,onions,peas

DATA end

DO

READ a$: IF a$ = "end" THEN EXIT DO

PRINT "I love "; a$

LOOP

PRINT "Those are the foods I love"

The third line (DATA end) is called the end mark, since it marks the end of the DATA. The READ line means:

READ a$ from the DATA;

but if a$ is the "end" of the DATA, then EXIT from the DO loop.

When the computer exits from the DO loop, the computer prints "Those are the foods I love". So altogether, the entire program makes the computer print:

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" THEN EXIT DO

is called the end routine, because the computer does that routine when it reaches the end of the DATA.

Henry the Eighth

Letís make the computer print this nursery rhyme:

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:

CLS

DATA ice cream,red,ocean,bed,tall grass,to wed

DATA candles,divorce,my kingdom,my horse,you

DATA end

DO

READ a$: IF a$ = "end" THEN EXIT DO

PRINT "I love "; a$

IF a$ = "to wed" THEN PRINT

LOOP

PRINT "Of course, of course,"

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 line 2 and the rest in line 3. Each line of data must begin with the word DATA. In each line, put commas between the items. Do not put a comma at the end of the line.

The program resembles the previous one. The new line (IF a$ = "to wed" THEN PRINT) makes the computer leave a blank line underneath "to wed", to mark the bottom of the first verse.

Pairs of data

Letís throw a party! To make the party yummy, letís ask each guest to bring a kind of food that resembles the guestís name. For example, letís have Sal bring salad, Russ bring Russian dressing, Sue bring soup, Tom bring turkey, Winnie bring wine, Kay bring cake, and Al bring Alka-Seltzer.

Letís send all those people invitations, in this form:

Dear _____________,

person's name

Let's party in the clubhouse at midnight!

Please bring ____.

food

Hereís the program:

CLS

DATA Sal,salad,Russ,Russian dressing,Sue,soup,Tom,turkey

DATA Winnie,wine,Kay,cake,Al,Alka-Seltzer

DATA end,end

DO

READ person$, food$: IF person$ = "end" THEN EXIT DO

LPRINT "Dear "; person$; ","

LPRINT " Let's party in the clubhouse at midnight!"

LPRINT "Please bring "; food$; "."

LPRINT CHR$(12);

LOOP

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).

Since the DATA comes in pairs, the READ line says to READ a pair of data (person$ and food$). The first time that the computer encounters the READ line, person$ is "Sal"; food$ is "salad". Then the LPRINT lines print this message onto paper:

Dear Sal,

We're throwing a party in the clubhouse at midnight!

Please bring salad.

The LPRINT CHR$(12) makes the computer eject the paper from the printer.

Then the computer comes to the word LOOP, which sends the computer back to the word DO, which sends the computer to the READ line again, which reads the next pair of DATA, so person$ becomes "Russ" and food$ becomes "Russian dressing". The LPRINT lines print onto paper:

Dear Russ,

We're throwing a 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 DO, so the computer prints this message onto 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 saying CLS and then feed the computer the DATA. The final program is the same as the previous program, except for the part Iíve shaded:

CLS

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

DO

READ person$, debt$: IF person$ = "end" THEN EXIT DO

LPRINT "Dear "; person$; ","

LPRINT " I just want to remind you..."

LPRINT "that you still owe me "; debt$; "."

LPRINT CHR$(12);

LOOP

PRINT "I've finished writing the letters."

Diets

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:

CLS

DATA Joe,273,219,Mary,412,371,Bill,241,173,Sam,309,198

DATA end,0,0

DO

READ person$, weight.before, weight.after

IF person$ = "end" THEN EXIT DO

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."

PRINT

LOOP

PRINT "Come to the diet clinic!"

Line 2 contains the DATA, which comes in triplets. The first triplet consists of Joe, 273, and 219. Each triplet includes a string (such as Joe) and two numbers (such as 273 and 219), so line 3ís end mark also includes a string and two numbers: itís the word "end" and two zeros. (If you hate zeros, you can use other numbers instead; but most programmers prefer zeros.)

The READ line says to read a triplet: a string (person$) and two numbers (weight.before and weight.after). The first time the computer comes to the READ statement, the computer makes person$ be "Joe", weight.before be 273, and weight.after be 219. The PRINT lines print this:

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:

CLS

DATA love,death,war

10 DATA chocolate,strawberry

READ a$

PRINT a$

RESTORE 10

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 10 tells the READ to skip ahead to DATA line 10, so the READ line reads "chocolate" instead. The entire program prints:

love

chocolate

So saying "RESTORE 10" makes the next READ skip ahead to DATA line 10. If you write a new program, saying "RESTORE 20" makes the next READ skip ahead to DATA line 20. Saying just "RESTORE" makes the next READ skip back to the beginning of the first DATA line.

Continents This program prints the names of the continents:

CLS

DATA Europe,Asia,Africa,Australia,Antarctica,North America,South America

DATA end

DO

READ a$: IF a$ = "end" THEN EXIT DO

PRINT a$

LOOP

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:

CLS

DATA Europe,Asia,Africa,Australia,Antarctica,North America,South America

DATA end

FOR i = 1 TO 2

DO

READ a$: IF a$ = "end" THEN EXIT DO

PRINT a$

LOOP

PRINT "Those are the continents."

PRINT

RESTORE

NEXT

After that program says to PRINT "Those are the continents", the program says to PRINT a blank line and then RESTORE. The word RESTORE makes the READ go back to the beginning of the DATA, so the computer can READ and PRINT the DATA a second time without saying "Out of DATA".

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:

CLS

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:

CLS

DATA white,blanc,yellow,jaune,orange,orange,red,rouge

DATA green,vert,blue,bleu,brown,brun,black,noir

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 DO loop. Hereís the complete program:

CLS

DATA white,blanc,yellow,jaune,orange,orange,red,rouge

DATA green,vert,blue,bleu,brown,brun,black,noir

INPUT "Which color interests you"; request$

DO

READ english$, french$

IF english$ = request$ THEN EXIT DO

LOOP

PRINT "In French, it's "; french$

Since the READ line is in a DO loop, the computer does the READ line repeatedly. So the computer keeps READing pairs of DATA, until the computer find the pair of DATA that the human requested. For example, if the human requested "red", the computer keeps READing pairs of DATA until it finds a pair whose English word matches the requested word ("red"). When the computer finds that match, the english$ is equal to the request$, so the IF line makes the computer EXIT DO and PRINT:

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 end of the DATA; and when the computer reaches the end mark, make the computer say "I wasnít taught that color":

CLS

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$

DO

READ english$, french$

IF english$ = "end" THEN PRINT "I wasn't taught that color": END

IF english$ = request$ THEN EXIT DO

LOOP

PRINT "In French, it's "; french$

In that program, the DO loopís purpose is to search through the DATA, to find DATA that matches the INPUT. Since the DO loopís purpose is to search, itís called a search loop.

The typical search loop has these characteristics:

It starts with DO and ends with LOOP.

It says to READ a pair of data.

It includes an error trap saying what to do IF you reach the "end" of the data because no match found.

It says that IF you find a match (english$ = request$) THEN EXIT the DO loop.

Below the DO loop, say what to PRINT when the match is found.

Above the DO loop, put the DATA and tell the human to INPUT a search request.

Auto rerun At the end of the program, letís make the computer automatically rerun the program and translate another color.

To do that, make the bottom of the program say GO back TO the INPUT line:

CLS

DATA white,blanc,yellow,jaune,orange,orange,red,rouge

DATA green,vert,blue,bleu,brown,brun,black,noir

DATA end,end

10 INPUT "Which color interests you"; request$

RESTORE

DO

READ english$, french$

IF english$ = "end" THEN PRINT "I wasn't taught that color": GOTO 10

IF english$ = request$ THEN EXIT DO

LOOP

PRINT "In French, it's "; french$

GOTO 10

The word RESTORE, which is above the search loop, makes sure that the computerís search through the DATA always starts at the DATAís beginning.

Press Q to quit That program repeatedly asks "Which color interests you" until the human aborts the program (by pressing Ctrl with PAUSE/BREAK). But what if the humanís a beginner who hasnít learned how to abort?

Letís permit the human to stop the program more easily by pressing just the Q key to quit:

CLS

DATA white,blanc,yellow,jaune,orange,orange,red,rouge

DATA green,vert,blue,bleu,brown,brun,black,noir

DATA end,end

10 INPUT "Which color interests you (press q to quit)"; request$

IF request$ = "q" THEN END

RESTORE

DO

READ english$, french$

IF english$ = "end" THEN PRINT "I wasn't taught that color": GOTO 10

IF english$ = request$ THEN EXIT DO

LOOP

PRINT "In French, it's "; french$

GOTO 10

 

 

END, STOP, or SYSTEM That programís shaded line ends by saying END. Instead of saying END, try saying STOP or SYSTEM.

While the program is running, hereís what the computer does when it encounters END, STOP, or SYSTEM:

STOP makes the program stop immediately. The screen becomes blue and shows the programís lines.

END makes the computer say "Press any key to continue" and wait for the human to press a key (such as F4 or ENTER). When the human finally presses a key, the screen becomes blue and shows the programís lines.

SYSTEM usually has the same effect as END. But if you saved the program onto the hard disk (using a name such as "french.bas") and then ran the program from DOS (by saying "C:\>qbasic /run french"), SYSTEM makes the program stop immediately and makes the screen show "C:\>".

 

Variables & constants

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 contain any arithmetic. For example, since 7+1 contains arithmetic (+), itís not a numeric constant. 8 is a numeric constant, even though 7+1 isnít.

A string constant is a simple string, in quotation marks:

"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"

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.

An expression is a numeric expression or a string expression.

Statements

At the end of a GOTO statement, the line number must be a numeric constant.

Right: GOTO 100 (100 is a numeric constant.)

Wrong: GOTO n (n is not a numeric constant.)

The INPUT statementís prompt must be a string constant.

Right: INPUT "What is your name; n$ ("What is your name" is a constant.)

Wrong: INPUT q$; n$ (q$ is not a constant.)

In a DATA statement, you must have constants.

Right: DATA 8, 1.3E5 (8 and 1.3E5 are constants.)

Wrong: DATA 7+1, 1.3E5 (7+1 is not a constant.)

In the DATA statement, if the constant is a string, you can omit the quotation marks (unless the string contains a comma or a colon).

Right: DATA "Joe","Mary"

Also right: DATA Joe,Mary

Here are the forms of popular BASIC statements:

General form Example

PRINT list of expressions PRINT "Temperature is"; 4 + 25; "degrees"

LPRINT list of expressions LPRINT "Temperature is"; 4 + 25; "degrees"

SLEEP numeric expression SLEEP 3 + 1

GOTO line number or label GOTO 10

variable = expression x = 47 + 2

INPUT string constant; variable INPUT "What is your name"; n$

IF condition THEN list of statements IF a >= 18 THEN PRINT "You": PRINT "vote"

SELECT CASE expression SELECT CASE a + 1

DATA list of constants DATA Joe,273,219,Mary,412,371

READ list of variables READ n$, b, a

RESTORE line number or label RESTORE 10

FOR numeric variable = numeric expression FOR I = 59 + 1 TO 100 + n STEP 2 + 3

TO numeric expression STEP numeric expression

Loop techniques

Hereís a strange program:

CLS

x = 9

x = 4 + x

PRINT x

The third line (x = 4 + x) means: the new x is 4 plus the old x. So the new x is 4 + 9, which is 13. The bottom line prints:

13

Letís look at that program more closely. The second line (x = 9) puts 9 into box x:

┌─────────────┐

box x │ 9 │

└─────────────┘

When the computer sees the next line (x = 4 + x), it examines the equationís right side and sees the 4 + x. Since x is 9, the 4 + x is 4 + 9, which is 13. So the line "x = 4 + x" means x = 13. The computer puts 13 into box x:

┌─────────────┐

box x │ 13 │

└─────────────┘

The programís bottom line prints 13.

Hereís another weirdo:

CLS

b = 6

b = b + 1

PRINT b * 2

The third line (b = b + 1) says the new b is "the old b plus 1". So the new b is 6 + 1, which is 7. The bottom line prints:

14

In that program, the second line says b is 6; but the next line increases b, by adding 1 to b; so b becomes 7. Programmers say that b has been increased or incremented. In the third line, the "1" is called the increase or the increment.

The opposite of "increment" is decrement:

CLS

j = 500

j = j - 1

PRINT j

The second line says j starts at 500; but the next line says the new j is "the old j minus 1", so the new j is 500 - 1, which is 499. The bottom line prints:

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:

CLS

c = 3

DO

PRINT c

c = c + 1

LOOP

In that program, c is called the counter, because it helps the computer count.

The second line says c starts at 3. The PRINT line makes the computer print c, so the computer prints:

3

The next line (c = c + 1) increases c by adding 1 to it, so c becomes 4. The LOOP line sends the computer back to the PRINT line, which prints the new value of c:

4

Then the computer comes to the "c = c + 1" again, which increases c again, so c becomes 5. The LOOP line sends the computer back again to the PRINT line, which prints:

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 for making the computer count:

Start c at some value (such as 3).

Then write a DO loop.

In the DO loop, make the computer use c (such as by saying PRINT c) and increase c (by saying c = c + 1).

Variations To read the printing more easily, put a semicolon at the end of the PRINT statement:

CLS

c = 3

DO

PRINT c;

c = c + 1

LOOP

The semicolon makes the computer print horizontally:

3 4 5 6 7 8 etc.

This program makes the computer count, starting at 1:

CLS

c = 1

DO

PRINT c;

c = c + 1

LOOP

The computer will print 1, 2, 3, 4, etc.

This program makes the computer count, starting at 0:

CLS

c = 0

DO

PRINT c;

c = c + 1

LOOP

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:

DO

READ question$, answer$

LOOP

Hereís the complete program:

CLS

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

DO

READ question$, answer$: IF question$ = "end" THEN EXIT DO

PRINT question$;

INPUT "??"; response$

IF response$ = answer$ THEN

PRINT "Correct!"

ELSE

PRINT "No, the answer is: "; answer$

END IF

LOOP

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 end of the DATA, the computer does an EXIT DO and prints "I hope you enjoyed the quiz!"

Hereís a sample run, where Iíve underlined the parts typed by the human:

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.

Count the correct answers 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:

CLS

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

DO

READ question$, answer$: IF question$ = "end" THEN EXIT DO

PRINT question$;

INPUT "??"; response$

IF response$ = answer$ THEN

PRINT "Correct!"

c = c + 1

ELSE

PRINT "No, the answer is: "; answer$

END IF

LOOP

PRINT "I hope you enjoyed the quiz!"

PRINT "You answered"; c; "of the questions correctly."

At the beginning of the program, the human hasnít answered any questions correctly yet, so the counter begins at 0 (by saying "c = 0"). Each time the human answers a question correctly, the computer does "c = c + 1", which increases the counter. The programís bottom line prints the counter, by printing a message such as:

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:

CLS

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

DO

READ question$, answer$: IF question$ = "end" THEN EXIT DO

PRINT question$;

q = q + 1

INPUT "??"; response$

IF response$ = answer$ THEN

PRINT "Correct!"

c = c + 1

ELSE

PRINT "No, the answer is: "; answer$

END IF

LOOP

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:

CLS

s = 0

DO

PRINT "Now the sum is"; s

INPUT "What number do you want to add to the sum"; x

s = s + x

LOOP

The second line starts the sum at 0. The PRINT line prints the sum. The INPUT line asks the human what number to add to the sum; the humanís number is called x. The next line (s = s + x) adds x to the sum, so the sum changes. The LOOP line sends the computer back to the PRINT line, which prints the new sum. The programís an infinite loop, which you must abort.

Hereís the general procedure for making the computer find a sum:

Start s at 0.

Then write a DO loop.

In the DO loop, make the computer use s (such as by saying PRINT s) and increase s (by saying s = s + the number to be added).

Checking account

If your bankís nasty, it charges you 20Ę to process each good check that you write, and a $15 penalty for each check that bounces; and it pays no interest on the money youíve deposited.

This program makes the computer imitate such a bank.Ö

CLS

s = 0

DO

PRINT "Your checking account contains"; s

1 INPUT "Press d (to make a deposit) or c (to write a check)"; a$

SELECT CASE a$

CASE "d"

INPUT "How much money do you want to deposit"; d

s = s + d

CASE "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 - 15

END IF

CASE ELSE

PRINT "Please press d or c"

GOTO 1

END SELECT

LOOP

In that program, the total amount of money in the checking account is called the sum, s. The second line (s = 0) starts that sum at 0. The first PRINT line prints the sum. The next line asks the human to press "d" (to make a deposit) or "c" (to write a check).

If the human presses "d" (to make a deposit), the computer asks "How much money do you want to deposit?" and waits for the human to type an amount to deposit. The computer adds that amount to the sum in the account (s = s + d).

If the human presses "c" (to write a check), the computer asks "How much money do you want the check for?" and waits for the human to type the amount on the check. The computer adds the 20Ę check-processing fee to that amount (c = c + .2). Then the computer reaches the line saying "IF c <= s", which checks whether the sum s in the account is big enough to cover the check (c). If c <= s, the computer says "Okay" and processes the check, by subtracting c from the sum in the account. If the check is too big, the computer says "That check bounced!" and decreases the sum in the account by the $15 penalty.

How the program is nasty 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 $5. That makes your balance will become negative $4, and the bank will demand that you pay the bank $4 ó 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!

How to stop the nastiness 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 DO:

IF s < 0 THEN 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; $15 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.

CLS

Start the sum at 0: s = 0

Make i go from 7 to 100: FOR i = 7 TO 100

Increase the 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:

CLS

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:

CLS

DATA 5, 3, 6.1, etc.

DATA 0

s = 0

DO

READ x: IF x = 0 THEN EXIT DO

s = s + x

LOOP

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 LOOP 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 DO and PRINT the final sum, s.