0% found this document useful (0 votes)
330 views25 pages

An Introduction To Programming The HP 48G/48GX Calculator: Thiel College

Uploaded by

bogus1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
330 views25 pages

An Introduction To Programming The HP 48G/48GX Calculator: Thiel College

Uploaded by

bogus1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

An Introduction to Programming

the HP 48G/48GX Calculator


by

Mervin E. Newton
Thiel College
© Copyright 1999

by

Mervin E. Newton

All rights reserved.

i
To

Sara Franco Newton

ii
Table of Contents

Copyright . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i

Dedication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ii

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv

Section 1 - What is a Program? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


EXERCISE SET 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Section 2 - Stack Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2


EXERCISE SET 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Section 3 - Editing and Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Section 4 - Variables, Input, Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4


EXERCISE SET 3/4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Section 5 - Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
EXERCISE SET 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Section 6 - Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
EXERCISE SET 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Section 7 - Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
EXERCISE SET 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

Section 8 - Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
EXERCISE SET 8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

iii
Preface

This introduction assumes the reader is already familiar with the basic operation of the Hewlett
Packard HP 48G series calculators; it deals only with programming techniques. For simplicity the
calculator will be referred to as the HP48G, but everything said applies to both the HP 48G and to the
HP 48GX.

To be more specific, this introductin deals only with those programming techniques which will
be needed by students in our Numberical Analysis course at Thiel College. Readers interested in more
advanced programming techniques should consult HP 48G Series Advanced User's Reference
Manual. Unfortunately this publication does not come with the calculator, but should be available
anywhere the calculator is sold.

The author wishes to thank Sara Franco Newton, Kara McDowell (Thiel class of 2001), and
Nicole Volchko (Thiel class of 2000) for their help in proof reading this work. Thanks also to Michelle
Porada (Thiel class of 2000) for her help in preparing it for the WWW.

An interactive version of this text can be found on the WWW at


http://www.thiel.edu/mathproject/itphpc/

iv
Section 1 - What is a Program?

Basically, an HP48G program is an object which contains a listing of the steps to solve a
particular type of problem. Let's look at a simple example. In a typical bowling league each member
of each team bowls three games in a match. To find the average for a particular member for the match,
you must add the individual's three scores and divide by 3. If the three scores were on the stack of
your HP48G, you would push the plus sign twice, enter a 3, and push the division key. Let's make this
a program. On the HP48G the listing of a program must be enclosed in the symbols << >>, which is a
left shifted minus sign. Our program then, would be

<< + + 3 ÷ >>

Type the above program into the command line then press ENTER. Notice that as soon as
you press the left shift and << >>, you see the PRG annunciator in the upper right corner of the
display, telling you that the calculator is in program mode. Also notice that division is shown as "/" in
the program. For a program to be useful, it must be given a name and saved. Let's call it BWL1.
Type 'BWL1' into the command line and press STO. If you now press VAR you should see BWL1
as the first item in your menu. To run the program put three scores on the stack and press the menu
button for BWL1. Try it with the scores 172, 188, and 186: put the three numbers on stack levels 1,
2 and 3, then press the BWL1 menu key. You should see 182 on level 1 of the stack. (NOTE: The
last number in the previous example could, alternatively, have been left in the command line; as in most
HP48G operations.)

The program above is short enough to fit in one line on the screen, but that will not always be the case.
When entering longer programs it is helpful to use the carriage return, ↵ , (right shift decimal point) to
go to a new line while in program mode. This also serves as a carriage return in a string.

EXERCISE SET 1

1. Write a program called 'TAX' to find a six percent sales tax for the amount in level 1 of
the stack. HINT: If you set your NUMBER FORMAT to Fix 2 the tax will be shown rounded to the
nearest penny.

2. Your sales force works 4 days per week. Each person's pay for the week is $400 plus 5% of sales
over $1000. For example: a salesperson who sells $1200 in the week would earn 5% of $200 plus
$400 is $410. Write a program to take the four daily sales figures from the stack and compute the

1
person's pay for the week. WARNING: Be sure you do not penalize a person who sells less than
$1000 for the week. The MAX function (MTH > REAL > MAX) should be helpful here.

3. In Ohio (as in many other states) the exits on the interstate highways are numbered by the nearest
mile marker, and the speed limit is 65 MPH. Write a program to take the exit number and the mile
marker you just past from the stack and compute the time it will take you to reach the exit assuming you
are traveling at 65MPH. NOTE: The ABS function (MTH > REAL > NXT> ABS) should be useful
to make sure you don't end up with a negative time.

Section 2 - Stack Manipulation

When working on the HP48G we frequently make use of the stack manipulation commands
which are available on the keyboard; ENTER, CLEAR, DROP, and SWAP. The ENTER
command is interesting in that it has several different functions depending on the status of the calculator.
The function of interest here is to duplicate the object in level 1 of the stack. With this understanding of
ENTER, all four of these commands are also available for programming using the same keys, BUT you
must left shift to enter the command into a program. Another difference with the ENTER key is that
you will see DUP as the command in the program.

There are 10 other stack manipulation commands which we tend not to use when working by
hand, but which are very helpful when programming. You will find the menu with these commands by
pressing left shift and STACK. The details about these commands can be found on pages 3-11 and
3-12 of the HP 48G Series User's Guide which comes with the calculator.

Suppose the bowling league of Section 1 computes a bowlers handicap for next week as 80%
of (200 minus this week's average). Let's write a program to take three scores from the stack and
leave the total on level 3, the average truncated to an integer on level 2, and next week's handicap
truncated to an integer on level 1.

<< + + DUP 3 ÷ FLOOR 200


OVER - 0 MAX .8 × FLOOR >>

Type this program into your calculator and store it as BWL2 then try it with several sets of data.
Notice that the commands 0 MAX are needed to make sure that a bowler whose average is over

2
200 will not have a negative handicap. The FLOOR function can be found at MTH > REAL > NXT
> NXT > FLOOR and is described on page 12 - 9 of the User's Guide.

EXERCISE SET 2

1. Change Problem 3 of Exercise Set 1 so that the distance is left on level two of the stack and the time
on level 1.

2. Change Problem 1 of Exercise Set 1 so that the original amount is left on level 3 of the stack, the tax
on level 2, and the total on level 1. Try to find three different solutions to this problem: one which uses
a couple of OVER commands at the end to find the total, one which uses an extra DUP early in the
program and ROT near the end to find the total, and one which uses the PICK command near the end
to find the total. Generally speaking, if two programs produce correct results but are of different
lengths, the one with the fewer steps is considered better than the longer one. With this in mind, is there
one of your three solutions which is "best?" Is there one which is "worst?"

3. Write a program to do linear interpolation. That is, given the two points (x1, y1), (x2, y2) and a
y2 − y1
number x between x1 and x2, find y = y1 + ( x − x1). The program should begin with x1 in
x2 − x1
level 5, y1 in level 4, x2 in level 3, y2 in level 2, and x in level 1; and should end with y in level 1. (First
strive for a solution which works, but then try to do it in at most 14 steps.)

Section 3 - Editing and Debugging

It is an unfortunate fact of life that humans make mistakes (called bugs) which cause the
calculator to halt in mid program because it has been asked to do something impossible or which cause
the calculator to give wrong answers. One of the easiest ways to find a bug in a program is to have the
calculator execute the program one step at a time so we can see exactly what it is doing. Let's look
again at the example BWL2 from Section 2. Put three bowling scores on levels 4, 3 and 2, and
'BWL2' on level 1. Now press PRG > NXT > RUN > DBUG. The program name will be taken off
the stack and the annunciator HALT will appear at the top of the screen. Now press the SST menu
key once for each step of the program. Notice that with each press the step being executed is shown in
the upper left corner of the screen and the result is shown on the stack. If you find an error and choose
not to continue single stepping through the program, press the menu button for KILL, to return to
normal keyboard commands.

3
Once an error is found we need to edit our program. Suppose we want to edit BWL2. Put
'BWL2' on the stack then left shift EDIT. (WARNING: This is one of the few cases where the name
must be on the stack, not in the command line, to get what you want.) The program will now show on
the screen and you can use the arrow keys to move around the program. A handy thing to remember,
especially when you are editing a long program, is that right shift down arrow gets you to the end of the
program and right shift up arrow gets you to the beginning of the program. When the cursor is where
the changes are needed, you can type in new things and use the backspace or delete keys to remove
things. There are also several editing commands in the menu. These are explained on page 2-12 of the
User's Guide. When all the necessary corrections have been made, press ENTER to make the
changes permanent and return to normal operations. If you decide you wish to exit without making the
changes permanent, press the CANCEL key and the program will be left unaltered.

In some cases (as in Problems 1 and 2 of Exercise Set 2) you may wish to create a new
program by making changes to an existing program, but leaving the original intact. To do this, right shift
and press the menu key for the desired program to put it on the stack, then left shift EDIT. Make the
necessary changes and press ENTER. The new version is now on the stack and can be saved under a
new name, but the original is unaltered.

Section 4 - Variables, Input, Output

In all of our examples so far we have placed the necessary data on the stack before the
program starts. This works but it can create problems for both the programmer and the user. This is
best demonstrated by Problem 3 of Exercise Set 2; manipulating the stack with five values is somewhat
of a challenge for the programmer, and the user must remember the exact order in which the data must
be entered for the program to work correctly. It would also be helpful to the user if programs like
BWL2 which have several results, had each output item labeled. In this section we will learn about the
use of variables, which helps reduce the amount of stack manipulation which may be required by a
program, and we will learn about some input and output techniques which will make the programs more
user-friendly.

There are two types of variables available for programming, global and local. The variables
you learned to use in Chapter 5 of the User's Guide are global variables. They function in programs
just as they do in normal operation. Local variables are specific to a program and live only while the
program is running. It is customary to use upper case letters for global variables and lower case letters
for local variables. To create local variables you must first put the values on the stack, put in an arrow
(right shifted zero key), then the list of variable names,and finally a new set of << >> (like a program

4
within the program). The local variables are now available to this inner program and can be used the
same as global variables. We will see an example of this below.

The problem of forcing the user to memorize the order in which data must be entered can be
solved with the INPUT command. This command allows the program to prompt the user for the data
one item at a time. To use the command there must be a prompt (a string telling the user what to enter)
on level 2 of the stack, "" on level one of the stack, then the INPUT command which can be found at
PRG > NXT > IN > INPUT. When the command is executed the program pauses with the prompt
displayed at the top of the screen and the cursor set to the command line ready for input. When the
user presses ENTER the program resumes and places the input on level 1 of the stack as a string.
Because the input is a string the most common command to follow the INPUT command is the OBJ->
command which can be found at PRG > TYPE > OBJ->. We will see an example of this below.

We will discuss two methods of labeling output, tagged output and the message box. Tagged
output is generally used at the end of a program. It leaves one or more output items on the stack, each
with an explanatory tag. The message box is generally used to pause the program with intermediate
results during program execution. After a message box comes up, the user must acknowledge it by
pressing OK for the program to continue.

To create a tagged output item the output object should be on stack level 2 and the desired
explanatory tag on level 1 as a string. Then the ->TAG command, which is found by PRG > TYPE >
->TAG, will combine them into a tag object on level 1. For the message box, put a message in a string
on level 1 and issue the MSGBOX command which is found by PRG > NXT > OUT > MSGB. To
create the message string, use the + to concatenate the parts. For example, suppose you wish to
display the message "There are # apples in the bag.", where # is a number which is on level 1 of the
stack. Use the following steps:

<< ... "There are " SWAP + " apples in the bag." + MSGBOX ... >>.

Notice that it was not necessary to convert the number to a string; when + operates on a string and a
number it converts the number into a string then concatenates. If, however, you wish to concatenate
two numbers, you must first explicitly convert at least one of them to a string with PRG > TYPE >
->STR. It is also important to note that when + is used for concatenation it is not a commutative
operation; the object in level 2 will appear in front of the object in level 1.

5
We will now consider two new version of our bowling program; the first will demonstrate the
use of global variables and the message box, and the second will demonstrate the use of the INPUT
command, local variables, and tagged output.

For the first example, which we call BWL3, we will make the following assumptions. During
the play of the games we were using a score keeping program which left the scores of
the three games in the calculator memory as SCR1, SCR2, and SCR3, and we want BWL3 to leave
the new handicap in memory as HNCP for use by the score keeping program next week. With this in
mind, the coding for BWL3 is

<<
SCR1 SCR2 + SCR3 + "SERIES TOTAL = " OVER + MSGBOX
3 / FLOOR "AVERAGE = " OVER + MSGBOX 200 SWAP - 0 MAX
.8 * FLOOR "NEW HANDICAP = " OVER + MSGBOX 'HNCP' STO
>>

Try single stepping through this program to see exactly how it works. Notice that you will have to
create the global variable SCR1, SCR2, and SCR3 before you can run the program. It is not
necessary to create HNCP in advance, the calculator will create it if it does not exist, and will overwrite
the existing version if it does exist.

The second example, which we will call BWL4, will use the INPUT command, local variables,
and tagged output. Admittedly, the use of local variables in this case is not particularly helpful, but it
does provide an example. Unlike BWL3, this program is intended to stand alone.

<<
"GAME 1 SCORE" "" INPUT OBJ->
"GAME 2 SCORE" "" INPUT OBJ->
"GAME 3 SCORE" "" INPUT OBJ->
0 0 0 --> s1 s2 s3 tot avrg hncp
<<
s1 s2 + s3 + 'tot' STO
tot 3 / FLOOR 'avrg' STO
200 avrg - 0 MAX .8 * FLOOR 'hncp' STO
tot "TOTAL" ->TAG

6
avrg "AVERAGE" ->TAG
hncp "HANDICAP" ->TAG
>>
>>

Notice that to create the local variables tot, avrg, and hncp it was necessary to put a
temporary values of 0 on the stack for each of them. Again, try single stepping through this program to
see exactly how it works.

The HP48G has several other input and output features which will not be discussed in this text.
Those interested in these more "exotic" I/O forms should consult the Advanced User's Reference
Manual.

EXERCISE SET 3/4

1. Change Problem 2 of Exercise Set 2 to add tags to the three lines of output.

2. Change Problem 1 of Exercise Set 2 so that the desired exit number and the speed limit are
obtained from global variables and the current milage marker is entered with an INPUT command.
The distance and time should be reported by way of message boxes.

3. Change Problem 3 of Exercise Set 2 so that the values of x 1, y1, x 2, y2, and x are entered with
INPUT commands and are assigned to local variables. Before data entry starts, a message box should
instruct the user to choose the node with the smaller x value as (x 1, y1). The output, y, should be
tagged.

Section 5 - Branching

We will discuss two general types of branching, IF and CASE. The IF structure has the form:

IF condition THEN
block 1
ELSE
block 2
END

7
The condition is an expression which is either true or false and each of the blocks is a set of one or
more instructions. If the condition is true then all the instructions in block 1 are executed, if condition
is false, then all the instructions in block 2 are executed. The ELSE block 2 is optional.

The CASE structure has the form

CASE
condition 1 THEN
block 1
END
condition 2 THEN
block 2
END
.
.
.
condition n THEN
block n
END
block n + 1
END

The block of instructions corresponding to the first true condition encountered is the only block which
will be executed. If none of the conditions is true, block n + 1 will be executed. This last block is
optional.

Before we can continue with the IF and CASE structure, we need to understand how the
HP48G works with boolean values and operations. PRG > TEST brings up a menu with six relational
functions. Each of the functions takes values from level 2 and level 1 and returns a 1 if the relation is
true and 0 if the relation is false. For example, put 5 on level 2 and 8 on level 1. If you press < you get
a 1 and if you press > you get a 0. Press NXT to get to the next page of this menu and you find the
commands AND, OR, XOR, and NOT. These four operations are the same on the calculator as they
are in logic; AND is true if both conditions are true, OR is true if at least one condition is true, XOR is
true if exactly one of the conditions is true and NOT is true if the condition is false. The first three of
these are binary functions which act on levels 1 and 2 of the stack. AND returns 1 if both values are

8
1's and 0 otherwise. OR returns 1 if at least one of the values is a 1, and 0 otherwise. XOR returns 1
if exactly one of the values is 1 and the other is 0, and returns 0 otherwise. NOT toggles the value on
level 1 between 0 and 1. It should be noted that these four logical functions and also the THEN
command which we will discuss in the next paragraph, treat any nonzero real number as a 1. If, for
example, you place .5 on lever 2 of the stack and -3.7 on level 1 and press AND the response will be
a 1.

We are now ready to return to the IF and CASE structures. The critical element here is the
THEN statement. When the calculator comes to THEN it takes the value off of level 1 of
the stack. If the value is true (that is, any real number not equal to zero), it executes the block of
instruction immediately following, and at the end of that block goes to the very end of the IF or CASE
structure. If the value is false (i.e., a zero) the program skips to the next section of the structure its
working through; in the case of the IF statement it goes to the block after the ELSE if there is one, or
to the END of the IF if there is no ELSE; in a CASE structure it goes to the next condition, to block n
+ 1, or the END of the CASE, whichever comes first.

PRG > BRCH > IF gets one to the menu with the IF elements and PRG > BRCH > CASE
to the menu with the CASE elements, but that's not the best way to get those structures into a program.
From the BRCH menu left shift IF will put IF ... THEN ... END into the program and right shift IF
will put IF ... THEN ... ELSE ... END into the program. Left shift CASE will put CASE ... THEN
... END ... END into the program and each right shift CASE will put in an additional THEN ... END.
These typing aids make the job easier and help eliminate the very common error of forgetting to put in
an END statement.

We will write a program to calculate a person's pay for a week. The input will be the hourly
rate and the hours worked. If the hours worked is greater that 40, the person is to receive an extra half
pay for the hours over 40.

<<
"HOURS WORKED" "" INPUT OBJ->
"PAY RATE" "" INPUT OBJ->
--> h p
<<
hp*

9
IF h 40 > THEN
h 40 - p 2 / * +
END
>>
"PAY" ->TAG
>>

Enter this program and save it as PAY1. Single step through the program three times with the hours
worked less than, equal to, and greater than 40.

We will now write a new version of BWL3 which will use an IF statement to overcome the
problem of a negative handicap if the bowler's average is greater than 200.

<<
SCR1 SCR2 + SCR3 + "SERIES TOTAL = " OVER + MSGBOX
3 / FLOOR "AVERAGE = " OVER + MSGBOX
IF DUP 200 < THEN
200 SWAP - .8 * FLOOR
ELSE
DROP 0
END
"NEW HANDICAP = " OVER + MSGBOX 'HNCP' STO
>>

Save this program as BWL5 and single step through it a couple of times, once with the average less
that 200 and once with it over 200. BWL3 is actually a more efficient program than this one, but this
gives us a good example of how the IF statement works, and it is easier to read this program and
understand what it is doing.

For an example of a CASE structure we will write a program to solve the quadratic equation
2
ax + bx + c = 0. We will assume we are only interested in real solutions, so we will write the program
to output a message about the type of roots, but only give the values in the case of two distinct real
roots or a double root.

10
<<
"ENTER LEADING ↵ COEFFICIENT" "" INPUT OBJ->
"ENTER COEFFICIENT ↵ OF LINEAR TERM" "" INPUT OBJ->
"ENTER CONSTANT TERM" "" INPUT OBJ->
0 --> a b c d
<<
b x2 4 a * c * - 'd' STO
CASE
d 0 > THEN
"THE ROOTS ARE " b +/- d +2a*/+
" AND " + b +/- d - 2 a * / + "." +
END
d 0 == THEN
"THERE IS A DOUBLE ROOT AT " b +/- 2 a * / + "." +
END
"THE ROOTS ARE COMPLEX."
END
>>
MSGBOX
>>

Save this program as QDEQ and single step through it with different values of a, b, and c so that you
can see all three paths of the CASE in action.

It should be noted that the CASE structure is not necessary for a programming language
because anything which can be done with a CASE structure can also be done with an IF structure.
The CASE structure of QDEQ, for example, could have been written as

IF d 0 > THEN
"THE ROOT ARE " b +/- d +2a*/+
" AND " + b +/- d - 2 a * / + "." +
ELSE
IF d 0 == THEN
"THERE IS A DOUBLE ROOT AT " b +/- 2 a * / + "." +

11
ELSE
"THE ROOTS ARE COMPLEX."
END
END

Although not strictly necessary, the CASE structure certainly makes it easier, and the more choices
which must be considered, the bigger the advantage of the CASE structure over the IF structure.

EXERCISE SET 5

1. Add the coding necessary to your solution of Problem 2 of Exercise Set 3/4 so that if the time to the
desired exit is more than four hours a message box will warn the user of the need to plan an
intermediate rest stop.

2. Write a program to check a customer's credit availability. The user should be prompted to enter the
customer's outstanding balance, current purchase, and credit limit. If the outstanding balance plus the
current purchase is less than the credit limit a message box will say the purchase is approved, otherwise
it will disapprove the purchase.

3. Change the example PAY1 above to compute withholdings and net pay. If the employee earned no
more than $50, there is no withholding. If the earnings are more than $50 but no more than $300,
withhold 10% of the excess over $50. If the earnings are over $300, but no more than $500, withhold
$25 plus 15% of the excess over $300. If the earnings are over $500, withhold $55 plus 20% of the
excess over $500. There should be three lines of tagged output giving the gross wages, the
withholding, and the net wages.

4. Change Problem 3 of Exercise Set 3/4 so that if x is not between x 1 and x 2 a message box will give
the user a warning that the program is extrapolating.

Section 6 - Looping

One of the great powers of computer and calculator programs comes from the ability to repeat
a sequence of commands as many times as may be necessary. The HP48G provides five different
looping structures, only two of which will be discussed here. Those interested in the other looping
forms should consult the User's Guide and/or the Advanced User's Reference Manual.

12
The first looping structure we will explore is the WHILE structure. It has the form

WHILE condition REPEAT


block
END

The condition here is the same as in Section 5 and the REPEAT command works very much like the
THEN command discussed in Section 5. When the program reaches REPEAT the object is removed
from level 1 of the stack, if it is true (i.e. any nonzero real number) the block of instructions is execute
and then the program returns to condition and tests it again. Notice that something must happen to
eventually make the condition false, or the program will loop for ever. When the condition is false
(i.e., the object on level 1 is a zero), the program jumps to the first command after the END. All the
elements for the WHILE structure can be found in PRG > BRCH > WHILE, but as is the case with
the IF, doing a left shift WHILE from the BRCH menu will produce the whole
WHILE...REPEAT...END structure.

As an example we will write a program which is a variation on our earlier program to compute
our bowling average. In this case we will assume that we are simply out for an evening of bowling with
friends and don't know how many games we will bowl. We will have the calculator prompt the user for
the next score until a negative score is entered, which will be a signal (called a sentinel) that there are no
more scores.

<<
00
"ENTER FIRST SCORE" "" INPUT OBJ->
WHILE DUP 0 ≥ REPEAT
+ SWAP 1 + SWAP
"ENTER NEXT SCORE ↵ OR -1 TO QUIT" "" INPUT OBJ->
END
DROP
IF SWAP DUP 0 > THEN
/ "AVERAGE" ->TAG
ELSE
"NO SCORES TO AVERAGE" MSGBOX DROP2
END
>>

13
Save this program as BOL1 and single step through it at least twice, once with several scores before
the -1 is entered and once with -1 entered as the first score. Observe carefully how it all works.

The second looping procedure we will consider is the FOR structure, which has the form

first last FOR index


block
NEXT

In this structure first is an integer which represents the first value of the loop index, last is an integer
which represents the last value of the loop index, and index is the loop index and is a local variable
which lives only while the loop is in effect. WARNING: Because i = − 1 to the calculator, using i
as the loop index can sometimes cause strange behavior. Although it is legal, it is better to choose
some other letter for index. When the FOR structure is encountered first and last are removed from
levels 2 and 1 of the stack respectively, the value first is assigned to index and the block is executed.
When the NEXT is encountered index is increased by 1; if it is still less than or equal to last, the block
is executed again; if index is greater than last, the program jumps to the next command after NEXT.
This continues until the loop is satisfied, that is, until index becomes greater than last. As soon as the
loop is exited, the index is no longer available. The FOR structure can be found at PRG > BRCH >
FOR. As in the previous structures we have studied, left shift FOR from the BRCH menu types in the
complete structure.

As an example, we shall rewrite BOL1 to prompt the user for the number of games played,
then ask for exactly that number of scores.

<<
"HOW MANY GAMES?" "" INPUT OBJ->
IF DUP 0 > THEN
--> n
<<
0 1 n FOR k
"ENTER SCORE " k + "" INPUT OBJ-> +
NEXT
n / "AVERAGE" ->TAG
>>

14
ELSE
"NO SCORES TO AVERAGE" MSGBOX DROP
END
>>

Save this program as BOL2 and single step through it at least twice, once with a positive first input and
once with zero as the first input. It won't show on this program because it is protected by the IF
statement, but if last starts out smaller than first the FOR loop will still be executed once.

EXERCISE SET 6

1. Change Problem 1 of Exercise Set 3/4 to prompt the user to enter the price of each item the
customer is purchasing until a zero is entered. It should then display the subtotal, the tax, and the total
as tagged output.

2. Professor Dinklesmith gives 10 quizzes during the semester and the final grade is the average of the
10 scores. An average of 90% or better is an A, 80% or more but less than 90% is a B, 70% or more
but less than 80% is a C, 60% or more but less than 70% is a D, and less than 60% is an F. Write a
program which will prompt the user for the ten scores then output the average with the appropriate
letter grade as a tag. For example, if the average is 87.3, the output should be B: 87.3

Section 7 - Flags

The HP48G has 64 user flags (numbered 1 to 64) which can be thought of as built in boolean
variables. PRG > TEST > NXT > NXT will take you to a menu with six flag commands; SF = set
flag, CF = clear flag, FS? = is flag set?, FC? = is flag clear?, FS?C = is flag set and clear it, and FC?C
= is flag clear and clear it. To use any of the commands a flag number must be on level 1 of the stack.
When the command is executed, the number is removed from the stack, and in the case of the last four
commands, the appropriate response is placed on level 1. For more details on these commands see
page 4-8 of the User's Guide.

Suppose our bowling league is for families with children and the kids get a little extra handicap
depending on their ages: those at least 10 but less than 13 get an extra 5 pins, those at least 7 but less
than 10 get an extra 10 pins, and those less than 7 get an extra 15 pins. We will rewrite BWL4 to
incorporate these new rules and call it BWL6. Run it with different choices for the ages of the bowler

15
to see how it works. Notice that when a flag between 1 and 5 is set, an annunciator is lit. The list {""
α } preceding the INPUT command in the program below causes the alpha lock to be set so the user
need only press Y or N. See Page 3-154 of the Advanced User's Reference Manual for more
information about the INPUT command.

<<
"IS THE BOWLER LESS ↵ THAN 13? Y/N" {"" α } INPUT
IF "Y" == THEN
"ENTER AGE GROUP: ↵ < 13 = 1, < 10 = 2, ↵ < 7 = 3."
"" INPUT OBJ-> SF
END
"GAME 1 SCORE" "" INPUT OBJ-->
"GAME 2 SCORE" "" INPUT OBJ-->
"GAME 3 SCORE" "" INPUT OBJ-->
0 0 0 --> s1 s2 s3 tot avrg hncp
<<
s1 s2 + s3 + 'tot' STO
tot 3 / FLOOR 'avrg' STO
200 avrg - 0 MAX .8 * FLOOR
CASE
1 FS?C THEN 5 + END
2 FS?C THEN 10 + END
3 FS?C THEN 15 + END
END
'hncp' STO
tot "TOTAL" ->TAG
avrg "AVERAGE" ->TAG
hncp "HANDICAP" ->TAG
>>
>>

EXERCISE SET 7

1. Change Problem 3 of EXERCISE SET 5 as follows: If the employee is over 62 or disabled, the
withholdings are reduced by 10% of the initial calculation; if the employee is both over 62 and disabled,
the withholdings are reduced by 15% of the initial calculation.

16
Section 8 - Arrays

It is assumed that the reader is familiar with the use of arrays and their associated commands on
the keyboard and various menus. Besides the GET and PUT commands to access specific elements of
an array, there is an algebraic way of accessing them which is frequently much more convenient in
programs. In what follows let v be a vector and M be a matrix. Then 'v(k) + 7' EVAL will get the kth
element of v, add 7 to it, and leave the result on the stack. The sequence 12 'M(2,5)' STO will replace
the element in the 2nd row and 5th column of M with the number 12. Suppose that A is a vector of
unknown length that contains integers and which has been stored in memory. We want to find the
average of the elements of A to one decimal place and then determine if one of the elements of A is
equal to that average. NOTE: The STO+ and INCR commands in the program below (and other
memory arithmetic functions which are available on the calculator) can be found by left shift
MEMORY > ARITH. The SIZE command can be found by MTH > MATR > MAKE.

<<
A SIZE 1 GET 1 O O --> n k sum av
<<
1 n FOR j
'sum' 'A(j)' EVAL STO+
NEXT
sum n / 'av' STO 1 SF
WHILE k n ≤ 1 FS? AND REPEAT
IF 'A(k)==av' THEN
1 CF
ELSE
'k' INCR DROP
END
END
"AVERAGE = " 1 FIX av + " ↵ IT IS " + STD
IF 1 FC?C THEN
"THE " k +
CASE
k 1 == THEN "ST" END
k 2 == THEN "ND" END
k 3 == THEN "RD" END
"TH"
END

17
+ " ↵ ELEMENT OF A." +
ELSE
"NOT IN A."
END
+ MSGBOX
>>
>>

Save this program as FDAV and single step through it with several different vectors A to see how it
works. Be sure to choose values which will test all the paths through the IF and CASE structures.

EXERCISE SET 8

1. With a vector A as in the example FDAV above, write a program to go through the vector to find
the smallest value and to see if there is more than one element with that smallest value. The output
should include the smallest value, the index of the first occurrence of the smallest value, and a statement
about whether or not that value is unique.

18
INDEX

<< >>, 1, 4 MSGBOX, 5, 6, 10, 11, 13, 15, 18


Annunciator, 1, 16 OBJ->, 5, 6, 9, 11, 13, 14, 16
Arrays, 17 OVER, 3, 6, 10
Branching, 7 PICK, 3
Carriage Return, 1, 11, 13, 16-18 PUT, 17
Commands, 2 REPEAT, 13
->TAG, 5, 6, 10, 13, 14, 16 ROT, 3
CANCEL, 4 SF, 15-17
CASE, 7, 8, 10, 11, 17 SIZE, 17
CF, 15, 17 SST, 3
CLEAR, 2 STD, 17
DBUG, 3 STO, 1, 6, 10, 11, 16, 17
DROP, 2, 10, 15 STO+, 17
DROP2, 13 SWAP, 2
DUP, 2, 3, 14 THEN, 7, 9
EDIT, 4 VAR, 1
ELSE, 8, 9 WHILE, 13, 17
ENTER, 1, 4 Concatenate, 5, 6, 10, 11, 17
EVAL, 17 Condition, 8, 9, 13
FC?, 15 Debug, 3
FC?C, 15, 17 Edit, 3
FIX, 17 Flags, 15
FOR, 14, 17 Functions
FS?, 15, 17 ABS, 2
FS?C, 15, 16 AND, 8
GET, 17 FLOOR, 2, 6, 10, 16
HALT, 3 MAX, 2, 6, 16
IF, 7, 8, 10, 11, 13, 17 NOT, 8
INCR, 17 OR, 8
INPUT, 5-7, 9, 11, 13, 14, 16 relational, 8
XOR, 8

19
Input, 4, 5, 7, 9 BWL4, 6, 15
Linear Interpolation, 3 BWL5, 10
Loop Index, 14 BWL6, 15
Looping, 12 FDAV, 18
Message Box, 5-7, 12 PAY1, 10, 12
Output, 4, 7, 15 QDEQ, 11
PRG annunciator, 1 Saving a Program, 1, 4
Prompt, 5, 13, 15 Sentinel, 13
Quadratic Equation, 10 Single Stepping, 3
Running a Program, 1 Stack Manipulation, 2, 4
Sample Programs String, 1, 5
BOL1, 14 Tagged Output, 5-7, 10, 13-16
BOL2, 15 Typing Aids, 9
BWL1, 1 Variable, 4
BWL2, 2-4 boolean, 8, 15
BWL3, 6, 10 global, 4, 6, 7, 17, 18
local, 4, 6, 7, 9, 11, 14, 16

20

You might also like