HP Prime Programming Tutorial
HP Prime Programming Tutorial
HP Prime Programming Tutorial
Over the next month, maybe month and a half, I plan to post programming tutorials for the HP
(Hewlett Packard) Prime.
If you have programmed with the HP 38G, 39g, or 39gii, this language will be similar to those. The
programming language for the Prime is named the HP Prime Programming Language (HPPP).
Throughout this tutorial, I am going to use the latest version of the software.
How to start writing a program:
1. Press Shift + 1 (Program).
2. Press New. It is the second touch key.
3. Enter the name of the program. Pressing the ALPHA key twice will turn on UPPERCASE LPHALOCK. Pressing ALPHA, Shift, ALPHA will turn on lowercase alpha-lock. To exit any lock, press the
ALPHA key one more time. When happy with the name, press Enter.
Comments can be typed. The are designated by two forward slashes. The slashes are typed by
pressing the Divide key ( ). Anything in the line following the two slashes is ignored in running the
program.
SQIN
Our first program is SQIN, because "Hello World" programs are so 2000s. SQIN takes a number,
squares it, then calculates the reciprocal. In short we are defining a custom function:
SQIN(x) = 1/x^2
Commands:
RETURN: returns a result to the stack (home page). You can return numbers, lists, vectors,
matrices, strings, or a combination of these times.
Access: Tmplt, 1. Block, 2. RETURN
All the program code in this tutorial series will be shown in Courier font.
EXPORTSQIN(X)
BEGIN
RETURN1/X^2;
END;
Tip: You can check the syntax of the program just by pressing the Check soft key in the program
editor. HP Prime will inform you if there is a syntax error and attempt to point you to the error. If
there are no syntax errors, the Prime states "No errors in the program". I use the Check command
all the time.
MOPMT
LOCAL: Declares any variables to be local to the program. In other words, the variables are
created, used, possibly displayed during program execution, and deleted at program termination.
Access: Tmplt, 4. Variable, 1. LOCAL
Tip: You can declare local variables and assign an initial value at the same time. For example:
LOCAL K:=1; stores 1 in K and makes K a local variable.
MOPMT calculates the monthly payment of a loan. The arguments are: the loan amount (L), the
interest rate (R), and the number of months (M).
EXPORTMOPMT(L,R,M)
BEGIN
LOCALK:=R/1200;
K:=L*K/(1(1+K)^M);
RETURN"Payment="+K;
END;
Tip: Use RETURN, TEXTOUT_P, and PRINT to return custom strings, which combine results,
messages, and calculations. Parts are connected with a plus sign.
Examples:
MOPMT(4000, 9.5, 30) returns 150.317437565
MOPMT(370000, 3.5, 360) returns 1661.46534383
Welcome to another programming tutorial for the HP Prime. In this session, we will cover MSGBOX,
IF-THEN-ELSE, PRINT, and the FOR loop.
MSGBOX
MSGBOX: MSGOX takes a string a makes a pop-up message box. Program execution stops until
you press a key to acknowledge the message.
Access: Cmds, 6. I/O, 8. MSGBOX
The program COMLOCK: Imagine that you are in charge of setting the combinations for the good,
old-school combination locks. This program gives three digit combinations through the use of
MSGBOX.
EXPORTCOMLOCK()
BEGIN
LOCALL0;
L0:=RANDINT(3,0,39);**
MSGBOX("SECRET:"+L0(1)+","+L0(2)+","+L0(3));
END;
** Thanks to Thomas Lake for pointing out my typo. Apologies for any inconvenience - Eddie
(3/21/2014)
Other commands that are featured:
RANDINT(n, a, b) generates a list of n integers between a and b. You can leave n out if you desire a
single random integer. Picks may be repeated.
The HP Prime's default list variables are designated L0 through L9.
IF-THEN-ELSE
IF-THEN-ELSE: Program structure:
IFconditionTHEN
doiftheconditionistrue;
ELSE
doiftheconditionisfalse;
END;
Access: Tmplt, 2. Branch, 2. IF THEN ELSE
Tip: You can leave out the ELSE part if you only want to test to see if a condition is true. Access the
simple IF-THEN structure by pressing Tmplt, 2. Branch, 1. IF THEN.
Access <, , ==, etc. by pressing Shift, 6. Note that the double equals is needed to check equality.
PRINT
PRINT: The PRINT command prints a sting, result, or a combination of both onto the Prime's
Terminal screen. If PRINT is used, the program will end on the terminal (text output) screen. Press a
button to exit.
You can access the terminal screen at any time by pressing the ON button, holding it, and then
pressing the Divide ( ) button.
Access: Cmds, 6. I/O, 9. PRINT
Tip: To clear the terminal screen, type PRINT(). This is a good way to clear the terminal screen and
I usually use this at the beginning of any program if PRINT is going to be used later on.
The program QROOTS (yet one more quadratic solver, sorry for not being original guys and gals),
demonstrates the use of IF-THEN-ELSE and PRINT.
Here I set the setting variable HComplex to 1, which allows for complex number results.
EXPORTQROOTS(A,B,C)
BEGIN
LOCALD;
PRINT();
HComplex:=1;
D:=B^24*A*C;
IFD?0THEN
PRINT("Rootsarereal.");
ELSE
PRINT("Rootsarecomplex.");
END;
PRINT((B+?D)/(2*A));
PRINT((B?D)/(2*A));
END;
Examples:
QROOTS(1,5,8) returns:
Roots are complex.
-2.5+1.32287565553*i
-2.5-1.32287565553*i
QROOTS(2,-4,-8) returns:
Roots are real.
3.2360679775
-1.2360679775
FOR
This section will explore the basic FOR structure:
FORvariableFROMstartTOendDO
commands;
END;
All the commands in the loop will be executed a set number of times. Each time a loop finishes,
thevariable increases by one. The loop terminates when variable=end.
Access: Tmplt, 3. LOOP, 1. FOR
The program SUMDIV takes any integer and adds up the sum of its divisors. For example, the
divisors of 12 are 1, 12, 2, 3, 4, and 6. The sum is 28.
The program:
EXPORTSUMDIV(N)
BEGIN
LOCALS:=0,K,mdiv,ldiv;
mdiv:=CAS.idivis(N);
ldiv:=DIM(mdiv);
FORKFROM1TOldiv(1)DO
S:=S+mdiv(K);
END;
RETURNS;
END;
** Thanks to Thomas Lake for pointing out that the variable "mat", which I had in this program was
unnecessary. - Eddie 3/21/2013
Examples:
SUMDIV(12) returns 28.
SUMDIV(24) returns 60.
SUMDIV(85) returns 108.
Program:
EXPORTTARGET()
BEGIN
LOCALC:=0,N:=RANDINT(1,20),G:=1;
WHILEG?NDO
C:=C+1;
INPUT(G,"Guess?","GUESS:","120");
IFG==0THEN
KILL;
END;
IFG<NTHEN
MSGBOX("Higher");
END;
IFG>NTHEN
MSGBOX("Lower");
END;
END;
MSGBOX("Correct!Score:"+C);
END;
Try it and of course, you can adjust the higher limit. Here is some thing for you to try with TARGET:
1. Add a limited amount of guesses.
2. Can you display the list of guesses?
REPEAT
ULAM Algorithm: take an integer n. If n is even, divide it by 2. If n is odd, multiply it by 3 and add 1.
ULAM counts how many steps it takes to get n to 1.
REPEAT:
EXPORTULAM(N)
BEGIN
LOCALC:=1,L0:={N};
REPEAT
IFFP(N/2)==0THEN
N:=N/2;
ELSE
N:=3*N+1;
END;
C:=C+1;
L0:=CONCAT(L0,{N});
UNTILN==1;
MSGBOX("NO.OFSTEPS="+C);
RETURNL0;
END;
Examples:
ULAM(5) returns:
Message Box: "NO. OF STEPS=6"
List: {5, 16, 8, 4, 2, 1}
ULAM(22) returns:
Message Box: "NO. OF STEPS=16"
List: {22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1}
GETKEY
The next section will introduce a super-important command, GETKEY. We will be working with
GETKEY over the entire series.
The Program KEYNO: The person presses key presses. Which each key press, the code returns to
the terminal screen. The program terminates when the Enter key is pressed.
GETKEY: Returns the key code of last key pressed. The Prime's key map is below. (Picture is from
the HP Prime User's Guide)
Access: Cmds, 6. I/O, 4. GETKEY
EXPORTKEYNO()
BEGIN
LOCALK;
PRINT();
PRINT("Pressanykeytogetitscode.");
PRINT("PressEntertoexit.");
REPEAT
K:=GETKEY;
IFK?0THEN
PRINT(K);
END;
UNTILK==30;
END;
First a tip from Han of the MoHPC Forum, which is found at http://www.hpmuseum.org/cgisys/cgiwrap/hpmuseum/forum.cgi#255084. Thank you Han for allowing me to share this.
Use the IF THEN ELSE structure with INPUT to execute a set of default instructions if the user
presses cancel. INPUT returns a value of 0 if ESC or cancel is pressed, and 1 if a value is entered.
IFINPUT(...)THEN
commandsifvaluesareentered
ELSE
commandsifCancelispressed
END;
Default values can be assigned to values as an optional fifth argument for INPUT.
INPUT(var,"Title","Prompt","Help",defaultvalue)
The type of variable maybe set to other than real numbers. Just remember to store such type before
the INPUT command. For example, if you want var to be a string, store an empty string:
var:="";
Again, major thanks to Han.
CHOOSE and CASE
CHOOSE: Creates a pop up choose box, similar to what you see when you click on a soft menu.
There are two syntaxes for CHOOSE:
Simple Syntax (up to 14 options):
CHOOSE(var, "title string", "item 1", "item 2", ... , "item n");
List syntax (infinite amount of items):
CHOOSE(var, "title string", {"item 1", "item 2"});
Choosing item 1 assigns the value of 1 to var, choosing item 2 assigns the value of 2 to var.
Access: Cmds, 6. I/O, 1. CHOOSE
CASE: Allows for different test cases for one variable. Also includes a default scenario (optional).
CASE
IFtest1THENdoiftrueEND;
IFtest2THENdoiftrueEND;
...
DEFAULTcommandsEND;
Access: Cmds, 2. Branch, 3. CASE
Let's look at two programs to demonstrate both CHOOSE and CASE.
TERMVEL - Terminal Velocity of an Object
EXPORTTERMVEL()
BEGIN
LOCALL0:={9.80665,32.174},
L1:={1.225,.0765},
L2:={.47,1.05,1.15,.04},C,K,M,A,T;
CHOOSE(C,"Units","SI","English");
CHOOSE(K,"TypeofObject","Sphere","Cube",
"Cylinder","TearShaped");
INPUT({M,A},"Object",
{"M=","A="},{"Mass","SurfaceArea"});
T:=?((2*M*L0(C))/(L1(C)*A*L2(K)));
MSGBOX("TerminalVelocity="+T);
RETURNT;
END;
Examples:
Sphere, SI Units, M = .05 kg, A = .0028 m^2
Terminal Velocity: T = 24.6640475387 m/s
Cube, US Units, M = 1.2 lb, A = .3403 ft^2
Terminal Velocity: T = 53.149821209 ft/s
CASE
IFC==1THENA:=?*R^2;END;
IFC==2THEN
INPUT(S,"SmallRadius","r=");
A:=?*(R^2S^2);
END;
IFC==3
INPUT(,"Angle","=");
\\Assumeyouareinthecorrectanglemode
IFHAngle==1THEN
\\TestAngleMode
:=*?/180;
END;
A:=*R^2/2;
END;
END;
MSGBOX("Areais"+A);
RETURNA;
END;
Examples
R = 2.5, r = 1.5, = /4 radians or 45
Circle: 19.6349540849
Ring: 12.5663706144
Sector: 2.45436926062
# is a digit 0-9.
Defining equations this way leaves them uncheck. If you want them plotted or accessed in Num
View, you will need to check them.
Example:
F1:="2*X^3" stores the function f(x) = 2*x^3 in Function 1.
R5:="A*SIN()" stores the polar function r() = A*sin() in Polar Function 5, with A being what value
stored in it.
STARTAPP
STARTAPP(application name in quotes);
Starts the named App. The calculator points the screen to the default view (Plot, Symb, Num).
Access: Cmds, 4. App Functions, 2. STARTAPP
STARTVIEW
Instructs the HP Prime to go to a certain view. It has two arguments, the view number and a redraw
number.
Common view numbers include (not all inclusive):
-2 = Modes screen
-1 = Home
0 = Symbolic (Symb)
1 = Plot
2 = Numeric (Num)
3 = Symbolic Setup
4 = Plot Setup
5 = Numeric Setup
6 = App Information
7 = The Views Key
8 = first special view
9 = second special view
Etc..
The redraw number is either 0 or non-zero. 0 does not redraw the screen, anything else does. I
recommend the latter.
Syntax: STARTVIEW(view number, redraw number)
Access: Cmds, 4. App Functions, 3. STARTVIEW
RGB
Returns an integer code pertaining to a color's RGB code. This is super useful for drawing and text
writing.
Syntax: RGB(red, green, blue, alpha)
Red: Intensity of Red, 0-255
Green: Intensity of Green, 0-255
Blue: Intensity of Blue, 0-255
Alpha: (optional) Opacity (up to 128).
RGB codes:
Blue: RGB(0,0,255)
Violet: RGB(143,255,0)
Dark Green: RGB(0,128,0)
Orange: RGB(255,127,0)
Yellow: RGB(0,255,255)
Red: RGB(255,0,0)
White: RGB(255,255,255)
Black: RGB(0,0,0)
Gray: RGB(129,128,128)
Brown: RGB(150,75,0)
Light Blue: RGB(173,216,330)
For other colors, RGB can be found on various sites on the Internet, including Wikipedia.
Access: Cmds, 2. Drawing, 5. RGB
This is a lot, but this is doable. Let's see all these commands and tips in action and create some
magic.
HAngle:=1;
CHOOSE(M,"Units","SI","US");
IFM==1THEN
str:="m";
G:=9.80665;
ELSE
str:="ft";
G:=32.17404;
END;
INPUT({V,},"Data",
{"V:",":"},
{"InitialVelocityin"+str+"/s",
"InitialAngleinDegrees"});
X1:="V*COS()*T";
Y1:="V*SIN()*T.5*G*T^2";
STARTAPP("Parametric");
CHECK(1);
//AdjustWindow
Xmin:=0
//Range
Xmax:=V^2/G*SIN(2*);
Ymin:=0
//Height
Ymax:=(V^2*SIN()^2)/(2*G);
MSGBOX("Range:"+Xmax+""+str+","
+",Height:"+Ymax+""+str);
//PlotView
STARTVIEW(1,1);
END;
Below are screen shots from an example with V = 35.25 m/s and = 48.7.
This session will show how routines work in HPPL. Generally, subroutines have be
declared before the main program. Declaration is important. The details of the subroutines
are after the main program.
Definitely take a look at the example programs to get a better understanding.
SUB Routines for HP Prime
General Syntax:
sub();//declaresubroutines
EXPORTmain()
BEGIN
commandsgohere,includingsub()
END;
sub()
BEGIN
commandsgohere
END;
SUBEXAM
This is just a demonstration of how sub routines work. This program calculates one of two values:
If A is positive, then the program evaluates A. If not, the program values B instead. Where:
A = 2(x-y)/ + xy
B = ^2
and = 2e^(x+y) - e^(x-y) - e^(y-x)
We will use as the subroutine.
SUB1();
EXPORTSUBEXAM(X,Y)
BEGIN
LOCALA,B;
A:=(2*(YX))/SUB1(X,Y)+X*Y;
B:=(SUB1(X,Y))^2;
IFA>BTHEN
RETURNA;
ELSE
RETURNB;
END;
END;
SUB1(X,Y)
BEGIN
RETURN2*e^(X+Y)e^(XY)e^(YX);
END;
Examples:
SUBEXAM(-4, 1) returns 21998.918189
SUBEXAM(2,3) returns 86283.2797974
SUBEXAM(-5,-6) returns 30.648061288
SUBEXAM(2,-3) returns 21810.6046664
Days Between Dates
DDAYS Using Subroutines for HP Prime: Best for 1901 to 2099
* Remember century years not divisible by 400 are NOT leap years. This program does not take
this into account. If any such years are passed, subtract one day for such year manually.
Source: HP 12C Manual - Hewlett Packard
//DeclareSubroutines
SUB1();
SUB2();
SUB3();
//Mainprogram
EXPORTDDAYS(m1,d1,y1,m2,d2,y2)
BEGIN
//DYSHP12C
LOCALx1,x2,z1,z2;
x1:=SUB1(m1);x2:=SUB1(m2);
z1:=SUB2(m1,y1);z2:=SUB2(m2,y2);
RETURNSUB3(y2,m2,d2,z2,x2)
SUB3(y1,m1,d1,z1,x1);
END;
SUB1(X)
BEGIN
IFX?2THEN
RETURN0;
ELSE
RETURNIP(.4*X+2.3);
END;
END;
SUB2(X,Y)
BEGIN
IFX?2THEN
RETURNY1;
ELSE
RETURNY;
END;
END;
SUB3(Y,M,D,Z,X)
BEGIN
RETURN365*Y+31*(M1)+D+IP(Z/4)X;
END;
TEXTOUT(text,x,y)
TEXTOUT_P(text,x,y)
Colored text at a set font size:
TEXTOUT(text,x,y,sizecode,color)
TEXTOUT_P(text,x,y,sizecode,color)
With all this, we finally get to some programming. Since it is December, and snowing in a lot of the
northern side of Earth, let's use TEXTOUT_P to draw snowflakes. I am going to use symbolize the
snowflake by the asterisk, the symbol of multiplication in programming. [ ] types *.
SNOWFLAKE
SNOWFLAKE takes one argument, which is the number of snowflakes to be drawn.
Note: Take note the order of the commands. The order regarding where to draw and generate
random numbers is important to get the results you want.
Program:
EXPORTSNOWFLAKE(N)
BEGIN
LOCALX,Y,Z,I,L0;
L0:={RGB(0,0,255),RGB(178,255,255),
RGB(30,144,255),RGB(0,255,255)};
\\blue,lightblue,dodgerblue,cyan
RECT();
FORIFROM1TONDO
X:=RANDINT(0,304);\\savesomeroomsincetexttakespixels
Y:=RANDINT(0,208);
Z:=RANDINT(1,4);
Z:=L0(Z);
TEXTOUT_P("*",X,Y,2,Z);
END;
FREEZE;
END;