The Secret Guide to Computers

 home » read » qbasic 2


 
 

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

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

 


Helpful hints

Here are some hints to help you master programming.

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


Debugging

If you write and run your own program, it probably won’t work.

Your first reaction will be to blame the computer. Don’t!

The probability is 99.99% that the fault is yours. Your program contains an error. An error is called a bug. Your next task is to debug the program, which means get the bugs out.

Bugs are common; top-notch programmers make errors all the time. If you write a program that works perfectly on the first run and doesn’t need debugging, it’s called a gold-star program and means you should have tried writing a harder one instead!

It’s easy to write a program that’s nearly correct but hard to find the little bug fouling it up. Most time you spend at the computer will be devoted to debugging.

Debugging can be fun. Hunting for the bug is like going on a treasure hunt – or solving a murder mystery. Pretend you’re Sherlock Holmes. Your mission: to find the bug and squish it! When you squish it, have fun: yell out, “Squish!”

How can you tell when a roomful of programmers is happy? Answer: when you hear continual cries of “Squish!”

To find a bug, use three techniques:

Inspect the program.

Trace the computer’s thinking.

Shorten the program.

Here are the details.…

Inspect the program Take a good, hard look at the program. If you stare hard enough, maybe you’ll see the bug.

Usually, the bug will turn out to be just a typing error, a typo. For example.…

Maybe you typed the letter O instead of zero? Zero instead of the letter O?

Typed I instead of 1? Typed 1 instead of I?

Pressed the SHIFT key when you weren’t supposed to? Forgot to press it?

Typed an extra letter? Omitted a letter?

Typed a line you thought you hadn’t? Omitted a line?

You must put quotation marks around each string, and a dollar sign after each string variable:

Right:    a$ = "jerk"

Wrong:  a$ = jerk

Wrong:  a = "jerk"

Here are three reasons why the computer might print too much:

1. You forgot to insert the word END or EXIT DO into your program.

2. Into a DO loop or FOR loop, you inserted a PRINT line that should be outside the loop.

3. When you started typing the program, you forgot to choose New from the file menu; so the computer is including part of the previous program.


Trace the computer’s thinking If you’ve inspected the program thoroughly and still haven’t found the bug, the next step is to trace the computer’s thinking. Pretend you’re the computer. Do what your program says. Do you find yourself printing the same wrong answers the computer printed? If so, why?

To help your analysis, make the computer print everything it’s thinking while it’s running your program. For example, suppose your program uses the variables b, c, and x$. Insert lines such as these into your program:

10 PRINT "I'm at line 10.  The values are"; b; c; x$

20 PRINT "I'm at line 20.  The values are"; b; c; x$

Then run the program. Those extra lines tell you what the computer is thinking about b, c, and x$ and also tell you how many times the computer reached lines 10 and 20. For example, if the computer prints what you expect in line 10 but prints strange values in line 20 (or doesn’t even get to line 20), you know the bug occurs after line 10 but before line 20.

Here’s a good strategy. Halfway down your program, insert a line that says to print all the values. Then run your program. If the line you inserted prints the correct values, you know the bug lies underneath that line; but if the line prints wrong values (or if the computer never reaches that line), you know the bug lies above that line. In either case, you know which half of your program contains the bug. In that half of the program, insert more lines, until you finally zero in on the line that contains the bug.

Shorten the program When all else fails, shorten the program.

Hunting for a bug in a program is like hunting for a needle in a haystack: the job is easier if the haystack is smaller. So make your program shorter: delete the last half of your program. Then run the shortened version. That way, you’ll find out whether the first half of your program is working the way it’s supposed to. When you’ve perfected the first half of your program, tack the second half back on.

Does your program contain a statement whose meaning you’re not completely sure of? Check the meaning by reading a book or asking a friend; or write a tiny experimental program that contains the statement, and see what happens when you run it.

Hint: before you shorten your program (or write tiny experimental ones), save the original version (by choosing Save from the file menu), even though it contains a bug. After you’ve played with the shorter versions, retrieve the original (by choosing Open from the file menu) and fix it.

To write a long, correct program easily, write a short program first and debug it, then add a few more lines and debug them, add a few more lines and debug them, etc. So start with a small program, perfect it, then gradually add perfected extras so you gradually build a perfected masterpiece. If you try to compose a long program all at once – instead of building it from perfected pieces – you’ll have nothing more than a mastermess – full of bugs.

Moral: to build a large masterpiece, start with a small masterpiece. To build a program so big that it’s a skyscraper, begin by laying a good foundation; double-check the foundation before you start adding the program’s walls and roof.


Error messages

If the computer can’t obey your command, the computer will print an error message. The following error message are the most common.…

Syntax errors If you say “prind” instead of “print”, the computer will say:

Syntax error

That means the computer hasn’t the faintest idea of what you’re talking about!

If the computer says you have a syntax error, it’s usually because you spelled a word wrong, or forgot a word, or used a word the computer doesn’t understand. It can also result from wrong punctuation: check your commas, semicolons, and colons. It can also mean your DATA statement contains a string but your READ statement says to read a number instead; to fix that problem, change the READ statement by putting a dollar sign at the end of the variable’s name.

If you try to say PRINT 5 + 2 but forget to type the 2, the computer will say:

Expected: expression

If you type a left parenthesis but forget to type the right parenthesis that matches it, the computer will say:

Expected: )

If you accidentally type extra characters (or an unintelligible word) at the end of the line, the computer will say:

Expected: end-of-statement

Numeric errors If the answer to a calculation is a bigger number than the computer can handle, the computer will say:

Overflow

To help the computer handle bigger numbers, remember to put a decimal point in any problem whose answer might be bigger than 32 thousand.

If you try to divide by zero, the computer will say:

Division by zero

If you feed the computer a number that’s inappropriate, the computer will say:

Illegal function call

That’s what the computer will say if you try saying WIDTH 50 instead of WIDTH 40, or you try saying LPRINT CHR$(1200) instead of LPRINT CHR$(12).

Printer errors If your printer runs out of paper, the computer will say:

Out of paper

If your printer isn’t communicating well with the computer, the computer will say:

Device fault

That means printer’s cable to the computer is unplugged or loose or defective or plugged into the wrong socket, or the printer is turned off, or the printer is off-line (because you pressed a button that turned off the printer’s ON LINE light), or the paper is jammed, or there’s no more ink left, or the printer broke.


Logic errors Some commands come in pairs.

The words DO and LOOP form a pair. If you say DO but no line says LOOP, the computer will gripe by saying:

DO without LOOP

If you say LOOP but no line says DO, the computer will say:

LOOP without DO

The words FOR and NEXT form another pair. If part of the pair is missing, the computer will say –

FOR without NEXT

or:

NEXT without FOR

If a line’s first word is SELECT, you’re supposed to have a line below saying END SELECT. If you say SELECT but no line says END SELECT, the computer will say:

SELECT without END SELECT

If you say END SELECT but no line’s first word is SELECT, the computer will say:

END SELECT without SELECT

Between the SELECT and END SELECT lines, you’re supposed to have several lines saying CASE. If you say CASE but no line’s first word is SELECT, the computer will say:

CASE without SELECT

If you say GOTO 10, the computer tries to find a line numbered 10. If you say GOTO joe, the computer tries to find a line named joe. If there’s no line numbered 10 or no line named joe, the computer will say:

Label not defined

Here are other messages about unmatched pairs, involving IF:

ELSE without IF

END IF without block IF

Block IF without END IF

If you say READ but the computer can’t find any more DATA to read (because the computer has read all the DATA already), the computer will say:

Out of DATA

The computer handles two major types of info: numbers and strings. If you feed the computer the wrong type of information – if you feed it a number when you should have fed it a string, or you feed it a string when you should have fed it a number – the computer will say:

Type mismatch

When you feed the computer a string, you must put the string in quotation marks, and put a dollar sign after the string’s variable. If you forget to type the string’s quotation marks or dollar sign, the computer won’t realize it’s a string; the computer will think you’re trying to type a number instead; and if a number would be inappropriate, the computer will say “Type mismatch”. So when the computer says “Type mismatch”, it usually means you forgot a quotation mark or a dollar sign.


PAUSE key

Magicians often say, “The hand is quicker than the eye.” The computer’s the ultimate magician: the computer can print information on the screen much faster than you can read it.

When the computer is printing faster than you can read, tap the PAUSE key. (If your keyboard is modern, that’s the last key in the top row. If your keyboard is old-fashioned, no key says PAUSE on it, so do this instead: while holding down the Ctrl key, tap the NUM LOCK key.)

Then the computer will pause, to let you read what’s on the screen.

When you’ve finished reading what’s on the screen and want the computer to stop pausing, press the ENTER key. Then the computer will continue printing rapidly, where it left off.

If your eyes are as slow as mine, you’ll need to use the PAUSE key often! You’ll want the computer to pause while you’re running a program containing many PRINT statements (or a PRINT statement in a loop).

F keys

You already learned that to run your program, you press SHIFT with F5; and while viewing the blue screen, you can peek at the black screen instead by pressing F4 (and then pressing F4 again to return to the blue screen). Here are other F keys you can press.…

F6 (immediate window) Near the bottom of QBASIC’s blue screen, you see the word “Immediate”. The area below that word is called the immediate window. The area above that word is called the program window.

Usually you type in the program window. That’s where you type your programs.

To use the immediate window, press the F6 key. That moves the cursor (blinking underline) down to the immediate window. Whatever you type afterwards will be in the immediate window.

Any command you type in the immediate window will be obeyed by the computer immediately. (The computer will not wait for you press SHIFT F5.)

For example, in the immediate window type this:

PRINT 4 + 2

When you press the ENTER key at the end of that line, the computer obeys that line immediately; the computer immediately makes the screen turn black and prints the answer (6) near the bottom of the black screen. When you finish admiring the answer, press the F4 key to switch back to the blue screen.

The cursor will still be in the immediate window. Go ahead: type another PRINT line in the immediate window. When you press the ENTER key at the end of the line, the computer will print the answer on the black screen. Press F4 again, so you see the blue screen again.

You can use the immediate window to quickly PRINT the answers to calculations (so you can discard your calculator) and to explore advanced aspects of the PRINT command.

When you get tired of using the immediate window, press the F6 key again, which moves the cursor back up to the program window.

Try this experiment: in the program window, write a program and run it (by pressing SHIFT F5). When the program finishes running (or gets interrupted by an error), go down to the immediate window (by pressing F6) and tell the computer to PRINT the program’s variables. For example, if the program mentioned a variable called x, say this in the program window:

PRINT x

That makes the computer print the number that x stands for. That info will help you debug the program.

F9 (breakpoint) If you point at a line of your program (by using the arrow keys) and then press the F9 key, the line turns red. Try it! Make several lines in your program turn red.

So when pointing at a line, pressing F9 makes the line turn red; pressing F9 again makes the line turn back to blue.

Try this experiment: type a long program (containing 5 lines or more), and make two of the lines turn red. Make the red lines be in the middle of the program, instead of being the top or bottom lines.

When you tell the computer to run the program (by pressing SHIFT with F5), the computer starts running the program; but when the computer reaches a red line, it pauses at the beginning of that line and shows you the blue screen again.

While the computer pauses at the red line, do whatever you wish! For example:

You can peek at the black screen (by pressing F4 to see the black screen, then pressing F4 again to return to the blue screen).

You can use the immediate window (by pressing F6, then typing a PRINT command in the immediate window, then pressing F6 to return to the program window).

You can edit your program.

If you press F5, the computer will continue running the program: it will obey that red line and the lines underneath. If the computer comes to another red line, the computer will pause at that red line also.

Pressing F5 makes the computer continue where it left off. Pressing SHIFT with F5 makes the computer run the program from the beginning instead.

Each red line is called a breakpoint, because when the computer is running a program and encounters a red line, the computer breaks its train of thought and pauses.

If you’ve turned many lines red, here’s how to get rid of all the redness: choose “Clear All Breakpoints” from the Debug menu (by pressing Alt then D then C).

F7 (run to here) To have fun, make sure none of the lines in your program is red; then point at a line in the middle of your program (by using the arrow keys), and press F7.

The computer will temporarily turn the line red (so the line becomes a breakpoint). Then the computer will run the program up to that line. Then the computer will get rid of the red.

So if you point at a line and then press F7, the computer will run just the program’s beginning, up to that line.

Notice the contrast:

Pressing SHIFT with F5 runs the whole program.

Pressing F7 runs just the program’s beginning.

F8 (single step) Instead of telling the computer to run your entire program, you can tell the computer to run just one line at a time, as slowly as you wish. Here’s how: press the F8 key. Each time you press the F8 key, the computer will run one more line of your program. So if you press the F8 key three times, the computer will run three lines of your program.

Pressing F8 makes the computer run one more line, then show you the blue screen again. At the blue screen, do whatever you wish: you can press F4 (to peek at the black screen), or press F6 (to move to the immediate window), or edit your program, or press F8 again (to run the next line).

The first time you press F8, the computer typically runs the program’s first line; but if the computer was in the middle of running your program and was interrupted (by a red breakpoint line or a line saying STOP), pressing F8 makes the computer continue where it left off and do one more line.


Apostrophe

Occasionally, jot a note to remind yourself what your program does and what the variables stand for. Slip the note into your program by putting an apostrophe before it:

'This program is another dumb example, written by Russy-poo.

'It was written on Halloween, under a full moon.

CLS

c = 40 'because Russ has 40 computers

h = 23 'because 23 of his computers are haunted

PRINT c - h 'That is how many computers are unhaunted.

When you run the program, the computer ignores everything that’s to the right of an apostrophe. So the computer ignores lines 1 & 2; in lines 4 & 5, the computer ignores the “because…”; in the bottom line, the computer ignores the comment about being unhaunted. Since c is 40, and h is 23, the bottom line makes the computer print:

 17

Everything to the right of an apostrophe is called a comment (or remark). While the computer runs the program, it ignores the comments. But the comments remain part of the program; they appear on the blue screen with the rest of the program. Though the comments appear in the program, they don’t affect the run.

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

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.


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.

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


all content copyright © 2002 / web design by josh feingold