Chapter 8: Difference between revisions

From BR Wiki
Jump to navigation Jump to search
No edit summary
Line 33: Line 33:
  00010 FOR WAX = 3 TO 16
  00010 FOR WAX = 3 TO 16


The beginning value of WAX (the loop variable) will be 4; the ending value will be 16.  The loop will be executed a total of 13 times.
The beginning value of WAX (the loop variable) will be 3; the ending value will be 16.  The loop will be executed a total of 14 times.


  00100 FOR I = N*.5 TO 10
  00100 FOR I = N*.5 TO 10

Revision as of 17:43, 8 March 2017

Looping and more branching experience is what you’ll learn in this chapter. When you’re done you should be able to:

  •   Use the FOR and NEXT statements to create a loop.
  •   Utilize the loop variable in expressions.
  •   Understand the execution sequence of nested FOR/NEXT loops.
  •   Describe an array, and understand the difference between a one-dimensional and a two-dimensional array.
  •   Use the ON GOTO statement in a program.
  •   Use the ON GOSUB statement in a program.

8.1 FOR / NEXT, ON GOTO, ON GOSUB & RENUM

So far you have learned about the type of loop that you can create with GOTO statements, and you have experienced what can happen when a program enters an infinite loop.  Business Rules! also allows you to use two separate statements, FOR and NEXT, to create loops that are executed in a specified number of times.

FOR / NEXT loops always begin with a FOR statement and end with a NEXT statement.  The following section of code shows an example. Type this example into Business Rules! and RUN it:

00010 FOR X=1 TO 10
00020   PRINT X
00030 NEXT X

The FOR statement in line 10 specifies the name of the loop variable, X, and beginning and ending values for that variable.  The first time that this loop is executed, X will equal one.  The second time the loop is executed, X will equal two, then three, and so on until its value is greater than 10 (which is the specified ending value).

The NEXT statement at line 30 simply marks the end of the loop.  When Business Rules! reaches the NEXT statement, it returns to the FOR statement and tests the value of X.  If X is less than or equal to the specified ending value (10), then the loop is executed.  If X is greater than 10, program execution jumps to the first statement after the end of the loop.

All the statements between FOR and NEXT are executed as part of the loop.  As in the above case, statements which are contained within a loop are usually tabbed in a few spaces so that it is easy to identify that they belong to the loop.

Focus on FOR

The syntax of the FOR statement is as follows:                             

The “num-var” is the name of the loop variable; it can be any numeric variable.The “num-expr TO num-expr” portion of the statement identifies the beginning and ending variables (a “num-expr” can be any numeric expression).The “STEP num-expr” portion of the statement is optional.  It tells Business Rules! how much to increment (add to) the loop variable each time the loop is executed; when a STEP amount is not specified, Business Rules! assumes a default value of one.

The following are examples of FOR statements:

00010 FOR WAX = 3 TO 16

The beginning value of WAX (the loop variable) will be 3; the ending value will be 16.  The loop will be executed a total of 14 times.

00100 FOR I = N*.5 TO 10

The Numeric expression N*.5 determines the beginning value of I.  If N equals 10, the beginning value will be 5.

01000 FOR T = 10 TO -10 STEP -1

The beginning value of T is 10; the ending value is -10.  The increment is -1 (if it were +1, the loop would not execute).  The loop will be executed a total of 21 times.

10000 FOR N = 100 TO 400 STEP 100

The beginning value of N is 100; the ending value is 400.  N will increment by 100 each of the four times the loop is executed.

Focus on NEXT

NEXT is one of Business Rules!'s shortest statements. Its syntax is as follows:

The NEXT statement’s “num-var” must be the same num-var which is specified in the corresponding FOR statement.

RIGHT WRONG
00070 FOR P = 1 TO 30 00070 FOR P = 1 TO 30
00080 PRINT P  00080 PRINT P
00090 NEXT P 00090 NEXT T

The num-var in 90 must match the num-var in line 70.

Quick Quiz 8.1

1. How many times will Business Rules! execute a FOR/NEXT loop?

a)   The number of times specified with the STEP option.
b)   An infinite number of times.
c)   Until the value of the loop variable is greater than the specified ending value.

2. Which item in the following FOR statement is the loop variable?

00010 FOR P = I TO X STEP N

a)   P
b)   I
c)   X
d)   N

3. What does the STEP option do?

a)   Determines the amount that the loop variable is to be incremented.
b)   Specifies the number of times that a loop is to be executed.
c)   Sets the default value of the loop variable.

Answers 8.1

8.2 Using the FOR / NEXT loop

FOR / NEXT loops are useful for a number of applications.  They can be used to repeat execution of a set of program lines N number of times or to cause time delays in your program.  The increment of the loop variable can be used in mathematical operations.  FOR / NEXT loops are also often used with arrays, which we will discuss later in this chapter.

Using FOR/NEXT to repeat execution of a set of program lines. Imagine that you are writing a computer game called GUESSWORD.  The object of the game is to guess the program’s secret word.

The program then tells you how many of the letters in the word you guessed are also in the computer’s word.  To make the game both fun and challenging for a wide variety of people, you decide to let the player choose the number of chances he or she gets to guess the correct word.

In order for this program to work properly, you would need to write a routine that compares each letter in the guessed word to each letter in the secret word.  This routine could then be enclosed in a FOR / NEXT loop that is repeated as many times as the player said it should be.  The following example shows the structure of this programming problem:  

(The word=comparison routine goes where you see the "o")

Using LOOPS to create time delays

The following example waits for an event to occur. The maximum time it will wait is 10 seconds. The event is the creation of a report data file named "report.prn" located in the "prl" folder.

01010 FOR X = 1 TO 10 
01020    SLEEP(1)
01030    IF EXISTS("prl\report.prn") THEN GOTO PRINT_REPORT
01040 NEXT X 

When Business Rules! begins executing the above loop, it assigns a value of one to X.  The second time the loop is executed Business Rules! replaces the value of X with a 2. It continues to reassign the value of X, each time the loop is executed, until X is greater than 10.

However, if the file "report.prn" is placed into the "prl" folder before 10 seconds have elapsed, then the program will exit the loop and proceed at the PRINT_REPORT label.

Using the LOOP variable in mathematical operations

You have seen how the loop variable in the FOR/NEXT loop can be used to execute a procedure a specific number of times.  This variable does not only serve as the loop’s counting mechanism, however, it can be used in other expressions within the loop as well.

Let’s look at an example.  Imagine that you have a young cousin who is just learning her multiplication tables.  She comes and asks you to write down the products in the 3x table.  You write them down for her, and a couple days later she comes back and asks for the products in the 4x table.  You can see that this could go on for quite a while, so you decide to write a program that produces the answers for each multiplication table as your cousin needs them.

How will you go about this?  Look at the following section of program code.  It accomplishes the same thing as the two that follow it, but more efficiently.  Line 20 assigns the operator’s choice of the times table to the variable TABLE.  The FOR statement in line 30 then assigns NUMBER to be the loop variable.  Each time the loop is executed, NUMBER will increase by one.  Also each time the loop is executed, line 40 multiplies TABLE and the current value of NUMBER together to come up with the next times table product.

Nested FOR / NEXT loops

It is possible to nest FOR/NEXT loops, or put one loop inside another.  It is important to understand the execution sequence of this programming device. Study the following set of nested FOR/NEXT loops and see if you can predict their execution sequence.  How many times will the outer loop be executed?  How many times will the inner loop be executed?

00010 FOR A=1 TO 4 -------------------------------------| 
00015   PRINT “A”                                   		  outer loop 
00020   FOR B=1 TO 2 -------------------|  
00025     PRINT TAB(5);”B”      	 inner loop  
00030   NEXT B ------------------------------|   
00040 NEXT A -----------------------------------------------| 

Once you have tried to determine the execution sequence, type the example into Business Rules! and RUN it.  You should find that the program prints in two columns.  Each time that Business Rules! begins execution of the outer loop, it prints an “A” in the first column.  And each time that Business Rules! executes the inner loop, it prints a “B” in column six of the screen.  Count the number of times and the order in which Business Rules! executes each group.  Were your guesses about the execution sequence correct?

A rule to remember about nested FOR/NEXT loops is that the inner loop is executed its specified number of times each time that the outer loop is executed. 

Keep in mind that a nested FOR/NEXT loop cannot be half in and half out of another loop: it must be contained entirely within another loop.  The following right and wrong examples illustrate this point.

Right Wrong
00010 for t=1 to 6 00010 for t=1 to 6
00020 for n=0 to -3 step -1 00020 for n=0 to -3 step -1
00030 next n 00030 next t
00040 next t 00040 next n

The RENUM Command

The RENUM command is a handy little command with an amazing set of powers.  It not only knows how to renumber an irregular list of line numbers (due to insertions, deletions and such) with perfectly incremented replacements, but it also keeps track of the line references within your code and changes them right along with its renumbering.  As an example, look at the following lines of code (which by the way, contain an infinite loop):

00005 PRINT “What is your password?” 
00012 INPUT PASSWORD$ 
00017 IF PASSWORD$=”WICHITA” OR PASSWORD$=“Wichita” THEN GOTO 30 ELSE GOTO 20 
00020 PRINT “Access denied” 
00025 GOTO 4000 
00030 PRINT “Hello, Mark.” 
o 
o 
o 
04000 END 

To renumber this section of code so that the first line is 00010 and each following line increments by 10, you enter: RENUM ENTER

This command would change the example to:

00010 PRINT “What is your password?” 
00020 INPUT PASSWORD$ 
00030 IF PASSWORD$=”WICHITA” OR “Wichita” THEN GOTO 60 

ELSE GOTO 40

00040 PRINT “Access denied” 
00050 GOTO 4540 
00060 PRINT “Hello, Mark.” 
o 
o 
o 
04540 END 

Notice that the line-ref (30) of the GOTO statement in line 40 is changed right along with the number of the line that it refers to.

Practice with nested FOR / NEXT LOOPS

The best way to learn about nesting a FOR/NEXT loop is to do it for yourself.  We’ll start with one loop at a time.

Let’s imagine that you are writing a program and you want it to start in a cheerful way.  You decide that one way to do this is to ask the user’s name, then send that person a message of “Hi,” the person’s name, and an exclamation point.  And just for fun, you decide to send the same message ten times so that it scrolls partly up the screen.  Go ahead and write the program code (using a FOR/NEXT loop) that would provide output similar to the following:

Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 
Hi Billy! 

Now let’s imagine that after running the section of program code you’ve just created, you decide each of the ten “Hi Billy!” lines should appear farther apart.  The way that Business Rules! would accomplish this is to PRINT several blank lines between each “Hi Billy!” line.  The following FOR/NEXT loop, inserted into the middle of your current FOR/NEXT loop, should do just this.  Go ahead and place this loop into your own program; you may need to do some experimenting to determine exactly where it should go.  We provide line numbers in this example, but you may need to change them.

00030    FOR S=1 TO 15 
00040      PRINT 
00050    NEXT S 

When you now RUN this double-loop program, the ten “Hi!” messages should scroll up the left side of the screen at 15-line intervals. But wait!  Those messages scroll too fast!  Let’s insert a third FOR/NEXT loop inside the second one to slow the whole process down.  It should look something like the following:

00043       FOR T=1 TO 500000 
00047       NEXT T 

This will cause the computer to count to 500,000 every time it prints something, slowing the whole process down so we can watch the messages scroll past. You may have to experiment with different values to get a value that runs at a good speed on your computer.   Using a FOR/NEXT loop to slow something down is hugEly dependant upon the speed of your computer. A better way to slow your program down is to use the SLEEP command. Erase the last for next loop you added by deleting lines 43 and 47 (or whichever line numbers they have in your code) from your program. To do this, you have to type "DEL 43" and press enter. Then type "DEL 47" and press enter. Now, add a new line that looks like the following:

00045       SLEEP(.05) 

The sleep command will cause your computer to rest for a set period of time. You specify the time to sleep in seconds. This command makes the computer rest for one twentieth of a second between each print statement.   You can use the RENUM command to renumber your program at any time.

Quick Quiz 8.2

1. How many total times will the inner FOR/NEXT loop in the following example be executed?

00030 FOR X = 10 TO -10 STEP -4 
00040   FOR Y = 1 TO 3 
00050   NEXT Y 
00060 NEXT X 

a)   60 times.
b)   3  times.
c)   18 times.
d)   6  times.

2. What does the RENUM command do?
a)   Changes the number of times a FOR/NEXT loop is executed.
b)   Renumbers an irregular listing of program lines.
c)   Goes through an entire program and changes all line references to the specified number.

3. Which of the following is not true about nested FOR/NEXT loops?
a)   An inner loop must be contained entirely within the next outer loop.
b)   Business Rules! allows you to next up to 20 loops at a time.
c)   A nested loop can share a NEXT statement with its outer loop.

Answers 8.2

Mid-Chapter Exercise

Create a program that prints a triangle of stars on your screen. It should look something like this:

  • hint... you will need to use two FOR statements within each other to make it work. Begin by writing a program to print the number of stars that the user requests, then modify it to output lines of stars as seen above.

Solution

8.3 The ON GOTO statement

You have already learned how the GOTO and GOSUB statements can be used to unconditionally transfer executions to another line or subroutine of a program.  ON GOTO and ON GOSUB are similar statements that conditionally transfer execution to another line or subroutine.  The Reason these transfers are considered conditional is that they make the transfer based on the value of a numeric expression in the statement.

The ON GOTO statement

Let’s look at the general syntax of the ON GOTO statement:

line# ON num-expr GOTO line-ref, line-ref, .... NONE line-ref 

1. The ON keyword is always separated from the GOTO keyword by a “num-expr”, or numeric expression.  (Numeric expressions can be numeric constants, numeric variables, or conditional expressions; they can also be system functions or user-defined functions, which you will learn about later in this tutorial.)  Part of the job of the ON GOTO statements is to determine the value of this numeric expression.

2. The “line-ref” portion of the ON GOTO statement specifies the line numbers that control should be transferred according to the value of the numeric expression.  Usually an ON GOTO statement specifies more than one line-ref; multiple line-refs must be separated with commas.  When the ON GOTO statement has determined the value of the numeric expression, it takes this number and matches it to the order of the items in the line-ref portion of the syntax.

3. The optional “NONE line-ref” portion of the syntax indicates where program execution should go when the value of the num-expr rounds off to be less than one, or greater than the number of line-refs.

Do not be surprised if you have just read the above explanations three or four times and still have no idea of what the ON GOTO statement actually does.  While the concept is rather simple, it can be difficult to grasp on the first explanation. 

  

Let’s consider an example.  The following set of program lines prints a list of the five business days of the week on the screen and asks the operator to enter a number that signifies the current day of the week.  This number is assigned to the numeric variable DAY by the INPUT statement in line 80.

00010 PRINT NEWPAGE 
00020 PRINT “Please enter the number that signifies the current day of the week:” 
00030 PRINT “1 - Monday” 
00040 PRINT “2 - Tuesday” 
00050 PRINT “3 - Wednesday” 
00060 PRINT “4 - Thursday” 
00070 PRINT “5 - Friday” 
00080 INPUT DAY 
00090 ON DAY GOTO 500,1000,1500,2000,2500 
00100 STOP 
00500 PRINT “Today is Monday” 
00900 STOP 
01000 PRINT “Today is Tuesday” 
01400 STOP 
01500 PRINT “Today is Wednesday” 
01900 STOP 
02000 PRINT “Today is Thursday” 
02400 STOP 
02500 PRINT “Today is Friday” 
03000 END 

Now look at the ON GOTO statement in line 90.  This statement looks up the value of DAY and matches it to the order of the line-ref specifications.  If DAY is 1 in other words, program control is transferred to the line specified by the first line-ref 500.  If DAY is 2, control goes to the line specified by the second line-ref.  Likewise, if DAY is 3, 4, or 5, control is transferred to the line specified by the third, fourth or fifth line-ref respectively.

Type the above program lines into Business Rules! and try them out for yourself.  What happens when you type in the values 1.2, 3, 8, 3.5, and 4.6 instead of the requested information?

What you should have discovered is that the ON GOTO statement rounds off the value of the num-expr before matching it to a line-ref.  Entering a value of 1.2 (which is rounded to 1) for instance, causes control to be transferred to the line indicated by the first line-ref.  Entering the value 3.5 (which is rounded to 4) causes control to transfer to the line indicated by the fourth line-ref.

You should have also discovered that entering a value which rounded out to greater than 5 or less than 1 caused the program to stop altogether.  This is because program control simply transfers to the next line (which turned out to be a STOP statement in this case) when the num-expr in an ON GOTO statement doesn’t match up with the position order of any of the line-refs.

If you wish, you can use the “NONE line-ref” portion of the ON GOTO syntax to specify where program control should go when the num-expr doesn’t match up with the line-refs.  To try the use of this parameter out, change line 90 on your screen to read as follows: 00090 ON DAY GOT 500,1000,1500,2000,2500 NONE 10 This change will cause the program to branch back to line 10 and reprint all the instructions whenever an inappropriate value is entered for the variable DAY.

The ON GOSUB statement

The ON GOSUB statement is identical, both in syntax and in operation, to the ON GOTO statement, except for one thing:  ON GOSUB transfers program control to a complete subroutine that must end with a RETURN statement.

Both the ON GOSUB and ON GOTO statements are frequently used to handle the branching that occurs when the operator is asked to choose one item from a menu.  In the following example, a program that figures monthly bills asks the operator which of several bills he or she wishes to figure.  An ON GOSUB statement then transfers execution to the appropriate subroutine, based on the operator’s answer (notice that the line-refs in this statement are line labels rather than line numbers).  When the subroutine is complete, a RETURN statement sends program execution back to the first statement after the ON GOSUB statement (line 140), where the operator is asked whether or not there is another bill to be figured.  As you can see from this example, the “main” part of the program is only a few lines long; most of the program is contained In the various subroutines.  

00010 ! ********************* B I L L S ************************* 
00020 ! ********PURPOSE: To figure monthly utility bills********* 
00030 ! CREATION DATE: 8/24/05             REVISION DATE: 8/24/05 
00040 ! *********Application Development Systems, INC.*********** 
00050 ! ********************************************************* 
00060 PRINT NEWPAGE 
00070 PRINT “Please indicate the number of the bill you would like to figure.” 
00080 PRINT “1 - Electricity” 
00090 PRINT “2 - Natural Gas” 
00100 PRINT “3 - Telephone” 
00110 PRINT “4 - Cable TV” 
00120 INPUT CHOICE 
00130 ON CHOICE GOSUB ELEC,NATGAS,PHONE,CABLE 
00140 PRINT “Do you wish to figure another bill? (y/n)” 
00150 INPUT ANSWER$ 
00160 IF ANSWER$=”Y” OR ANSWER$=”y” THEN GOTO 00070 
00170 STOP 
01000 ELEC: ! Subroutine for electricity bill 
o 
o 
01650 RETURN 
02000 NATGAS: ! Subroutine for natural gas bill 
o 
o 
02580 RETURN 
03000 PHONE: ! Subroutine for telephone bill 
o 
o 
03890 RETURN 
04000 CABLE: ! Subroutine for cable TV bill 
o 
o 
04500 RETURN 
99999 END 

 

Quick Quiz 8.3

1. Study the following ON GOTO statement, and then answer the questions.

00100 ON VAR/10 GOTO 00900, 01100,01500,02000 

a)   What will happen if the value of VAR/10 is 4?
b)   What will happen if the value of VAR is 25?
c)   What will happen if the value of VAR/10 is 16?

2. How many subroutines are referred to with line numbers in the following statement.

00100 ON CHOICE GOSUB 2000,3000,4000 NONE 5000

a)   One.
b)   Two.
c)   Three.
d)   Four.

3. Name one frequent use of the ON GOTO and ON GOSUB statements.

Answers 8.3

8.4 DO Loops

FOR/NEXT loops and GOTO can handle a lot of things you need to do in a program. Sometimes, you’ll want a loop with a little more flexibility. DO loops can do this for you since they require no line labels or numbers to execute. Here’s the syntax:

DO WHILE condition-expression

or

DO UNTIL condition-expression
The DO is always used with the LOOP statement.

The While keyword indicates that the loop should be executed only if the specified conditional expression evaluates to true. If the conditional expression evaluates to false, execution will skip to the first line following the Loop statement. The Until keyword indicates that the loop should be executed only if the specified conditional expression evaluates to false. If the conditional expression evaluates to true, execution will skip to the first line following the Loop statement.

Look at the example below:

00005    LET X=1
00010    DO WHILE X<10
00020       PRINT "Hello Cat"
00030       LET X=X+1
00040    LOOP 

Do loops continue to execute repeatedly until the condition is met. They can also be exited using the EXIT DO statement.

Chapter Exercises

1. Create a FOR/NEXT loop that outputs the following: 10
 7
 4
 1
-2
-5
-8

2. Write a program using a FOR/NEXT loop to print the following items each time through the loop: 1, 1*1, 2**1, 3***1.  The loop should be executed starting at 1 and ending with 16.

You might want to experiment with three types of PRINT statements inside your loop.  First, try unformatted printing with a comma.  Then, run the program again with formatted printing with a FORM statement and run the program a third time.  Which do you prefer and why?

3. Your wealthy cousin Leo (rumored to have connections with Las Zetas) has agreed to loan you $15,000 for that cabin on the lake.  The interest rate is 12% per year.  The loan is to be repaid in small monthly payments for 10 years. Let’s write a program (called a loan amortization program) to figure out how much interest will be paid in dollars.

Use the formula for monthly payment from Chapter 4.  For each of the 120 monthly payments, the money goes for two things: paying interest and reducing the principal.  Your printout should have four columns of data:

Month Interest Principal Balance
Number Paid Repayment Remaining
______ ________ _________ _________
512.34 36.66 14,963.34
2 510.10 39.90 14,923.44
    O     O     O
120    5.12   494.88  0.00
______  ________  _________  _________
TOTAL     ????????        15,000.00          0.00

  As the example above shows, you should also compute totals for the two middle columns.

After using the monthly payment formula once at the start of your program, the formulas that you will need inside the loop are:

LET INT = RATE/12 * BALANCE !      Interest paid 
LET REPAY = MONTHLY -  INT !       Principal repayment 
LET BALANCE = BALANCE - REPAY !    Balance remaining 

At the start of your program you will also need to add these statements:

LET RATE = .15 !                  Interest rate 15% 
LET BALANCE = 1500 !         Initial amount of loan 
LET YEARS = 10 !                10 year loan 

How many dollars will cousin Leo make in interest on this little favor?

Solution

NEXT:Organizing Folders and Programs

Back to Index