The Secret Guide to Computers

 home » read » qbasic 2  home  read  buy the book now!  contact us 


 
 

Variables

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.


Since the computer automatically capitalizes computer words (such as CLS), automatically puts spaces around symbols (such as + and =), and lets you type a question mark instead of the word PRINT, you can type just this:

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

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

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

CLS

PRINT 1297.43 * 2; 1297.43 * .05; 1297.43 + 483.19; 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:

CLS

c = 1297.43

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

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

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!

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

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:

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.

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

INPUT "In what year were you born"; y

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

Here’s a sample run:

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

In what year were you born? 1962

In the year 2020, 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:

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.


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:

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.

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

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

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.

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

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 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 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!”.

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.

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,

     Let's 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,

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


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:

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


all content copyright © 2002 | This website is provided as a community service by StaffASAP, the best Applicant Tracking System in the World!