User Data, Nested Loops
Let's begin this chapter by divulging the answers to the three problems
at the end of the last chapter. Please remember that your variable names
and the values in your DATA statements will be different. What is important
is that the program gives you the correct answers. First was the "Largest
Number" program. Here is it's listing:
MORE: READ X IF X = -1 THEN GOTO FINISH IF X > LARGEST THEN GOTO UPDATE GOTO MORE UPDATE: LARGEST = X GOTO MORE DATA 6,2,4,8,5,12,45,56,18,54,28,64,53,95,75,51,20,15,30,88,-1 FINISH: PRINT "Largest is"; LARGEST END
Notice how we used the "-1" method to test for the end of actual data.
Next was the "find the average of two numbers" program. It could look something like this:
MORE: READ A, B LET SUM = A + B PRINT SUM / 2 GOTO MORE DATA 1,3,2,4,57,122,6,-9 END
Here is probably how you did the "Consecutive Products" problem:
MORE: READ N O = N + 1 P = N + 2 Q = N + 3 PRINT N * O * P * Q GOTO MORE DATA 9,2,45,54 END
On to bigger and better things. Well, on to other things, anyway. The first thing we will learn in this chapter is how to ask the person running the program for information. You probably noticed that up to now, every time time you run a program, you get the same answer(s). If you are using READ...DATA statements, the only way an operator could change the results is to actually go into the program and change the necessary data. The only problem with that is the program user is not usually the person who wrote the program, so they will have no idea what to change, assuming that the person even knows how to program! What we need is a way for the computer to ask the user for data directly. Would you believe that QBASIC has a function to do just that? It's called the INPUT statement. It would look something like this in a program: INPUT X. When the program gets to the INPUT statement, it types a question mark on the screen and waits for the user to type in the requested number. Incidently, you can also have the statement accept more than one variable at a time, just like the READ statement. It would look like this: INPUT A,B,C. When the program gets to this line, the user must enter the three pieces of data, separated by commas. If only one or two are entered, the computer responds with "Redo from Start" and redisplays the question mark. This is also true if you enter too many pieces of data, or enter something other than numbers. Enough explaining, let's try it in an actual program, like our perimeter thing. Type this program in:
PRINT "This Program computes the perimeter of a rectangle." PRINT "Please enter the length and width of the rectangle," PRINT "Separated by commas." INPUT L, W PRINT "The Perimeter is"; 2 * L + 2 * W END
Go ahead and run the program. The computer will respond:
This Program computes the perimeter of a rectangle. Please enter the length and width of the rectangle, Separated by commas. ?_
and you will see the blinking cursor. Remember that the cursor means the computer is waiting for you to type something in. Go ahead and enter:
and press the Enter key. The computer will respond:
The Perimeter is 26
and you will get the "Press any key to continue" prompt, meaning that the program is done running. If you were to add program lines (The lines in green)
PRINT "This Program computes the perimeter of a rectangle." PRINT "Please enter the length and width of the rectangle," PRINT "Separated by commas." AGAIN: INPUT L, W PRINT "The Perimeter is"; 2 * L + 2 * W GOTO AGAIN END
then the program would type another question mark on the screen and ask for more data. This would make the program an "infinite loop", and would run forever. To stop an infinite loop, or a running program at any point. hold down one of the keys marked "Ctrl" (some keyboards have one; others have two) and while holding that key, press the "Break" key. The word "Break" is printed on the front of a keycap on some computers, and the top on others. Depending on which keyboard you have, it is either on a key labeled "ScrlLk" over on the numeric keypad section, or on a key labeled "Pause" on the right end of the very top row of keys. If you're not sure, check with the manuals that came with your computer.
The user must be somewhat careful what he types in response to the question mark for the INPUT statement. First, the number of entries must match the number of variables in the statement, or he will get the "Redo from Start" message. He will also get this message if he types in any letters (with 2 very specific exceptions - that's in the advanced section) or symbols. For example, fractions cannot be entered. Three-fourths must be entered as a decimal, not a fraction. In other words, the user must type in 0.75 and not 3/4 to enter the value. Incidentally, the zero before the decimal point is optional. The computer will take .75 without complaining, also.
Time to talk about Nested Loops. No, they're not for the birds! Simply put, it is just a loop that is inside another loop. Here is a simple example (if you want, you can type it in):
FOR OUTER = 1 TO 100 FOR INNER = 1 TO 100 PRINT "*"; NEXT INNER PRINT "!"; NEXT OUTER END
What happens? well, the OUTER loop is initialized in the first line. Then the INNER loop gets initialized in the second line. Line 3 prints out an asterisk, and line feed is suppressed (notice the semicolon). Line 4 increments the INNER variable and re-executes the inner loop. This happens 100 times, and then the INNER loop is done. We jump down to line 5, where a single exclamation point is printed. Then the OUTER variable is incremented, and tested back at line 2. That loop hasn't run out yet, so line 3 gets executed. The INNER loop is re-initialized all over again, and the whole process starts again. In this particular case, the OUTER loop goes through 100 "cycles", which means the INNER loop is executed 100 times. Each inner loop runs through 100 of its own "cycles", so some simple multiplication tells us (are you following all of this so far?) that the asterisk is printed a total of 10,000 times! It is printed in 100 sets of 100. In other words, the program prints out 100 "*"'s followed by a single "!". It does this 100 times, for a total of 10,000 "*"'s and 100 "!"'s. Got it? I didn't think so. We'll do a couple of much smaller loops so you can see what is happening. Type this in:
FOR OUTER = 1 TO 4 FOR INNER = 1 TO 4 PRINT "Outer="; OUTER, "Inner ="; INNER NEXT INNER NEXT OUTER END
Now go ahead and run the program. Notice that you get 16 lines? Notice that the INNER loop goes through a complete cycle before the OUTER loop goes to the next value. Each time the OUTER gets another value, the INNER goes through another cycle. It's one dirty way to do multiplication by addition, but has much more interesting uses. One that we will do quite a bit later is for sorting.
Let's move on to some more mathematical functions in QBASIC. You (should) already know four: Addition (+); Subtraction (-); Multiplication (*); Division (/). Just to show you how these work if you haven't experimented with them yet (come on, pay attention - they have all been used in programs so far), type in these lines in the immediate window:
PRINT 27 + 55
PRINT 87 - 39
PRINT 12 * 11
PRINT 1215 / 45
The answers for each are 82, 48, 132, and 27. Let's learn some new functions. We'll need some of these for the next chapter. Here are all of the "non-trigonometric" mathematical functions:
Exponentiation is ^
Absolute Value is ABS(x)
Natural Exponent is EXP(x)
Integer Truncation (what?) is FIX(x)
"Largest" Integer Truncation (huh?) is INT(x)
Natural Logarithm is LOG(x)
Random Number is RND(x)
Sign Determination is SGN(x)
Square Root is SQR(x)
Here's How to use them: To find a "generic" exponent, or in U.S. English, if you wanted to calculate seven to the third power, it would be something like 7^3. Try it now (in the immediate window):
and see what the answer is. Absolute Value is pretty straightforward. It the number is positive, it stays positive. If it's negative, it is made positive. Try these:
Notice that both answers are positive. Next up is natural exponentiation. That is simply the number e raised to the indicated power. e is the symbol used for the natural base. It's value is approximately 2.71828 or so. QBASIC operates using natural logarithms and antilogarithms. For example, to print e raised to the fourth power, type PRINT EXP(4) and voila! There's your answer!
Integer truncation just chops off anything after the decimal point. Type in
and see what you get. Just the 4, of course. Now let's try the Integer function. Type in
and what do you have? 4 again. What's the difference, you ask? Type these in and notice the answers:
AH-HA!! There's the difference! The FIX function just chops off the decimal point and everything after it. The INT function returns the next lower (or more negative) integer. It only makes a difference for negative numbers.
Natural logarithm is the inverse of the natural exponentiation discussed above.
We'll devote a major chunk of a future chapter to random numbers and their uses.
SGN(x) can be kind of nifty. Here's all it does (Type these in):
Notice that positive numbers give you an answer of 1, negative numbers give an answer of -1, and zero gives you back a zero. This can be useful for certain types of decision-making with IF...THEN statements. Can you think of any? I didn't think so
The last one is Square Root. Use it like this:
and you get the correct answer of 25.
No "quizzes" this time. Instead, practice using some of these new math
functions in programs of your own design. Try to think up of some kind
of nifty math problem (borrow somebody's math book and have fun!) and
try writing a program to compute the answer. Be sure to use INPUT statements
for getting the values into the computer!! Next chapter, we will write
a "Square Root" program that uses a "Divide and Average" method for finding
the answer. If you know how this method works, see if you can write the
program ahead of time. Be careful, though - even when written correctly,
the computer will either give a wrong answer or "hang up"! We'll find
ways to fix that by introducing "tolerance acceptance" as well as guarding
against bad inputs (like negative numbers) using something called "input
checking" or "error checking" or something like that. See you next chapter!
Introduced In This Chapter:
Concepts: Basic User Interface, Infinite Loops, Stopping a Running Program,
Nested Loops, More Math Functions,