Chapter 5: Difference between revisions

From BR Wiki
Jump to navigation Jump to search
(Moved answer from chapter to make it not immediately visible to the student)
 
(23 intermediate revisions by 2 users not shown)
Line 15: Line 15:
===The GOTO Statement ===
===The GOTO Statement ===
   
   
Using symbols, we can visualize the progress of the MILEAGE program that you wrote in the last chapter.
Using symbols, we can visualize the progress of the MILEAGE program that you wrote in [[Chapter 3]], where you also learned about the CONV error condition and saw how Zippy the Cursor jumped across several program lines to reach the error-handling routine for a conversion error.  A program jump such as Zippy performed can be a very useful programming tool. It is usually referred to as a branching statement.   
 
In [[Chapter 3]], you learned about the CONV error condition and saw how Zippy the Cursor jumped across several program lines to reach the error-handling routine for a conversion error.  A program jump such as Zippy performed can be a very useful programming tool. It is usually referred to as a branching statement.   


A '''branching statement''' is a line of code that causes program control to jump to another line of code.  
A '''branching statement''' is a line of code that causes program control to jump to another line of code.  
Line 31: Line 29:
[[image:5.1.jpg|500px]]
[[image:5.1.jpg|500px]]
   
   
Line 100 tells Business Rules! to jump to line 450.  Unless a later (or earlier) statement in the program branches control to the lines between 100 and 450, any lines between 100 and 450 will never be executed. Note that line 450 must be present in your program before you can save it. Trying to use the SAVE or REPLACE command before you define line 450 will result in ERROR 213 (Line reference not found).
Line 100 tells Business Rules! to jump to line 450.  Unless a later (or earlier) statement in the program branches control to the lines between 100 and 450, any lines between 100 and 450 will never be executed. Note that line 450 must be present in your program before you can save it. Trying to use the SAVE or REPLACE command before you define line 450 will result in ERROR 213 (Line reference not found).
   
   
Line 52: Line 51:
   
   
==== Quick Quiz 5.1 ====
==== Quick Quiz 5.1 ====
 
 
1. A branching statement: <br>
1. A branching statement: <br>
a) Causes Business Rules! to enter an endless loop. <br>
a) Causes Business Rules! to enter an endless loop. <br>
b) Causes program control to jump from one line to another. <br>
b) Causes program control to jump from one line to another. <br>
c) Can only be used to transfer control forward through a program. <br>
c) Can only be used to transfer control forward through a program. <br>
 
 
2. The GOTO statement: <br>
2. The GOTO statement: <br>
a) Is an example of a conditional branching statement. <br>
a) Is an example of a conditional branching statement. <br>
b) Always creates a loop. <br>
b) Always creates a loop. <br>
c) Allows you to transfer control to any line in the program. <br>
c) Allows you to transfer control to any line in the program. <br>
 
 
3. Which of the following statements best describes the GOTO statement? <br>
3. Which of the following statements best describes the GOTO statement? <br>
a) GOTO is an unconditional branching statement; it transfers program control every time it is executed. <br>
a) GOTO is an unconditional branching statement; it transfers program control every time it is executed. <br>
b) GOTO is a conditional branching statement; it transfers program control only when certain conditions are met. <br>
b) GOTO is a conditional branching statement; it transfers program control only when certain conditions are met. <br>
c) GOTO is an unconditional looping statement; it creates a loop every time it is executed. <br>
c) GOTO is an unconditional looping statement; it creates a loop every time it is executed. <br>
 
 
4. In the above example, under what conditions might the program execute code between lines 100 and 450? <br>
4. In the above example, under what conditions might the program execute code between lines 100 and 450? <br>
a) When the GOTO statement does not execute. <br>
a) When the GOTO statement does not execute. <br>
b) When a statement between lines 100 and 450 branches control back to line 100. <br>
b) When a statement between lines 100 and 450 branches control back to line 100. <br>
c) When a statement before line 100 or at line 450 or later transfers control to code between lines 100 and 450.  
c) When a statement before line 100 or at line 450 or later transfers control to code between lines 100 and 450.  
 
Answers:


1-b; 2-c; 3-a; 4-c
[[Answers 5.1]]
   
 
 
 
==== Challenge Question ====
==== Challenge Question ====


LIST the PROGX program and look at line 40 again.  How can you change this line so that the number 20 is not mentioned, but so that the program still branches back to line 20?  
LIST the PROGX program and look at line 40 again.  How can you change this line so that the number 20 is not mentioned, but so that the program still branches back to line 20?  
 
 
Answer:
[[Solutions#CHAPTER 5|Solution]]
Add a line label to line 20 and refer to it as the line-ref in the GOTO statement


===5.2 The IF Statement===
===5.2 The IF Statement===
Line 190: Line 188:
Run this program several times and use a different number for age every time. You will see that either lines 40 and 50 execute, or line 70 and 80 execute, depending on what number you enter.
Run this program several times and use a different number for age every time. You will see that either lines 40 and 50 execute, or line 70 and 80 execute, depending on what number you enter.


==== Quick Quiz 5.2 ==== 
==== Quick Quiz 5.2 ====


1. An IF statement is: <br>
1. An IF statement is: <br>
Line 196: Line 194:
b) A statement which evaluates a condition, such as comparing two values, then executes instructions based on the results of the evaluation. <br>
b) A statement which evaluates a condition, such as comparing two values, then executes instructions based on the results of the evaluation. <br>
c) A statements which cannot enter an endless loop.  
c) A statements which cannot enter an endless loop.  
 
 
2. When an IF condition is true: <br>
2. When an IF condition is true: <br>
a) Business Rules! executes the instructions in both the THEN and the ELSE clauses. <br>
a) Business Rules! executes the instructions in both the THEN and the ELSE clauses. <br>
b) Business Rules! skips the THEN clause and executes the ELSE clause instructions. <br>
b) Business Rules! skips the THEN clause and executes the ELSE clause instructions. <br>
c) Business Rules! executes the THEN clause and ignores the ELSE clause instructions. <br>
c) Business Rules! executes the THEN clause and ignores the ELSE clause instructions. <br>
 
 
Answers: <br>
[[Answers 5.2]]
 1-a; 2-c.<br>


====Extra Practice:====
====Extra Practice:====
Remember the AREA program that you started in chapter 3? Suppose the user wanted to calculate the area of more than just a circle. Add two more shapes (square, triangle, or rectangle) to the program, and using the IF, THEN, and ELSE clauses, calculate their areas accordingly. Keep in mind that for each shape, the user will need to enter different inputs (i.e. length or height).
Remember the AREA program that you started in chapter 3? Suppose the user wanted to calculate the area of more than just a circle. Add two more shapes (square, triangle, or rectangle) to the program, and using the IF, THEN, and ELSE clauses, calculate their areas accordingly. Keep in mind that for each shape, the user will need to enter different inputs (i.e. length or height).
[[Solutions#CHAPTER 5|Solution]]


===5.3 Relational Expressions===
===5.3 Relational Expressions===
Line 409: Line 408:
  if “A” then print “A is true”
  if “A” then print “A is true”


====Quick Quiz 5.3==== 
====Quick Quiz 5.3====
 
1. Identify the valid relational expressions:<br>  
1. Identify the valid relational expressions:<br>  
a)         P <= X100 <br>
a)         P <= X100 <br>
Line 420: Line 418:
g)         PAR$ : golf <br>
g)         PAR$ : golf <br>
h)         MIX * 3.8 <br>
h)         MIX * 3.8 <br>
 
 
2. True or False: Relational symbols may be used only with numeric variables or expressions.  
2. True or False: Relational symbols may be used only with numeric variables or expressions.  
 
 
3. Which statements can be used as instructions within the THEN and ELSE clauses in the IF statement? <br>
3. Which statements can be used as instructions within the THEN and ELSE clauses in the IF statement? <br>
a) GOTO and IF. <br>
a) GOTO and IF. <br>
b) PRINT and IF,THEN.<br>  
b) PRINT and IF,THEN.<br>  
c) Most valid Business Rules! statements. <br>
c) Most valid Business Rules! statements. <br>
 
 
4. When Business Rules! evaluates string values: <br>
4. When Business Rules! evaluates string values: <br>
a) It changes lowercase letters into uppercase letters. <br>
a) It changes lowercase letters into uppercase letters. <br>
b) It always returns a false comparison and follows the instructions in the ELSE clause. <br>
b) It always returns a false comparison and follows the instructions in the ELSE clause. <br>
c) It uses exactly what is entered within “delimiters” as its source of comparison. <br>
c) It uses exactly what is entered within “delimiters” as its source of comparison. <br>
 
 
5. What happens when the IF comparison in an IF statement is evaluated as false and there is no ELSE clause?  
5. What happens when the IF comparison in an IF statement is evaluated as false and there is no ELSE clause? <br>
a) An error occurs.  
a) An error occurs. <br>
b) Business Rules! transfers to an error-handling routine.  
b) Business Rules! transfers to an error-handling routine. <br>
c) Program control is passed to the next statement.  
c) Program control is passed to the next statement. <br>
 
 
Answers:
[[Answers 5.3]]
 1-a, b, c, e, and f; 2-False; 3-c; 4-c; 5-c.


===5.4 The AND and OR Keywords===
===5.4 The AND and OR Keywords===
Line 451: Line 448:


Complete the following truth table with either ‘true’ or ‘false’to determine the outcome of an if statement that involves two conditions separated by the and keyword:
Complete the following truth table with either ‘true’ or ‘false’to determine the outcome of an if statement that involves two conditions separated by the and keyword:


{|
{|
Line 541: Line 537:
  IF LWRC$(QUEST$)=”yes” THEN GOTO 100 ELSE GOTO 300
  IF LWRC$(QUEST$)=”yes” THEN GOTO 100 ELSE GOTO 300


==== Quick Quiz 5.4 ====
[[Solutions#CHAPTER 5|Solution]]


====Quick Quiz 5.4====
1. The AND and OR keywords can be used: <br>
1. The AND and OR keywords can be used: <br>
a) To provide additional instructions in the ELSE clause of the IF statement. <br>
a) To provide additional instructions in the ELSE clause of the IF statement. <br>
b) To specify more than one conditional expression in an IF statement.<br>
b) To specify more than one conditional expression in an IF statement.<br>
c)  To require that at least two conditional expressions be true before BR follows the THEN instructions. <br>
c)  To require that at least two conditional expressions be true before BR follows the THEN instructions. <br>
 
 
2. The AND keyword: <br>
2. The AND keyword: <br>
a) May be used only once in each IF clause. <br>
a) May be used only once in each IF clause. <br>
b) Requires two conditions to be met before an expression is evaluated as true. <br>
b) Requires two conditions to be met before an expression is evaluated as true. <br>
c) Is required in all IF statements. <br>
c) Is required in all IF statements. <br>
 
 
3. The OR option: <br>
3. The OR option: <br>
a) Cannot be specified when the IF statement already uses the AND option. <br>
a) Cannot be specified when the IF statement already uses the AND option. <br>
b) Must be specified within parentheses. <br>
b) Must be specified within parentheses. <br>
c) Tells Business Rules! to execute the THEN instructions when at least one of a set of conditional instructions is true. <br>
c) Tells Business Rules! to execute the THEN instructions when at least one of a set of conditional instructions is true. <br>
 
 
Answers: <br>
[[Answers 5.4]]<br>
1-b; 2-b; 3-c.
 
 
 


Line 593: Line 590:
#the GOSUB statement itself must always include a line-ref (either a line number or a line label) that tells Business Rules! where to find the first line of the subroutine, and  
#the GOSUB statement itself must always include a line-ref (either a line number or a line label) that tells Business Rules! where to find the first line of the subroutine, and  
#the specified subroutine must always end with a RETURN statement.  Business Rules! will send a syntax error when you try to SAVE or RUN a program that has a GOSUB statement but no corresponding RETURN statement.  
#the specified subroutine must always end with a RETURN statement.  Business Rules! will send a syntax error when you try to SAVE or RUN a program that has a GOSUB statement but no corresponding RETURN statement.  
 
 
The following GOSUB statement tells BR to transfer program control to the subroutine which starts with the line label SALESTAX.  BR keeps track of the position of this GOSUB (sometimes referred to as the calling GOSUB because it calls for the services of the subroutine) until it encounters a RETURN statement.  It then returns program control to the first statement after the GOSUB in the main part of the program.  
The following GOSUB statement tells BR to transfer program control to the subroutine which starts with the line label SALESTAX.  BR keeps track of the position of this GOSUB (sometimes referred to as the calling GOSUB because it calls for the services of the subroutine) until it encounters a RETURN statement.  It then returns program control to the first statement after the GOSUB in the main part of the program.  
 
 
  250 GOSUB SALESTAX  
  250 GOSUB SALESTAX  
 
 
SALESTAX, as its name implies, could be a subroutine which calculates state sales tax (of 6%, in the following case), on the purchase price of a retail sale.  When such a calculation is used several times in a program, the programmer saves time and space by branching control to a single subroutine instead of rewriting the calculation each time it is needed.  Note that the following example of this subroutine begins with the line label which was specified in line 250 (above), and ends with a RETURN statement.  
SALESTAX, as its name implies, could be a subroutine which calculates state sales tax (of 6%, in the following case), on the purchase price of a retail sale.  When such a calculation is used several times in a program, the programmer saves time and space by branching control to a single subroutine instead of rewriting the calculation each time it is needed.  Note that the following example of this subroutine begins with the line label which was specified in line 250 (above), and ends with a RETURN statement.  
 
 
  10000 SALESTAX: ! A subroutine to figure sales tax of 6% on retail sales  
  10000 SALESTAX: ! A subroutine to figure sales tax of 6% on retail sales  
  10010 PRINT “Enter purchase price”  
  10010 PRINT “Enter purchase price”  
Line 605: Line 602:
  10030 LET TAX=PRICE * 6 / 100      ! 6%  
  10030 LET TAX=PRICE * 6 / 100      ! 6%  
  10040 RETURN  
  10040 RETURN  
 
 
====Quick Quiz 5.5 ====
====Quick Quiz 5.5 ====
 
 
1. GOSUB is: <br>
1. GOSUB is: <br>
a) A conditional branching statement much like GOTO. <br>
a) A conditional branching statement much like GOTO. <br>
b) Only used with IF statements. <br>
b) Only used with IF statements. <br>
c) A branching statement which sends program control to a subroutine. <br>
c) A branching statement which sends program control to a subroutine. <br>
 
 
2. A subroutine: <br>
2. A subroutine: <br>
a) Has a maximum length of 25,000 program lines. <br>
a) Has a maximum length of 25,000 program lines. <br>
b) Is a set of program lines which can be executed more than once in a program. <br>
b) Is a set of program lines which can be executed more than once in a program. <br>
c) Always begins with a RETURN statement <br>
c) Always begins with a RETURN statement <br>
 
 
3. The RETURN statement: <br>
3. The RETURN statement: <br>
a) Is required at the end of a subroutine. <br>
a) Is required at the end of a subroutine. <br>
b) Sends program control back to the beginning of a program. <br>
b) Sends program control back to the beginning of a program. <br>
c) Works in conjunction with the GOTO statement. <br>
c) Works in conjunction with the GOTO statement. <br>
 
 
Answers: <br>
[[Answers 5.5]] <br>
1-c; 2-b; 3-a. <br>
 
 
 


Line 630: Line 627:
   
   
You learned in this section that Business Rules! resumes execution with the first statement after calling GOSUB when it encounters a RETURN statement.  What would happen if Business Rules! resumed execution with the GOSUB statement instead?
You learned in this section that Business Rules! resumes execution with the first statement after calling GOSUB when it encounters a RETURN statement.  What would happen if Business Rules! resumed execution with the GOSUB statement instead?
[[Solutions#CHAPTER 5|Solution]]


===5.6 What happens when you use GOSUB inside a subroutine? ===
===5.6 What happens when you use GOSUB inside a subroutine? ===
A subroutine is exactly like any other part of your program except for two things: it should only be executed when a GOSUB statement sends control to it, and it must end with a RETURN statement.  Any statement (including GOSUB) that can be used in the main part of a program can also be used in a subroutine.  You can then design programs with subroutines that call subroutines.  Subroutines that are referenced from within other subroutines are referred to as nested.  
A subroutine is exactly like any other part of your program except for two things: it should only be executed when a GOSUB statement sends control to it, and it must end with a RETURN statement.  Any statement (including GOSUB) that can be used in the main part of a program can also be used in a subroutine.  You can then design programs with subroutines that call subroutines.  Subroutines that are referenced from within other subroutines are referred to as nested.  
 
 
Our old friend Zippy the Cursor may be able to help you envision the flow of a program when it uses a double (or triple or quadruple or even greater) sequence of subroutines.  
Our old friend Zippy the Cursor may be able to help you envision the flow of a program when it uses a double (or triple or quadruple or even greater) sequence of subroutines.  
 
 
One thing that we neglected to tell you earlier is that Zippy keeps a big piece of chalk in his back pocket.  Whenever he encounters a GOSUB statement, he runs to a room called the FLOWSTACK and marks its line number on a chalkboard.  He then dashes on to the specified subroutine and begins executing that.  If he then encounters another GOSUB statement, he again stops in at the FLOWSTACK to add its line number to the chalkboard.  He then goes on to execute the specified subroutine.  Zippy will go through this process until all the GOSUB line numbers are written on the chalkboard.  
One thing that we neglected to tell you earlier is that Zippy keeps a big piece of chalk in his back pocket.  Whenever he encounters a GOSUB statement, he runs to a room called the FLOWSTACK and marks its line number on a chalkboard.  He then dashes on to the specified subroutine and begins executing that.  If he then encounters another GOSUB statement, he again stops in at the FLOWSTACK to add its line number to the chalkboard.  He then goes on to execute the specified subroutine.  Zippy will go through this process until all the GOSUB line numbers are written on the chalkboard.  
 
 
When Zippy finally gets all the way through a subroutine and reaches a RETURN statement, he goes back to the FLOWSTACK room, finds the last number on the chalkboard and erases it.  He then locates this same line number in the program, recognizes the GOSUB statement it contains, and starts executing again with the next statement after the GOSUB.  He goes through this same procedure every time he encounters a RETURN statement.  
When Zippy finally gets all the way through a subroutine and reaches a RETURN statement, he goes back to the FLOWSTACK room, finds the last number on the chalkboard and erases it.  He then locates this same line number in the program, recognizes the GOSUB statement it contains, and starts executing again with the next statement after the GOSUB.  He goes through this same procedure every time he encounters a RETURN statement.  
 
 
The amount of line numbers written at any one time on the chalkboard in the FLOWSTACK room is the number of active GOSUBs that a program contains.  As soon as a line number is erased, that GOSUB is no longer active.  As was already mentioned, the maximum number of active GOSUBs that a program can contain is 50.
The amount of line numbers written at any one time on the chalkboard in the FLOWSTACK room is the number of active GOSUBs that a program contains.  As soon as a line number is erased, that GOSUB is no longer active.  As was already mentioned, the maximum number of active GOSUBs that a program can contain is 50.


Line 668: Line 667:
  200    return  
  200    return  


==== Quick Quiz 5.6 ==== 
==== Quick Quiz 5.6 ====


1. How does a subroutine differ from other parts of a program? <br>
1. How does a subroutine differ from other parts of a program? <br>
Line 675: Line 674:
c) It always ends with a RETURN statement. <br>
c) It always ends with a RETURN statement. <br>
d) Both b and c. <br>
d) Both b and c. <br>
 
 
2. Where does Business Rules! keep track of the number of active GOSUBs in a program? <br>
2. Where does Business Rules! keep track of the number of active GOSUBs in a program? <br>
a) In the error-handling routine. <br>
a) In the error-handling routine. <br>
b) In the directory.<br>  
b) In the directory.<br>  
c) In the FLOWSTACK.<br>  
c) In the FLOWSTACK.<br>  
 
 
3. What is the maximum number of GOSUBs which may be active at any one time in a program? <br>
3. What is the maximum number of GOSUBs which may be active at any one time in a program? <br>
a) 50 <br>
a) 50 <br>
b) 9 <br>
b) 9 <br>
c) Unlimited. <br>
c) Unlimited. <br>
 
 
4. What is the maximum number of GOSUBs which may be used in a program? <br>
4. What is the maximum number of GOSUBs which may be used in a program? <br>
a) 9 <br>
a) 9 <br>
b) 50 <br>
b) 50 <br>
c) Unlimited <br>
c) Unlimited <br>
 
Answers: <br>
1-d; 2-c; 3-a; 4-c.
 
===5.7 Writing Menu === 


A program menu operates something like the kind of menu that you see in a restaurant.  It appears on the screen and gives the program user a list of options or functions that the program will perform.  When the user chooses one of the options, that program immediately branches to the routine that performs that function.  Software users often like menu-driven programs (programs which always give the user a list of the available choices) because they are easy to use.
[[Answers 5.6]] <br>
 
 
Menus are a very convenient and simple programming tool; you can design them with PRINT, IF and GOTO statements.  The entire role of some programs in life is to be a menu for the selection of other programs, while some programs include menus and perform other work.  
 
 
 
===5.7 Writing a Menu ===
 
A program menu appears on the screen and gives the user a list of options or functions that the program will perform. When the user chooses one of the options, that program immediately branches to the routine that performs that function.
 
Menus can be designed with PRINT, IF and GOTO statements.  The entire role of some programs in life is to be a menu for the selection of other programs, while some programs include menus and perform other work.  
 
Imagine that you are asked to write a program for a company which would like to keep better records on its fleet of vehicles.  Vehicle use for this company is divided into four service categories: sales, grounds use, delivery and executive use.  The program must be designed so that the figures for each group are recorded separately, but also so that the user can choose to enter information for the categories in any order.  
Imagine that you are asked to write a program for a company which would like to keep better records on its fleet of vehicles.  Vehicle use for this company is divided into four service categories: sales, grounds use, delivery and executive use.  The program must be designed so that the figures for each group are recorded separately, but also so that the user can choose to enter information for the categories in any order.  
 
 
One way to organize a program such as this is to break it into four major chunks, each of which returns to the main flow of the program when finished.  The following example uses GOTO as the THEN instructions in the IF statement.  
One way to organize a program such as this is to break it into four major chunks, each of which returns to the main flow of the program when finished.  The following example uses GOTO as the THEN instructions in the IF statement.  
 
 
  10 ! **********************COMPANY VEHICLES**********************  
  10 ! **********************COMPANY VEHICLES**********************  
  20 PRINT “Type the number of the service category you wish to enter information about, or type Q to quit:”  
  20 PRINT “Type the number of the service category you wish to enter information about, or type Q to quit:”  
Line 749: Line 749:
  15920 ! *********************************************************  
  15920 ! *********************************************************  
  99999 END: END  
  99999 END: END  
 
 
Can you make a diagram and chart the general flow of the above program?  Subroutines are usually diagrammed to the right of the main program.  
Can you make a diagram and chart the general flow of the above program?  Subroutines are usually diagrammed to the right of the main program.  
 
 
====Quick Quiz 5.7====  
====Quick Quiz 5.7====


1. A program menu: <br>
1. A program menu: <br>
Line 758: Line 758:
b) Operates much like the table of contents in a book. <br>
b) Operates much like the table of contents in a book. <br>
c) Is the list of the files in a directory. <br>
c) Is the list of the files in a directory. <br>
 
 
Answer: <br>
Answer: <br>
1.b
[[Answer 5.7b|Answer]] <br>


====Challenge Question ====
====Challenge Question ====
 
 
GOSUB statements can be used to achieve the same results as the GOTOs in the above COMPANY VEHICLES program.   
GOSUB statements can be used to achieve the same results as the GOTOs in the above COMPANY VEHICLES program.   
What changes would you have to make to the program for this to happen?  Which method is the more efficient way to code the menu into the program?  
What changes would you have to make to the program for this to happen?  Which method is the more efficient way to code the menu into the program?  
 
 
Answer: <br>
[[Answer 5.7b|Answer]] <br>
If there was a GOSUB, instead of a return statement after a GOSUB had just been executed the second GOSUB would send the program execution to the subroutine or line specified in the second GOSUB statement instead of returning to where the program left off.
 
   
   
====Chapter 5 Exercises ====
====Chapter 5 Exercises ====
 
 
1. Write a program to calculate distance in meters.  The metric equivalent is that one meter is 39.37 inches.  The user will input the distance in feet and inches (hint: use two separate INPUT statements for feet and inches).  Allow the user to execute the program several times.  The program should end when the user enters a negative number for feet (don’t forget to tell the user this arbitrary rule for how to end the program).  
1. Write a program to calculate distance in meters.  The metric equivalent is that one meter is 39.37 inches.  The user will input the distance in feet and inches (hint: use two separate INPUT statements for feet and inches).  Allow the user to execute the program several times.  The program should end when the user enters a negative number for feet (don’t forget to tell the user this arbitrary rule for how to end the program).  
 
 
2. Write a program to compare two loans.  Use a subroutine to calculate the amount of the monthly payment on a loan.  You can modify the program that you wrote for Chapter 4, Assignment 2.  For each loan, your program should accept a dollar amount, an interest rate, and a number of years.  Your subroutine should do all calculations for the loan.  A possible outline of your program is:  
2. Write a program to compare two loans.  Use a subroutine to calculate the amount of the monthly payment on a loan.  You can modify the program that you wrote for Chapter 4, Assignment 2.  For each loan, your program should accept a dollar amount, an interest rate, and a number of years.  Your subroutine should do all calculations for the loan.  A possible outline of your program is:  
 
 
a) Input numbers for first loan. <br>
a) Input numbers for first loan. <br>
b) Execute subroutine. <br>
b) Execute subroutine. <br>
Line 783: Line 783:
f) Print second monthly payment. <br>
f) Print second monthly payment. <br>
g) Subtract two monthly payments. <br>
g) Subtract two monthly payments. <br>
 
 
With this program, you can answer questions like “How much will I save if interest rates drop one-half percent lower?”, or “How much will I save on monthly payments if I pay an extra $1000 to reduce the loan amount on my new house?”  
With this program, you can answer questions like “How much will I save if interest rates drop one-half percent lower?”, or “How much will I save on monthly payments if I pay an extra $1000 to reduce the loan amount on my new house?”  
 
 
3. Add “range checks” to the program that you wrote for Assignment 2.  Immediately after each of the numbers are entered, check that the values fall within the following boundaries or ranges:  
3. Add “range checks” to the program that you wrote for Assignment 2.  Immediately after each of the numbers are entered, check that the values fall within the following boundaries or ranges:  
 
 
a) Amount of Loan -- between $0 and $1,000,000.<br>
a) Amount of Loan -- between $0 and $1,000,000.<br>
b) Interest Rate -- between 1 and 30 percent. <br>
b) Interest Rate -- between 1 and 30 percent. <br>
c) Number of Years -- between 1 and 35 years. <br>
c) Number of Years -- between 1 and 35 years. <br>
 
 
If the user enters any numbers outside these ranges, the numbers should be rejected and a message should be printed about what values are acceptable (hint: use IF statements with AND or OR).
If the user enters any numbers outside these ranges, the numbers should be rejected and a message should be printed about what values are acceptable (hint: use IF statements with AND or OR).
 
 
4. Modify the program you wrote for assignment 2 (or 3) so that the input section for the second loan will use corresponding values from the first loan if zero is entered.  
4. Modify the program you wrote for assignment 2 (or 3) so that the input section for the second loan will use corresponding values from the first loan if zero is entered.  
 
 
For instance, if the first loan is for $100,000, at 8 percent for 10 years, the user could compare the same loan at 9 percent by entering for the second loan 0, 9, 0 for the loan amount, rate and years, respectively.  The program would treat this second loan as if the user had entered $100,000, 9 percent and 10 years.
For instance, if the first loan is for $100,000, at 8 percent for 10 years, the user could compare the same loan at 9 percent by entering for the second loan 0, 9, 0 for the loan amount, rate and years, respectively.  The program would treat this second loan as if the user had entered $100,000, 9 percent and 10 years.


NEXT: [[Chapter 6]]
[[Solutions#CHAPTER 5|Solutions]]
 
 
NEXT: [[Chapter 6|Debugging Features]]


[[BR Tutorial|Back to Index]]
[[BR Tutorial|Back to Index]]
<noinclude>
[[Category:Tutorial 1]]
</noinclude>

Latest revision as of 16:22, 21 December 2019

5.1 Branching Statements

This chapter teaches you all the ins and outs of branching statements, which are just what the name implies - statements which cause program flow to branch in different directions. When you have completed this chapter you should be able to:  

  1. Use a flow chart to diagram the progress of your programs.
  2. Explain the difference between a conditional expression and an unconditional expression.
  3. Use the GOTO statement to transfer program control to a specified line.
  4. Use the IF, THEN, ELSE statement to transfer control on the basis of a conditional expression.
  5. Identify the meanings of 10 relational symbols.
  6. Describe a subroutine.
  7. Use the GOSUB statement to transfer program control to a specified subroutine.

 

 

The GOTO Statement

  Using symbols, we can visualize the progress of the MILEAGE program that you wrote in Chapter 3, where you also learned about the CONV error condition and saw how Zippy the Cursor jumped across several program lines to reach the error-handling routine for a conversion error.  A program jump such as Zippy performed can be a very useful programming tool. It is usually referred to as a branching statement. 

A branching statement is a line of code that causes program control to jump to another line of code.   There are several different types of branching statements. Some are conditional, meaning that the program controls branches only when a specific condition is met.

Others are unconditional, meaning that regardless of any conditions, the program branches when that statement is used, i.e. there is no decision to be made.

A GOTO statement is an unconditional branching statement, which transfers program control from the currently executing line of code to any line in the program.   The GOTO statement is always specified with a line-ref so that Business Rules! knows which line to jump to. The following two lines show the typical syntax and an example of a GOTO statement:

 

Line 100 tells Business Rules! to jump to line 450.  Unless a later (or earlier) statement in the program branches control to the lines between 100 and 450, any lines between 100 and 450 will never be executed. Note that line 450 must be present in your program before you can save it. Trying to use the SAVE or REPLACE command before you define line 450 will result in ERROR 213 (Line reference not found).   To see more about how the GOTO statement operates, type in the following program, which we’ll call PROGX.  

10 LET X=1 
20 SEEVALUE: PRINT X          !Reminder -- SEEVALUE: is a line label
30 LET X=X+1 
40 GOTO 20 
50 END 

  When you have PROGX typed in, go ahead and RUN it.  It should print a continuous ribbon of numbers (each being one greater than the last) which scrolls up the left side of your screen.    It will continue to do this indefinitely until you manually end the program by putting it into ATTN mode (with Ctrl + A) and typing either STOP or END.   The reason that PROGX continues without stopping is that the GOTO statement in line 40 causes it to enter an endless loop by sending program control backwards to line 20.  After the program re-executes lines 20 and 30, it encounters the GOTO statement in line 40 again and the same process is repeated over and over.  The following flow chart illustrates this loop:

  As you can see, there is no arrow pointing to 50, since the program never gets to line 50. That is because our program logic is flawed and needs to be changed to allow for some stopping point in its execution.  

Quick Quiz 5.1

1. A branching statement:
a) Causes Business Rules! to enter an endless loop.
b) Causes program control to jump from one line to another.
c) Can only be used to transfer control forward through a program.

2. The GOTO statement:
a) Is an example of a conditional branching statement.
b) Always creates a loop.
c) Allows you to transfer control to any line in the program.

3. Which of the following statements best describes the GOTO statement?
a) GOTO is an unconditional branching statement; it transfers program control every time it is executed.
b) GOTO is a conditional branching statement; it transfers program control only when certain conditions are met.
c) GOTO is an unconditional looping statement; it creates a loop every time it is executed.

4. In the above example, under what conditions might the program execute code between lines 100 and 450?
a) When the GOTO statement does not execute.
b) When a statement between lines 100 and 450 branches control back to line 100.
c) When a statement before line 100 or at line 450 or later transfers control to code between lines 100 and 450.

Answers 5.1

 

Challenge Question

LIST the PROGX program and look at line 40 again.  How can you change this line so that the number 20 is not mentioned, but so that the program still branches back to line 20?

Solution

5.2 The IF Statement

Imagine that you are writing a program that shows customers prices for different items. Your item list is as follows:

  1. Video game
  2. DVD
  3. CD
  4. X-Box

How will you display the appropriate information to the user? One possible solution is to use an IF statement. Look at the this program for an example of how it works:

010 print “What item are you purchasing?”
020 print “1 - Video game”
030 print “2 - DVD”
040 print “3 - CD”
050 print “4 - X-Box”
060 input choice
070 if choice = 1 then
080    print “Video games cost $17.99 each”
090 else if choice = 2 then
100    print “DVDs cost $14.00 each”
110 else if choice = 3 then
120    print “CDs cost $12.99 each”
130 else if choice = 4 then
140    print “X-Box costs $199.99”
150 else
160    print “Item not recognised”
170 end if

Now let us define the IF statement and its syntax: 

An IF statement is a conditional branching statement with one or more possible branches. The IF statement:

  1. executes the first branch if the first condition is true,
  2. executes the second branch if the second condition is true, and so on until you run out of conditions, and then
  3. executes the ELSE branch if none of the conditions are true.

Syntax

In this sample, all the conditions and branches except the first one are optional.

010 IF condition1 THEN 
020       branch1 
030 ELSE IF condition2 THEN         
040       branch2 
050 ELSE IF condition3 THEN 
060       branch3 
….
150 ELSE IF last_condition THEN 
160       branch_y 
170 ELSE 
180       branch_z
190 END IF

The dots …. are not part of the syntax. They are there to show that you can put any number of ELSE IF conditions and branches into a an IF statement.

In an IF statement, only one of all the branches executes, never more than that.

Notice, that each clause and branch are on separate lines. This is done to make a long IF statement readable. However, you can also put all the clauses of an IF statement on the same line of code. When you put the entire statement on one line of code, the END IF clause should not be added. The syntax then becomes:

10 IF condition1 THEN branch1 ELSE IF condition2 THEN branch2 ELSE IF condition3 THEN branch3 …. ELSE IF last_condition THEN branch_y ELSE branch_z

Note that the ELSE IF and ELSE clauses of the IF statement are optional. If the ELSE IF and ELSE clause is absent, the syntax of the IF statement becomes:

IF condition THEN branch

The IF clause tells BR to evaluate the condition. IF X=10 is an example of this clause. When Business Rules! sees this clause, it compares the values of X and 10.  When the values are equal, the condition is said to be true.  When the values are not equal, the condition is said to be false.    THEN clause tells BR what to do only when the IF condition is true. The following statement tells Business Rules! to evaluate the relationship between X and 10:  

10 IF X=10 THEN PRINT “X equals 10” 

  If (and only if) X and 10 are equal, then BR will print the message “X equals 10“ on the screen.  Almost every BR statement (including GOTO) can be used in the THEN clause, with some exceptions, such as DIM statements.   The ELSE clause tells Business Rules! what to do when the IF condition is false. The following statement tells Business Rules! to print “X does not equal 10” if X is not equal to 10:  

10 IF X=10 THEN PRINT “X equals 10” ELSE PRINT “X does not equal 10”

  BR statements which work with the THEN clause also work with ELSE clause.

In the PROGX program from the last lesson, let’s replace the GOTO statement in line 40 with the following IF statement:

40 IF X=10 THEN PRINT “X equals 10” ELSE GOTO 20 

The new PROGX program should then look as follows:  

10 LET X=1 
20 SEEVALUE: PRINT X 
30 LET X=X+1 
40 IF X=10 THEN PRINT “X equals 10” ELSE GOTO 20 
50 END 

If you now RUN this program, Business Rules! will print the numbers 1 through 9 and the statement “X equals 10” onto the screen, and then end the program and give you the READY prompt.  Make a flow chart and see if you can trace the step-by-step action of the program yourself:

Now, what if you need to react to one condition with more than one line of code? Here is how you can do that:

10 print “Let’s figure out if you can get the kids’ discount. How old are you?”
20 input age
30 if age <= 5 then
40    print “Kids get 50% off :)”
50    let discount = 50
60 else if age > 5 then
70    print “Sorry, you are too old for the kids’ discount :(“
80    let discount = 0
90 end if

Run this program several times and use a different number for age every time. You will see that either lines 40 and 50 execute, or line 70 and 80 execute, depending on what number you enter.

Quick Quiz 5.2

1. An IF statement is:
a) Five separate statements which appear on the same line.
b) A statement which evaluates a condition, such as comparing two values, then executes instructions based on the results of the evaluation.
c) A statements which cannot enter an endless loop.

2. When an IF condition is true:
a) Business Rules! executes the instructions in both the THEN and the ELSE clauses.
b) Business Rules! skips the THEN clause and executes the ELSE clause instructions.
c) Business Rules! executes the THEN clause and ignores the ELSE clause instructions.

Answers 5.2

Extra Practice:

Remember the AREA program that you started in chapter 3? Suppose the user wanted to calculate the area of more than just a circle. Add two more shapes (square, triangle, or rectangle) to the program, and using the IF, THEN, and ELSE clauses, calculate their areas accordingly. Keep in mind that for each shape, the user will need to enter different inputs (i.e. length or height).

Solution

5.3 Relational Expressions

Before we move any further let us define the concepts of true and false as they relate to BR.

In BR, true evaluates to 1, while false evaluates to 0

To verify this, open the BR command prompt and type in

5 > 2

It is true that 5 is more than 2, therefore, the above expression should evaluate as true. When you type the expression in and press ENTER, BR will print

1

The above expression is equivalent to

print 5 > 2

In an IF statement, any single nonzero number evaluates to true, while 0 evaluates to false.

Consider the following example:

10 if 5 then print “5 evaluates to true”
20 if -5 then print “-5 evaluates to true”
30 if 0 then print “0 evaluates to true” ! this line will not print
40 print -5 > 5
50 print -5 < 5 

The result will be:

5 evaluates to true
-5 evaluates to true
0
1

From previous chapters, we are familiar with addition, subtraction, and comparison. But what are they exactly? The answer is operations. Consider the following expression:

A + C

In this expression,

the operation is addition,
the operands are A and C, and
the operator is the + symbol.

Let us now formally define these terms:

An operation is a process that does something to an expression.
An operator is the symbol which triggers an operation.
An operand is an expression or expressions on which an operator performs an operation.

Here is another example:

“This is an example of “ & “the concatenation operation”

In this example:

the operation is concatenation,
the first operand is the string “This is an example of “,
the second operand is “the concatenation operation”, and
the operator is the & symbol, also known as ampersand.

A relational expression is a BR expression that tests some kind of relation between two BR expressions. A relational expression always returns either true or false.

An example of a relational expression is 5 < 4.

  1. We are testing whether 5 is less than 4
  2. Less than is the relational operator
  3. 5 and 4 are the operands
  4. The expression returns false, because 5 is not less than four

Relational expressions use relational operators, which perform some sort of comparison between two operands.

The following relational operators may be used in relational expressions:

< less than
> greater than
= or == equal to
< > or > < not equal to
<= or =< less than or equal to
>= or => greater than or equal to

These symbols may be used to compare both numeric and string values.

Consider the following example:

0 let a = 100
20 if a < 100 then print “a is less than 100“
30 if a <= 100 then print “a is less than or equal to 100“
40 if a = 100 then print “a is equal to 100“
50 if a == 100 then print “a is equal to 100“
50 if a > 100 then print “a is more than 100“
60 if a >= 100 then print “a is more than or equal to 100“
70 if a <> 100 then print “a is not equal to 100“

What results do you think will print on the screen when the above example is run?

Once you write down your answer, compare it to the result below:

a is less than or equal to 100
a is equal to 100
a is equal to 100
a is more than or equal to 100

Now let’s learn a little bit more about operators. There are two types of operators.

A binary operator is an operator which has two operands – one on the left and one on the right.

For example, + is a binary operator, because we always add two numbers, not one.

A unary operator is an operator which has only one operand.

As an example of a unary operator, we now introduce the ~ operator.

The negation operator denoted by the ~ symbol returns the following:

  1. Returns true if its operand is false
  2. Returns false if its operand is true

The negation operator ~ is also known as the not operator.

For example, the statement

if not x > 0 then print “X is not positive”

tests whether x is not positive. This statement is the same as

if ~ x > 0 then print “X is not positive”

We advise that you use not rather than ~, since it is more clear and readable.

The following example demonstrates the concepts covered in this section, as well as those from the previous section:

10 print “This program calculates the average of three test scores.”
20 Score1_prompt: print “Enter the first score”
30 input score1 conv Score1_prompt
40 if not score1 >= 0 then goto Score1_prompt
50 Score2_prompt: print “Enter the second score”
60 input score2 conv Score2_prompt
70 if not score2 >= 0 then goto Score2_prompt
80 Score3_prompt: print “Enter the third score”
90 input score3 conv Score3_prompt
100 if not score3 >= 0 then goto Score3_prompt
110 let average = (score1 + score2 + score3) / 3
120 print “The average is “; average

So, we learned how numbers and numeric comparisons work in IF statements. What about strings and string comparisons?

Strings can be compared directly using the same relational operators as numbers.

Consider the following example:

10 if “a” < “b” then print “a is less than b”
20 if “a” > “b” then print “a is more than b”

Which of the two IF statements will be true? The second one. This makes more sense if you realize that in the alphabet the letter b is after the letter a, therefore “b” is more than “a”.

It is easy to tell how to compare characters of the English alphabet. But what about comparing a comma to a period? What would print if the following program was run:

10 if “.” > “,” then
20    print “period is alphabetically larger than comma” 
30 else
40    print “comma is alphabetically larger than period” 
50 end if

You can find out the answer by looking in the ASCII table. In this table, the comma is character #44, while the period is character #46. This means that the result of the example above is:

period is alphabetically larger than comma

What if you need to compare strings with more than one character, such as “Aaron” and “Aardvark”? The answer is to compare the strings one character at a time. Here is how the comparison is done:

A   A	characters are equal, so move to the next character
a   a	characters are equal, so move to the next character
r    r	characters are equal, so move to the next character
o   d	since o > d in the ASCII table, then “Aaron” is more than “Aardvark”
n   v
    a
    r
    k

Notice, that in the example above we stop the comparison when we find two unequal characters.

BR compares strings in one character at a time. In other words, when comparing string1$ and string2$:

  • the 1st character in string1$ is compared to the 1st character in string2$,
  • the 2nd character in string1$ is compared to the 2nd character in string2$,
  • … the comparison continues until you run out of characters or reach unequal characters.

We learned earlier that a single number or numeric variable may be used as a condition in an IF statement. However, this is not true for strings.

A single string cannot be evaluated to true or false. Neither can it be used as a condition of an IF statement.

As we know already, any single non-zero number in an IF statement evaluates to true. However, with strings this is not the case. The following will result in an error:

if “A” then print “A is true”

Quick Quiz 5.3

1. Identify the valid relational expressions:
a)         P <= X100
b)         G == 100
c)         HEV$ = 42
d)        HEV$ * “Mike”
e)         ANK <> 6
f)          ARC >< 45
g)         PAR$ : golf
h)         MIX * 3.8

2. True or False: Relational symbols may be used only with numeric variables or expressions.

3. Which statements can be used as instructions within the THEN and ELSE clauses in the IF statement?
a) GOTO and IF.
b) PRINT and IF,THEN.
c) Most valid Business Rules! statements.

4. When Business Rules! evaluates string values:
a) It changes lowercase letters into uppercase letters.
b) It always returns a false comparison and follows the instructions in the ELSE clause.
c) It uses exactly what is entered within “delimiters” as its source of comparison.

5. What happens when the IF comparison in an IF statement is evaluated as false and there is no ELSE clause?
a) An error occurs.
b) Business Rules! transfers to an error-handling routine.
c) Program control is passed to the next statement.

Answers 5.3

5.4 The AND and OR Keywords

One final feature of the IF statement is that you can specify more than one conditional expression in the IF clause. The example

IF QUEST$=”yes” AND X=2 THEN GOTO 100 ELSE GOTO 300 

tells Business Rules! to branch to line 100 only when both the conditional expressions QUEST$=”yes” and X=2 are true.  If one or both of the statements are false, the program branches to line 300.

The and keyword allows specifying two (or more) conditions in a single IF statement. The conditions on both sides of the and keyword must be true in order for the IF statement to evaluate to true.

Complete the following truth table with either ‘true’ or ‘false’to determine the outcome of an if statement that involves two conditions separated by the and keyword:

Condition1 Condition2 if Condition1 and Condition2
true true ______
true false ______
false true ______
false false ______

Answer: Only the first line of this table is true.

Next, consider this example:

10 let x=1
20 let y=2
30 let z=3
40 if z < y and y < x then print “x is largest”
50 if x < y and y < z then print “z is largest”

Let us evaluate line 40 by substituting the values for x, y, and z:

40 if 3 < 2 and 2 < 1 then print “x is largest”

Both of the conditions are false, therefore, 3 < 2 and 2 < 1 evaluates to false and the print statement does not execute.

50 if 1 < 2 and 2 < 3 then print “z is largest”

Since both of the conditions are true, 1 < 2 and 2 < 3 evaluates to true, and therefore, the print statement does execute.

Another BR keyword that allows specifying multiple conditions in a single IF statement is the OR keyword.

The or keyword allows specifying two (or more) conditions in a single IF statement. At least one condition on either side of the or keyword must be true in order for the IF statement to evaluate to true.

The following is the truth table that may be used for to determine the outcome of an if statement that involves two conditions separated by the or keyword:

Complete it using ‘true’ or ‘false.’

Condition1 Condition2 if Condition1 or Condition2 true true ______ true false ______ false true ______ false false ______

Answer: In this table, only the last line is false.

The statement:

IF QUEST$=”yes” OR QUEST$=”YES” THEN GOTO 100 ELSE GOTO 300 

tells Business Rules! to transfer to line 100 when either “yes” or “YES” is specified for the QUEST$ variable.

The AND and OR keywords can even be used more than once in the same IF statement.  You could for instance, use the following statement:   10 IF QUEST$=”yes” OR QUEST$=”YES” OR QUEST$=”Yes” OR QUEST$=”Y” OR QUEST$=”y” THEN GOTO 100 ELSE GOTO 300   This statement would tell Business Rules! to branch to line 100 when QUEST$ equals any one of five different values: yes, YES, Yes, Y, or y.

EXTRA PRACTICE

Continuing to work on the AREA prgoram you are building. What improvements can you think of to add now to facilitate the user’s input? Go ahead and write those into it.

When multiple conditions separated by AND and OR keywords are used in a single IF statement
  1. Combining of the conditions is sequential from left to right.
  2. Conditions in parentheses are combined together first before being combined with any other conditions outside of the parentheses.
  3. NOT keyword is processed before AND and OR
  4. AND keyword is processed before OR
  5. OR keyword is processed last

In the two following statements look the same, but the placement of parentheses changes the order of execution and the result:

10 if  2 < 3 or 3<4  and 5<1 then print “true statement” ! this will print
20 if (2 < 3 or 3<4) and 5<1 then print “true statement” ! this won’t print

On a sidenote, Business Rules! has another way to handle user inputs that may be in either upper or lower case, as in the example above, when the user might enter “Yes”, “yes”, or “YES”. Instead of always using the OR keyword, Business Rules! has a simpler way to avoid this problem: the internal function UPRC$ or LWRC$ which will convert any following string into either uppercase or lowercase respectively.

IF UPRC$(QUEST$)=”YES” THEN GOTO 100 ELSE GOTO 300

or

IF LWRC$(QUEST$)=”yes” THEN GOTO 100 ELSE GOTO 300

Solution

Quick Quiz 5.4

1. The AND and OR keywords can be used:
a) To provide additional instructions in the ELSE clause of the IF statement.
b) To specify more than one conditional expression in an IF statement.
c)  To require that at least two conditional expressions be true before BR follows the THEN instructions.

2. The AND keyword:
a) May be used only once in each IF clause.
b) Requires two conditions to be met before an expression is evaluated as true.
c) Is required in all IF statements.

3. The OR option:
a) Cannot be specified when the IF statement already uses the AND option.
b) Must be specified within parentheses.
c) Tells Business Rules! to execute the THEN instructions when at least one of a set of conditional instructions is true.

Answers 5.4

 

5.5 Subroutines; GOSUB and RETURN statements

GOSUB is an unconditional branching statement which is much like GOTO except that it allows you to send program control to a subroutine, which returns to the line of code immediately after the line of code that called it. 

A subroutine is a line or a set of lines of code separated from the main flow of a program. The subroutine may be executed as many times as desired by the programmer.

When a subroutine is called, a line-ref must be included, (which is a line number or label).

Syntax to call a subroutine
010 GOSUB ROUTINE_NAME
Syntax to execute the subroutine and return back
100 ROUTINE_NAME:!
200  ! here you put any instructions desired
300  ! here you put more instructions if desired
         ….
900 return

When Business Rules! has finished executing the subroutine, it encounters a required RETURN statement which sends it back to the point from which it left off in the main program.

In order to visualize how subroutines work, look at this diagram:

A typical subroutine is a set of calculations or a set of instructions that may be used more than once in a program.  It is often coded at the end of a program. In BR the line numbers are subject to a limit of 99999 program lines.

Note

BR programs can be up to 99999 lines in length. You cannot specify a line number higher than 99999.

There are two requirements when you use the GOSUB statement:

  1. the GOSUB statement itself must always include a line-ref (either a line number or a line label) that tells Business Rules! where to find the first line of the subroutine, and
  2. the specified subroutine must always end with a RETURN statement.  Business Rules! will send a syntax error when you try to SAVE or RUN a program that has a GOSUB statement but no corresponding RETURN statement.

The following GOSUB statement tells BR to transfer program control to the subroutine which starts with the line label SALESTAX.  BR keeps track of the position of this GOSUB (sometimes referred to as the calling GOSUB because it calls for the services of the subroutine) until it encounters a RETURN statement.  It then returns program control to the first statement after the GOSUB in the main part of the program.

250 GOSUB SALESTAX 

SALESTAX, as its name implies, could be a subroutine which calculates state sales tax (of 6%, in the following case), on the purchase price of a retail sale.  When such a calculation is used several times in a program, the programmer saves time and space by branching control to a single subroutine instead of rewriting the calculation each time it is needed.  Note that the following example of this subroutine begins with the line label which was specified in line 250 (above), and ends with a RETURN statement.

10000 SALESTAX: ! A subroutine to figure sales tax of 6% on retail sales 
10010 PRINT “Enter purchase price” 
10020 INPUT PRICE 
10030 LET TAX=PRICE * 6 / 100      ! 6% 
10040 RETURN 

Quick Quiz 5.5

1. GOSUB is:
a) A conditional branching statement much like GOTO.
b) Only used with IF statements.
c) A branching statement which sends program control to a subroutine.

2. A subroutine:
a) Has a maximum length of 25,000 program lines.
b) Is a set of program lines which can be executed more than once in a program.
c) Always begins with a RETURN statement

3. The RETURN statement:
a) Is required at the end of a subroutine.
b) Sends program control back to the beginning of a program.
c) Works in conjunction with the GOTO statement.

Answers 5.5

 

Challenge Question

  You learned in this section that Business Rules! resumes execution with the first statement after calling GOSUB when it encounters a RETURN statement.  What would happen if Business Rules! resumed execution with the GOSUB statement instead?

Solution

5.6 What happens when you use GOSUB inside a subroutine?

A subroutine is exactly like any other part of your program except for two things: it should only be executed when a GOSUB statement sends control to it, and it must end with a RETURN statement.  Any statement (including GOSUB) that can be used in the main part of a program can also be used in a subroutine.  You can then design programs with subroutines that call subroutines.  Subroutines that are referenced from within other subroutines are referred to as nested.

Our old friend Zippy the Cursor may be able to help you envision the flow of a program when it uses a double (or triple or quadruple or even greater) sequence of subroutines.

One thing that we neglected to tell you earlier is that Zippy keeps a big piece of chalk in his back pocket.  Whenever he encounters a GOSUB statement, he runs to a room called the FLOWSTACK and marks its line number on a chalkboard.  He then dashes on to the specified subroutine and begins executing that.  If he then encounters another GOSUB statement, he again stops in at the FLOWSTACK to add its line number to the chalkboard.  He then goes on to execute the specified subroutine.  Zippy will go through this process until all the GOSUB line numbers are written on the chalkboard.

When Zippy finally gets all the way through a subroutine and reaches a RETURN statement, he goes back to the FLOWSTACK room, finds the last number on the chalkboard and erases it.  He then locates this same line number in the program, recognizes the GOSUB statement it contains, and starts executing again with the next statement after the GOSUB.  He goes through this same procedure every time he encounters a RETURN statement.

The amount of line numbers written at any one time on the chalkboard in the FLOWSTACK room is the number of active GOSUBs that a program contains.  As soon as a line number is erased, that GOSUB is no longer active.  As was already mentioned, the maximum number of active GOSUBs that a program can contain is 50.

Calling a subroutine while already inside another subroutine is called nested subroutines. Study the following diagram to visualize what happens as nested subroutines are executing:

Below is the code for the diagram above:

010  MAINLOOP: ! Main Part Of The Program
020     print "Enter the item price"
030  INPUT_PRICE: input Price conv INPUT_PRICE
040     gosub CALCULATE_TAX
050     print "Your total price with tax is: $"; Price + Tax
060     stop
070  !
080  CALCULATE_TAX: !
090     gosub CHECK_TAX_FREE_WEEKEND
100     if Tax_Free$ = "Y" then
110        let Tax = 0
120     else
130        let Tax = Price * 6 / 100
140     end if
150     return
160  !
170  CHECK_TAX_FREE_WEEKEND: !
180     print "Is today TAX FREE wekend? Enter Y or N"
190     input Tax_Free$
200     return 

Quick Quiz 5.6

1. How does a subroutine differ from other parts of a program?
a) It cannot contain additional GOSUB statements.
b) It should be executed only when a GOSUB statement branches program control to it.
c) It always ends with a RETURN statement.
d) Both b and c.

2. Where does Business Rules! keep track of the number of active GOSUBs in a program?
a) In the error-handling routine.
b) In the directory.
c) In the FLOWSTACK.

3. What is the maximum number of GOSUBs which may be active at any one time in a program?
a) 50
b) 9
c) Unlimited.

4. What is the maximum number of GOSUBs which may be used in a program?
a) 9
b) 50
c) Unlimited

Answers 5.6

 

5.7 Writing a Menu

A program menu appears on the screen and gives the user a list of options or functions that the program will perform. When the user chooses one of the options, that program immediately branches to the routine that performs that function.

Menus can be designed with PRINT, IF and GOTO statements.  The entire role of some programs in life is to be a menu for the selection of other programs, while some programs include menus and perform other work.

Imagine that you are asked to write a program for a company which would like to keep better records on its fleet of vehicles.  Vehicle use for this company is divided into four service categories: sales, grounds use, delivery and executive use.  The program must be designed so that the figures for each group are recorded separately, but also so that the user can choose to enter information for the categories in any order.

One way to organize a program such as this is to break it into four major chunks, each of which returns to the main flow of the program when finished.  The following example uses GOTO as the THEN instructions in the IF statement.

10 ! **********************COMPANY VEHICLES********************** 
20 PRINT “Type the number of the service category you wish to enter information about, or type Q to quit:” 
30 PRINT “1 - Sales”                   | 
40 PRINT “2 - Grounds use”        | This is the menu that 
50 PRINT “3 - Delivery”               | the user will see. 
60 PRINT “4 - Executive use”      | 
70 PRINT “Q - Quit”                    | 
80 INPUT CHOICE$                                    
90 IF CHOICE$=”1” THEN GOTO SALES             |    comments can serve 
100 IF CHOICE$=”2” THEN GOTO GROUND        |    as dividers between 
110 IF CHOICE$=”3” THEN GOTO DELIV            |    major parts of a 
120 IF CHOICE$=”4” THEN GOTO EXEC             |    program. 
130 IF CHOICE$=”Q” THEN GOTO END              | 
140 STOP 
1500 ! ********************************************************** 
1510 ! ********************************************************** 
2000 SALES: ! This section records information about sales vehicles. 
o 
o 
o 
3410 GOTO 20 
3420 ! ********************************************************** 
3430 ! ********************************************************** 
6000 GROUND: ! This section records information about ground use vehicles. 
o 
o 
o 
7050 GOTO 20 
7060 ! ********************************************************** 
7070 ! ********************************************************** 
10000 DELIV: ! This section records the information on delivery vehicles. 
o 
o 
o 
11260 GOTO 20 
11270 ! ********************************************************* 
11280 ! ********************************************************* 
14000 EXEC: ! This section records information about executive vehicles. 
o 
o 
o 
15900 GOTO 20 
15910 ! ********************************************************* 
15920 ! ********************************************************* 
99999 END: END 

Can you make a diagram and chart the general flow of the above program?  Subroutines are usually diagrammed to the right of the main program.

Quick Quiz 5.7

1. A program menu:
a) Describes the options which can be ordered with a software package.
b) Operates much like the table of contents in a book.
c) Is the list of the files in a directory.

Answer:
Answer

Challenge Question

GOSUB statements can be used to achieve the same results as the GOTOs in the above COMPANY VEHICLES program.  What changes would you have to make to the program for this to happen?  Which method is the more efficient way to code the menu into the program?

Answer

 

Chapter 5 Exercises

1. Write a program to calculate distance in meters.  The metric equivalent is that one meter is 39.37 inches.  The user will input the distance in feet and inches (hint: use two separate INPUT statements for feet and inches).  Allow the user to execute the program several times.  The program should end when the user enters a negative number for feet (don’t forget to tell the user this arbitrary rule for how to end the program).

2. Write a program to compare two loans.  Use a subroutine to calculate the amount of the monthly payment on a loan.  You can modify the program that you wrote for Chapter 4, Assignment 2.  For each loan, your program should accept a dollar amount, an interest rate, and a number of years.  Your subroutine should do all calculations for the loan.  A possible outline of your program is:

a) Input numbers for first loan.
b) Execute subroutine.
c) Print and store first monthly payment.
d) Input numbers for second loan.
e) Execute subroutine.
f) Print second monthly payment.
g) Subtract two monthly payments.

With this program, you can answer questions like “How much will I save if interest rates drop one-half percent lower?”, or “How much will I save on monthly payments if I pay an extra $1000 to reduce the loan amount on my new house?”

3. Add “range checks” to the program that you wrote for Assignment 2.  Immediately after each of the numbers are entered, check that the values fall within the following boundaries or ranges:

a) Amount of Loan -- between $0 and $1,000,000.
b) Interest Rate -- between 1 and 30 percent.
c) Number of Years -- between 1 and 35 years.

If the user enters any numbers outside these ranges, the numbers should be rejected and a message should be printed about what values are acceptable (hint: use IF statements with AND or OR).

4. Modify the program you wrote for assignment 2 (or 3) so that the input section for the second loan will use corresponding values from the first loan if zero is entered.

For instance, if the first loan is for $100,000, at 8 percent for 10 years, the user could compare the same loan at 9 percent by entering for the second loan 0, 9, 0 for the loan amount, rate and years, respectively.  The program would treat this second loan as if the user had entered $100,000, 9 percent and 10 years.

Solutions


NEXT: Debugging Features

Back to Index