2018 HP Prime Programming Tutorial
2018 HP Prime Programming Tutorial
Edward Shore
All original content copyright, © 2013, 2018. Edward Shore. Unauthorized use and/or
unauthorized distribution for commercial purposes without express and written permission from
the author is strictly prohibited. This tutorial may be distributed for noncommercial purposes,
provided that full credit is given to the author. This document is provided “as-is”. Please contact
the author at ews31415@gmail.com if you have questions.
Calculator screen shots are generated with the HP Prime Virtual Calculator, © 2018 HP
Development Company, L.P. The author is not an employee of Hewlett Packard.
0
HP Prime Programming Tutorial
Table of Contents
Introduction ................................................................................................................................ 4
Tutorial #1: Help Key, LOCAL, RETURN ................................................................................... 5
The Help Key.......................................................................................................................... 5
How To Start Writing a HP Prime Program ............................................................................. 5
Structure of an HP Prime Program ......................................................................................... 5
The RETURN Command ........................................................................................................ 6
The Program SQIN ............................................................................................................. 6
Checking Programs ................................................................................................................ 6
Running Programs.................................................................................................................. 6
Storing Values to Variables .................................................................................................... 7
The LOCAL Command ........................................................................................................... 7
The Program MOPMT ......................................................................................................... 8
Tutorial #2: MSGBOX, IF-THEN-ELSE, PRINT, when, FOR ...................................................... 9
The Command MSGBOX ....................................................................................................... 9
Program Structure .................................................................................................................. 9
The PRINT ............................................................................................................................10
The when Function ................................................................................................................11
The Program DOESTAX ....................................................................................................11
The Basic FOR Loop .............................................................................................................11
The Program DISPCUBES ................................................................................................11
The Program SUMDIV .......................................................................................................12
The FOR Loop with STEP .....................................................................................................13
The Program PRINTEVENS ..............................................................................................13
Tutorial #3: WHILE, INPUT, KILL, REPEAT, GETKEY..............................................................15
The WHILE Structure ............................................................................................................15
The INPUT Command (Basic) ...............................................................................................15
The KILL................................................................................................................................15
The Program TARGET.......................................................................................................16
INPUT with a List of Choices .................................................................................................16
The Program EARTHCOORD ............................................................................................16
INPUT with Checkboxes ........................................................................................................17
The Program DOESTAX2 ..................................................................................................17
1
The REPEAT Structure .........................................................................................................19
The Program ULAM ...........................................................................................................19
The GETKEY Command .......................................................................................................20
The Program KEYNO.........................................................................................................20
The Program MOVEM........................................................................................................21
Tutorial #4: CHOOSE and CASE ..............................................................................................22
The CHOOSE Command ......................................................................................................22
The Program TERMVEL ....................................................................................................22
The CASE Structure ..............................................................................................................23
The Program AREAC .........................................................................................................23
Tutorial #5: STARTAPP, STARTVIEW, CHECK, UNCHECK, RGB, HAngle .............................25
System Equation Variables....................................................................................................25
Defining Equations from Home and Inside Programs ............................................................25
The STARTAPP Command ...................................................................................................25
The CHECK and UNCHECK Commands ..............................................................................26
The STARTVIEW Command .................................................................................................26
Designating Colors with RGB and Hex Codes .......................................................................27
The Color of a Graph .............................................................................................................28
The System Variable HAngle.................................................................................................28
The Program CONIC .........................................................................................................28
The Program PROJ13........................................................................................................30
Tutorial #6: Subroutines ............................................................................................................32
How Subroutines Work ..........................................................................................................32
The Program SUBEXAM....................................................................................................32
Tutorial #7: Drawing Graphics, FREEZE, WAIT, TEXTOUT ......................................................34
The Graphics Screen: Cartesian vs Pixel .............................................................................34
The Drawing Commands .......................................................................................................36
Clearing the GROB screen ....................................................................................................36
Displaying the Graphics Screen with FREEZE ......................................................................37
The Commands TEXTOUT and TEXTOUT_P .......................................................................37
The Program SNOWFLAKE ...............................................................................................38
Tutorial #8: LINE, FILLPOLY, ARC ..........................................................................................40
The LINE Command ..............................................................................................................40
The Program DRAWHOUSE..............................................................................................40
Drawing Polygons with the FILLPOLY Command ..................................................................41
The Program PENT ...........................................................................................................41
2
The ARC Command ..............................................................................................................42
Drawing Circles with ARC......................................................................................................42
Drawing Ellipses with ARC ....................................................................................................42
Drawing Partial Arcs with ARC ..............................................................................................43
The Program DRAWARCS ................................................................................................43
Tutorial #9: Numerical Calculus with the Template Key.............................................................45
Numerical Derivatives ............................................................................................................45
Definite Integrals ...................................................................................................................45
Double Definite Integrals .......................................................................................................45
Summation ............................................................................................................................45
Substitution ...........................................................................................................................45
The Program CALCDEMO .................................................................................................46
Tutorial #10: Using App Functions ...........................................................................................47
Function App Functions .........................................................................................................47
Solve App Functions..............................................................................................................48
Statistics 2Var Functions (2 Variable Statistics) .....................................................................48
Finance App Functions ..........................................................................................................49
Tutorial #11: DRAWMENU and MOUSE ...................................................................................51
The DRAWMENU Command ................................................................................................51
The MOUSE Command .........................................................................................................51
Using a Soft Menu until an Exit Condition is Reached ...........................................................52
The Program BLOTCH.......................................................................................................52
The Program TALLY ..........................................................................................................54
Tutorial #12: Introduction to Creating Custom Apps .................................................................57
Creating the App ...................................................................................................................57
How to Access the App’s Program: Where the Magic Happens .............................................58
The App’s Program................................................................................................................58
The Custom App TrigPlot ...................................................................................................59
HP Prime Program: TrigPlot (in app TrigPlot) ....................................................................61
Index .........................................................................................................................................66
3
Introduction
This is an in-depth tutorial of the HP Prime HP PPL, which is the primary programming
language for the HP Prime. In late 2013, I posted a series of tutorials on my blog, Eddie’s Math
and Calculator Blog, https://edspi31415.blogspot.com/, which covered many basic programming
topics.
Most of the text will be coming from these blog entries, with some additional information added
to this document.
I hope you enjoy this tutorial and allows you to get a firm foundation of the programming
language of the HP Prime.
For this tutorial, the current firmware, 13441 (2/12/2018) will be used.
Key Conventions:
Happy Programming,
Eddie Shore
4
Tutorial #1: Help Key, LOCAL, RETURN
Let’s get started! By the end of this tutorial session, you will be making programs and learning
how to run them.
The Help screen will give you the syntax for most commands and functions, plus give an
explanation how the command or function works. I use the Help facility on the HP Prime all the
time. Definitely, learn and get familiar with the [Help] key.
2. You will see a list of all the programs that have already been entered in memory. To start a
new program, press the soft ( New ) key.
3. Enter the name of the program. To enter a letter, press the [ALPHA] key and corresponding
letter that goes with the key. Pressing the [ALPHA] key twice will turn on UPPERCASE ΑLPHA-
LOCK. If you want to type lower case letters, press [ALPHA], [Shift], [ALPHA] to turn on
lowercase alpha-lock. To exit any lock, press the ALPHA key one more time. When happy with
the name, press [Enter].
1. The only characters allowed in a program name are: letters, Greek letters, numbers, and the
underscore character (_).
2. The program name must start with a letter. For example: TEST123 is a valid name,
TEST_123 is also a valid name, but neither 123TEST or 123_TEST are not valid program
names.
EXPORT program_name(arguments)
BEGIN
commands and comments go here
END;
Each line containing a command generally must end with a semicolon (;). A semicolon can by
5
type by pressing [ALPHA], [ + ].
Comments are statements included in the program to give the user and the programmer useful
notes and reminders while looking over the program. Comments can also divide and name
sections. To type a comment, you will need two forward slashes ( / / ), which can be generated
by pressing the divide key [ ÷ ]. Anything in the line following the two slashes is ignored in
running the program.
Now let’s look at our first program, SQIN. This program will first square a number, then take the
reciprocal of it.
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.
All the program code in this tutorial series will be shown in Courier font.
EXPORT SQIN(X)
BEGIN
RETURN 1/X^2;
END;
Checking Programs
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.
Caution: checking programs does not check whether the arguments used by the commands are
valid. However, it is still a good way to check your progress.
Running Programs
Home Mode - Textbook Entry,
Home Mode - Algebraic Entry,
CAS Mode:
6
Type the program name. Follow the name with parentheses and enclose the required
arguments.
Or use the Toolbox (top row of white keys, 2nd key from the left, it looks like a tool box, in this
tutorial I will type the key as [Toolbox]), select the User touch key, select the program, and input
the required arguments.
Enter each argument, separate each entry by pressing the Enter key. Type the name, and in the
parenthesis state the number of arguments.
For example, if the program TEST has four arguments, the RPN stack would like this:
4: argument_1
3: argument_2
2: argument_3
1: argument_4
TEST(4) to run the program.
4 > A
The other is to use the equals then colon method ( ≔ ), like so:
A≔4
The programs listed in this tutorial will use the latter method.
There are two methods of declaring local variables: using variables as pass-through
arguments, or using the LOCAL command. Variables using the LOCAL command can be any
type: real numbers, complex numbers, strings, lists, matrices, integers, etc.
Tip: When variables are declared using LOCAL, the default value given to these variables is 0.
7
The other type of variable are global variables, which can be defined inside or outside a
program and retain their value. Global variables include system variables, and some global
variables have restrictions.
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).
EXPORT MOPMT(L,R,M)
BEGIN
LOCAL K:=R/1200;
K:=L*K/(1-(1+K)^-M);
RETURN "Payment ="+K;
END;
Since L, R, and M are pass-through arguments, they are automatically local variables. K is
declared a local variable. When MOPMT finishes, nothing globally is stored to L, R, M, or K.
Tip: Use RETURN, TEXTOUT_P, and PRINT to return custom strings, which combine results,
messages, and calculations. Strings are connected with a plus sign.
Examples:
MOPMT(4000, 9.5, 30) returns 150.317437565
MOPMT(370000, 3.5, 360) returns 1661.46534383
8
Tutorial #2: MSGBOX, IF-THEN-ELSE, PRINT, when, FOR
The Command MSGBOX
MSGBOX takes a string a makes a pop-up message box. Program execution stops until you
press a key to acknowledge the message. The pop-up message is a singular string.
Imagine that you are in charge of setting the combinations for the good, old-school combination
locks. This program gives three digit combinations of integers 0 through 39, and uses MSGBOX
to return the combination.
EXPORT COMLOCK()
BEGIN
LOCAL L0;
L0:=RANDINT(3,0,39);
MSGBOX("SECRET: "+L0(1)+","
+L0(2)+","+L0(3));
END;
Featured command: 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.
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 the testing symbols <, ≤, ==, ≠, ≥, and >; along with AND, OR, by pressing [Shift], [ 6 ].
Note that the double equals sign is needed to check equality.
Comparison tests result in either 1 for true, or 0 for false. AND, along with OR, can be used to
combine to conditions. For example, if you want to test whether X is within the range of 1000
and 1999 inclusive, use the testing condition (X ≤ 1000) AND (X ≤ 1999).
9
The PRINT Command
The PRINT command prints a sting, result, or a combination of both on to the Prime's Terminal
screen. If PRINT is used, the program will end on the terminal (text output) screen. Press any
button to exit.
To clear the terminal screen, insert a blank print command: PRINT(). I usually use this at the
beginning of any program when I plan to use the PRINT is going to be used later in the
program.
You can access the terminal screen at any time by pressing and holding the [ ON ], then press
[ ÷ ].
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.
EXPORT QROOTS(A,B,C)
BEGIN
LOCAL D;
PRINT();
HComplex:=1;
D:=B^2-4*A*C;
IF D≥0 THEN
PRINT("Roots are real.");
ELSE
PRINT("Roots are complex.");
END;
PRINT((-B+√D)/(2*A));
PRINT((-B-√D)/(2*A));
END;
Examples:
QROOTS(1,5,8) returns:
QROOTS(2,-4,-8) returns:
10
The when Function
The when function is a short version of an IF-THEN-ELSE structure. Be aware the when
command requires lower case spelling. The command is treated as a function. Access the
when function in the general catalog.
Syntax:
The DOESTAX program tests whether sales tax applies to an item given its price. Assume that
there is an 8.5% sales tax when the item’s price exceeds $10.00, otherwise no sales tax
applies.
EXPORT DOESTAX(N)
BEGIN
N≔when(N>10,N*1.085,N);
RETURN N;
END;
Examples:
DOESTAX(8) returns 8
DOESTAX(12) returns 13.02
All the commands in the loop will be executed a set number of times. Each time a loop finishes,
the value of the variable increases by one. The loop terminates when variable=end.
The program DISCUBES prints out all the cubes (x^3) for integers 1 to N.
EXPORT DISPCUBES(N)
BEGIN
LOCAL I;
// clear terminal
PRINT();
11
// basic FOR loop
FOR I FROM 1 TO N DO
PRINT(I^3);
END;
END;
1
8
27
64
125
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.
EXPORT SUMDIV(N)
BEGIN
LOCAL S:=0,K,mdiv,ldiv;
mdiv:=CAS.idivis(N);
ldiv:=DIM(mdiv);
FOR K FROM 1 TO ldiv(1) DO
S:=S+mdiv(K);
END;
RETURN S;
END;
Examples:
SUMDIV(12) returns 28.
SUMDIV(24) returns 60.
SUMDIV(85) returns 108.
DIM: returns the dimensions of a sequence, string, or matrix. The DIM command does not cover
lists. To find the dimension of a list, used SIZE instead.
12
Access: (Cmds), 1. Strings, 9. DIM
All the commands in the loop will be executed a set number of times. Each time a loop finishes,
the variable increases by one. The loop terminates when variable ≥ end.
If you want any FOR loops with decrements, use the FOR DOWN(TO) and FOR DOWN(TO)
STEP structures.
The program PRINTEVENS will print all even integers between A and B. A and B can have
non-integer input. In this program, a FOR loop with increment 2 (STEP 2) is used.
EXPORT PRINTEVENS(A,B)
BEGIN
// Print all even numbers between
// A and B
LOCAL I;
// Clear terminal screen
PRINT();
// Check if A is even
// Take A to the next integer
A:=CEILING(A);
// Test to see if A is even
A:=when(FP(A/2)==0,A,A+1);
// For loop with step increment 2
FOR I FROM A TO B STEP 2 DO
PRINT(I);
END;
END;
Example:
PRINTEVENS(3,10)
Result:
4
6
13
8
10
14
Tutorial #3: WHILE, INPUT, KILL, REPEAT, GETKEY
Caution: Watch your ENDs! Make sure an END is with each loop and the program itself. Press
the soft key Check to check your work.
INPUT: Creates an input screen for variables. On the HP Prime, the input can asked for more
than one input. TARGET demonstrates INPUT with one prompt.
One Variable:
Multi-Variable:
Note: Everything after the variable is optional. However, the order of arguments must be
maintained. For example, if you want a list of initial values but no reset values, leave a blank list
{ } for reset values.
Note: Pressing Cancel will store a 0 in variable. You may include code of what to do if the user
presses Cancel, but it is not required.
15
The Program TARGET
HP Prime Program: TARGET. TARGET is a game where you provide a guess to get a desired
number. If you miss, the calculator will tell you if number is higher and lower. At the end of the
game, the calculator gives you how may picks you needed to get the target number.
EXPORT TARGET()
BEGIN
LOCAL C:=0, N:=RANDINT(1,20), G:=-1;
WHILE G≠N DO
C:=C+1;
INPUT(G,"Guess?","GUESS:","1 - 20");
// Guess of 0 terminates program
IF G==0 THEN
KILL;
END;
// Guess is lower than N
IF G < N THEN
MSGBOX("Higher");
END;
// Guess is higher than N
IF G > N THEN
MSGBOX("Lower");
END;
END;
// Display player’s score
MSGBOX("Correct! Score: "+C);
END;
One Variable:
INPUT({{variable, list of choices}}, "title", "label", "help text",
reset value, initial value)
Note that you will need two sets of list brackets! Also keep in mind, everything after the variable
is optional.
The program EARTHCOORD gives the user a choice of four cities. Once that is selected, you
get the approximate latitude and longitude.
EXPORT EARTHCOORD()
BEGIN
16
// Localize variables
LOCAL L1,L2,L3,I;
// Store latitdues
L1:={34.2166666667,41.9,-33.8599722222,
35.6895055556};
// Store Longitudes
L2:={-118.25,12.5,151.211111111,
139.708366667};
// Input
INPUT({{I,L3}},"Lat/Long","City:");
// Display coordinates
RETURN {→HMS(L1(I)),→HMS(L2(I))};
END;
One Variable:
INPUT({{variable, 1}}, "title", "label", "help text", reset value,
initial value)
Note that you will need two sets of list brackets! Also keep in mind, everything after the variable
is optional.
Remember DOESTAX in Tutorial 2? In this version, DOESTAX2 will analyze up to three items
and ask for the sales tax rate. The checkboxes below will indicate whether the tax applies.
EXPORT DOESTAX2()
BEGIN
// Localize variables
LOCAL item1, item2, item3;
LOCAL ck1, ck2, ck3;
LOCAL rate,total;
// Input Command
INPUT({item1,{ck1,1},item2,{ck2,1},
17
item3,{ck3,1},rate},
"Check Out",
{"Item1:","Tax1:","Item2:","Tax2:",
"Item3:","Tax3:","Rate:"});
// Calculation
rate:=rate/100;
total:=item1*(1+ck1*rate)
+item2*(1+ck2*rate)
+item3*(1+ck3*rate);
// Display total
RETURN total;
END;
Example: Analyze the total of three items: $59.99 subject to sales tax, $9.99 subject to sales
tax, and $10.00 not subject to sales tax. The sales tax rate is 9%. Turn the first two
checkboxes on while leave the last check box unchecked.
18
Result: $86.28
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
commands
UNTIL condition;
The ULAM algorithm takes an integer n and tests whether n is divisible by 2 (even). 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.
EXPORT ULAM(N)
BEGIN
LOCAL C:=1, L0:={N};
REPEAT
IF FP(N/2)==0 THEN
N:=N/2;
ELSE
N:=3*N+1;
END;
C:=C+1;
L0:=CONCAT(L0,{N});
UNTIL N==1;
MSGBOX("NO. OF STEPS="+C);
RETURN L0;
END;
Examples:
ULAM(5) returns:
Message Box: "NO. OF STEPS=6"
List: {5, 16, 8, 4, 2, 1}
19
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}
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.
EXPORT KEYNO()
BEGIN
LOCAL K;
PRINT();
PRINT("Press any key to get its code.");
PRINT("Press Enter to exit.");
REPEAT
K:=GETKEY;
IF K ≥ 0 THEN
PRINT(K);
END;
UNTIL K==30;
20
END;
This program allows the user to move the character “M” using the arrow keys. Exit the program
by pressing the plus button [+].
EXPORT MOVEM()
BEGIN
END;
21
Tutorial #4: CHOOSE and CASE
Choosing item 1 assigns the value of 1 to var, choosing item 2 assigns the value of 2 to var, and
so on.
The Program TERVEL calculates the terminal velocity of an object given its shape and the units
to be used (kilograms/meters/seconds or pounds/feet/seconds). Lists are created to store the
necessary data.
EXPORT TERMVEL()
BEGIN
LOCAL L0:={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,"Type of Object","Sphere","Cube",
"Cylinder","Tear-Shaped");
INPUT({M,A},"Object",
{"M=","A="},{"Mass","Surface Area"});
T:=√((2*M*L0(C))/(L1(C)*A*L2(K)));
MSGBOX("Terminal Velocity="+T);
RETURN T;
END;
Examples:
22
Cube, US Units, M = 1.2 lb, A = .3403 ft^2
Terminal Velocity: T = 53.149821209 ft/s
CASE
IF test 1 THEN do if true END;
IF test 2 THEN do if true END;
...
DEFAULT commands END;
The program AREAC (Area of Circles, Rings, and Sectors) demonstrates the use of a CASE
structure.
EXPORT AREAC()
BEGIN
LOCAL C,R,S,θ,A;
CHOOSE(C,"Areas","1. Circle","2. Ring","3. Sector");
IF C==2 THEN
INPUT(S,"Small Radius","r=");
A:=π*(R^2-S^2);
END;
IF C==3 THEN
INPUT(θ, "Angle", "θ=");
// Assume you are in the correct angle mode
IF HAngle==1 THEN
// Test Angle Mode
θ:=θ*π/180;
END;
A:=θ*R^2/2;
END;
END;
MSGBOX("Area is "+A);
23
RETURN A;
END;
Examples:
Circle: 19.6349540849
Ring: 12.5663706144
Sector: 2.45436926062
24
Tutorial #5: STARTAPP, STARTVIEW, CHECK, UNCHECK,
RGB, HAngle
We can use the HP Prime’s PPL to work with different Applications and use their functions. In
this tutorial, we will work with switching the HP Prime to different apps.
For example F1 refers to Function F1(X), V2 refers to open statement V2(X,Y), and so on.
Solve equations are used with the Solve.SOLVE function.
Examples:
R5:="A*SIN(θ)" stores the polar function r(θ) = A*sin(θ) in Polar Function 5, with A being what
value stored in it.
Starts the named App. The calculator points the screen to the default view (Plot, Symb, Num).
25
The CHECK and UNCHECK Commands
Checks and unchecks specific equation or function (0-9) in the current app. For example, if you
are in the Function app, CHECK(1) activates F1. As you should expect, UNCHECK(1) turns F1
off.
Please note that CHECK and UNCHECK are App Specific functions. App specific functions are
functions that belong to a specific app. Unless you are working the current app, CHECK and
UNCHECK will proceed the syntax:
Appname.CHECK(n)
Appname.UNCHECK(n)
It is always safer to use the CHECK and UNCHECK commands with the Appname. (include the
period) prefix.
Access: [Toolbox], (App), select your app (CHECK and UNCHECK, if available, are in various
places in the menu)
Examples:
26
Etc..
The redraw number is either 0 or non-zero. 0 does not redraw the screen, anything else does.
The redraw number is optional.
You can also designate colors by hexadecimal code using the format #RRGGBBh. RR is for red
(00 – FF), green (00 – FF), and blue (00 – FF). The # prefix and h suffix tells the HP Prime that
this is a hexadecimal integer.
Red: #FF0000h
Green: #00FF00h
Blue: #0000FFh
Here is a list of colors with a hex conversion table. White, silver, black, red, magenta, violet,
blue, lime green, cyan, teal, gray, maroon, and yellow are exact values. Others are
approximate values.
27
The Color of a Graph
Check the color of a graph by using the syntax:
F#(COLOR)**
This returns a hexadecimal value for the color. This applies to any of the equation variables F#,
R#, (X# and Y# will have the same value), U#, V#, and E#. There is a list of two colors for FZ#
(3D Graphing).
F#(COLOR):=RGB(red,blue,green,[alpha]) **
F#(COLOR)≔#RRGGBBh **
Example:
The value of HAngle can be recalled and values can be stored in HAngle.
You can choose the color how the conic section is plotted, from red, blue, orange, and green.
(Game show enthusiasts, I hope you note the order of the colors I listed... ;) ).
EXPORT CONIC()
BEGIN
// Initialize varaibles
LOCAL cr, cg, cb, I;
28
INPUT({A,B,C,D,E,F},
"Ax^2+By^2+Cxy+Dx+Ey+F", { },
{0,0,0,0,0,0},{0,0,0,0,0,0});
// Colors
CHOOSE(I, "Choose a Color",
"Red","Blue","Orange","Green");
// Red values list
cr:={255,0,255,0};
// Green values list
cg:={0,0,127,255};
// Blue values list
cb:={0,255,0,0};
// Plot View
STARTVIEW(1,1);
END;
An example:
29
The Program PROJ13
The program PROJ13 calculates range and height of a projectile, and plots its path. The
program sets the mode into Degrees (HAngle=1) and the calculator to the Parametric app.
Equations:
x = V * cos θ * t
y = V * sin θ * t - .5 * g * t^2
Where:
V = initial velocity
θ = initial degree of flight
g = Earth gravitation constant (9.80665 m/s^2, ≈32.17404 ft/s^2)
Air resistance is not factored, so we are dealing with ideal conditions. How much the projectile
represents reality varies, where factors include the object being projected, the temperate and
pressure of the air, and the weather.
EXPORT PROJ13()
BEGIN
30
LOCAL M, str;
// V, G, θ are global
// Degrees
HAngle:=1;
X1:="V*COS(θ)*T";
Y1:="V*SIN(θ)*T-.5*G*T^2";
STARTAPP("Parametric");
CHECK(1);
// Adjust Window
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);
// Plot View
STARTVIEW(1,1);
END;
31
Tutorial #6: Subroutines
General Syntax:
EXPORT main()
BEGIN
commands go here, including sub()
END;
sub()
BEGIN
commands go here
END;
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)/Φ + x*y
B = Φ^2
SUB1();
EXPORT SUBEXAM(X,Y)
BEGIN
LOCAL A, B;
A:=(2*(Y-X))/SUB1(X,Y)+X*Y;
B:=(SUB1(X,Y))^2;
IF A>B THEN
RETURN A;
ELSE
32
RETURN B;
END;
END;
SUB1(X,Y)
BEGIN
RETURN 2*e^(X+Y)-e^(X-Y)-e^(Y-X);
END;
Examples:
33
Tutorial #7: Drawing Graphics, FREEZE, WAIT, TEXTOUT
The Graphics Screen: Cartesian vs Pixel
OK this section we will start covering some of the graphics features of the HP Prime
Programming Language. We touched on graphics a bit when we used STARTAPP and
STARTVIEW to call up the Plot screen of certain apps (Function, Parametric, Polar, Sequence,
Advanced Graphing, Graph 3D).
This time we are going to use drawing commands that can be used in any HP Prime app. In a
sense we are creating a graphic object (GROB). The HP Prime allows for ten graphic objects,
named G0 - G9. For this tutorial series, (unless specified) I am always going to use the default
GROB, G0. This makes typing commands much easier.
Each graphic object operates in either one of two coordinate systems: Cartesian and pixel.
1. The end points depend on the Plot variables Xmin, Xmax, Ymin, and Ymax.
2. The system is familiar, having x increasing as we move to the right and y increasing as we
move up.
3. The trade is that some (very few) drawing commands don't accommodate the Cartesian
system. An example is the ARC command, which requires the radius to be in pixels.
34
The Pixel System (x,y):
1. The boundaries are fixed. The pixel (0,0) is the top left hand corner, the pixel (319, 239) is
the lower right hand corner.
35
Note that the y pixels from 219 to 239 are allocated for the soft touch menu.
LINE draws a line using Cartesian coordinates, while LINE_P draws a line using Pixel
coordinates.
To clear the GROB screen, we will simply type RECT(). The wipes the screen, leaving it white.
It is necessary to do this at least at the beginning of each program containing drawing
commands. In a sense, RECT() is similar to PRINT().
36
Displaying the Graphics Screen with FREEZE and WAIT
It is not enough to type the drawing commands. We need a command to tell the HP Prime to
show the graphics. Two ways to do it are:
FREEZE: This does exactly what it says, freezes the screen. To exit, tap the screen or press
ESC. Pressing Enter will re-execute the program.
WAIT(0): This freezes the screen for an indefinite amount of time. However, pressing any button
will cause the program to continue. Of course, if the last END is followed by WAIT(0), the
program terminates.
If you want the calculator to pause for a certain amount of time, the WAIT command is also
used. Use WAIT(n) to make the calculator wait n seconds before executing the next step. This
is useful if you are working an amination.
Cartesian:
TEXTOUT(text, GROB*, x, y, font size*, text color*, width*, background
color*)
Pixel:
TEXTOUT_P(text, GROB*, x, y, font size*, text color*, width*,
background color*)
text: The text to be written. It can be a string, results, calculations, or any combination.
x: x coordinate
37
y: y coordinate
font size*: The text font's size code. Must be used if you want text to be a color other than black.
Optional. Default is the current size set by Home Settings.
text color*: The color of the text. Use of the RGB command is advised. Optional. Default color is
black.
width*: Length of the background box of the text. Optional. I usually don't use this argument.
background color*: Color of the background box. Optional. I usually don't use this argument.
Simplified Syntaxes:
With all this, we finally get to some programming. Typically during winter, it snows a lot. 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. The times key [ × ] types the asterisk
character, *.
EXPORT SNOWFLAKE(N)
BEGIN
LOCAL X,Y,Z,I,L0;
L0:={RGB(0,0,255),RGB(178,255,255),
RGB(30,144,255),RGB(0,255,255)};
RECT();
FOR I FROM 1 TO N DO
38
X:=RANDINT(0,304);
// save some room since text takes pixels
Y:=RANDINT(0,208);
Z:=RANDINT(1,4);
Z:=L0(Z);
TEXTOUT_P("*",X,Y,2,Z);
END;
FREEZE;
END;
39
Tutorial #8: LINE, FILLPOLY, ARC
All the example programs shown will use pixel coordinates.
Cartesian:
Pixels:
DRAWHOUSE demonstrates the LINE_P command to draw a house. The base is brown
(#905000h), and the roof is maroon (#800000h).
EXPORT DRAWHOUSE()
BEGIN
END;
40
Drawing Polygons with the FILLPOLY Command
The FILLPOLY command draws a filled polygon. The general syntax is:
Cartesian:
Pixels:
The program DRAWPENT draws a five sided polygon in pink (#FFC0C0h) on an indigo screen
(#400080h).
EXPORT DRAWPENT()
BEGIN
41
// Show the screen
WAIT(0);
END;
42
Draw a filled circle:
Filled arc:
EXPORT DRAWARCS()
BEGIN
END;
43
44
Tutorial #9: Numerical Calculus with the Template Key
We can use the template key, which is located on the top row of gray keys, third key from the
left (from here on in marked as [Template]).
Numerical Derivatives
Definite Integrals
Where X and Y represent the first and second variable, A and B are limits for the first variable,
and C and D are limits for the second variable.
Summation
With this function, the step is assumed to be 1, with both the lower and upper limits being
integers.
Substitution
One variable:
Multiple variables:
45
The Program CALCDEMO
The program CALCDEMO demonstrates the use of the five template functions as discussed in
this section. The terminal is used to print the results and the calculator is set to Radians mode.
EXPORT CALCDEMO()
BEGIN
// Demonstration of Template functions
// Derivatives
PRINT("d/dx sin x at x = π/4");
PRINT(∂(SIN(X),X=π/4));
// Integrals
PRINT("∫(sin x dx) from x=1 to x=3");
PRINT(∫(SIN(X),X,1,3));
// Double Integrals
PRINT("∫(∫(x^2*y dx)dy), x=[1,2], y=[0,4]");
PRINT(∫(∫(X^2*Y,X,1,2),Y,0,4));
// Summation
PRINT("Σ(n^3) from n=1 to n=12");
PRINT(Σ(N^3,N,1,12));
// Substitution
PRINT("Calculate 3*a+5 when a=-2");
PRINT(3*A+5|A=−2);
END;
46
Tutorial #10: Using App Functions
The HP Prime holds a lot of useful app-specific functions, and I am going to highlight some of
them here. Like CHECK and UNCHECK in Tutorial #5, you are always safer to use the
Appname. prefix, which allow you to use the program no matter what app you are currently in.
Access (general): [Toolbox], (App), (choose your app function, as the order of the apps are
shuffled)
Intersection – ISECT
Finds the intersection of two functions, a guess may be provided. I recommend that you provide
a guess.
Root - ROOT
Find the root (zero) of a function that is closest the guess provided. ROOT does not find
complex roots.
Calculates the definite integral (area under the curve) of a function. If two functions are
provided, then the area between curves is calculated.
47
Area between Curves:
SOLVE solves a single equation or uses any of the equations stored under the variables E0 –
E9. A guess is recommended, but not required.
Use SetDepend and SetIndep to set a column as the dependent y variable (C0 – C9), and
independent x variable (C0 – C9) for any of the five stat fit variables (S1 – S5).
Syntax:
Statistics_2Var.SetDepend(Statistics_2Var.S#, Statistics_2Var.C#)
Statistics_2Var.SetIndep(Statistics_2Var.S#, Statistics_2Var.C#)
Statistics_2Var.S#(4):=type number
Sets the stat regression type for stat fits S1 through S5. The regression types are:
1: Linear
2: Logarithmic
3: Exponential
4: Power
5: Exponent
6: Inverse
7: Logistic
8: Quadratic
9: Cubic
10: Quartic
11: Sinusoidal (Trigonometric)
12: Med-Med
48
For example, the following sets Stat Fit 1 to Linear Regression:
Statistics_2Var.S1(4):=1
Syntax: Statistics_2Var.Do2VStats(Statistics_2Var.S#)
For fits S1 – S5
{x-list, y-list, frequency list, fit type number, regression equation, scatter plot color, mark type, fit
plot color}
Predictive Values
The first active fit is used with the prediction function, hence S1 takes priority over S2, S3, S4,
and S5, respectively.
The following functions calculate various elements using Time Value of Money. Remember that
the cash flow convention is used, positive for inflows, negative for outflows.
Syntax – Payment:
Finance.TvmPMT(N, I/YR, PV, FV, P/YR, C/YR, BEG)
Variables:
N = number of payments
I/YR = annual interest rate
49
PV = present value
PMT = periodic payment
FV = future value
P/YR = payments per year
C/YR = compound periods per year, optional, default P/YR = C/YR
BEG = 1 for beginning of period payments, 0 for end of period payments, optional, default BEG
=0
50
Tutorial #11: DRAWMENU and MOUSE
I find DRAWMENU and MOUSE to be truly advanced commands. For this series, I present the
basic use of these commands.
Syntax:
However, if we want the soft menu to actually work, we are going to need the command
MOUSE.
For the purpose of type, MOUSE has the following type designations:
For this tutorial, we are only going to focus on the MOUSE command as long as pertains to the
DRAWMENU command. The pixels associated with the soft menu are:
51
Using a Soft Menu until an Exit Condition is Reached
One way to use DRAWMENU is keep the menu active until an exit condition is reached. In this
case, the longer you press the soft key, and touch the screen, the more the key repeats. This is
different from the use of GETKEY, which each physical key stroke executes the command once
per key stroke.
The program BLOTCH allows the user to draw a randomized blotches on the screen, with the
menu keys serving as adjustment parameters.
EXPORT BLOTCH()
BEGIN
// EWS 04-20-2014
// Initialize
LOCAL m,m1,mx,my,j,k,r;
WHILE MOUSE(1)≥0 DO END;
// Clear Canvas
RECT;
LOCAL s:=50, d:=4;
// Menu - to be redrawn
DRAWMENU("Clear","S+5","S-5","D+2","D-2","Exit");
DRAWMENU("Clear","S+5","S-5","D+2","D-2","Exit");
// Clear Screen
IF (my≥220 AND my≤319) AND (mx≥0 AND mx≤51) THEN
RECT;
END;
// Change Size
IF (my≥220 AND my≤319) AND (mx≥53 AND mx≤104) THEN
IF s<80 THEN s:=s+5; END;
END;
52
// Change Depth
IF (my≥220 AND my≤319) AND (mx≥159 AND mx≤210) THEN
IF d<8 THEN d:=d+2; END;
END;
// Exit Key
IF (my≥220 AND my≤319) AND (mx≥256 AND mx≤319) THEN
BREAK;
END;
// Draw Blotch
FOR j FROM mx-s/2 TO mx+s/2 STEP d DO
FOR k FROM my-s/2 TO my+s/2 STEP d DO
r:=RANDINT(1677215);
RECT_P(j,k,j+d-1,k+d-1,r);
END; END;
RECT_P(0,220,319,239);
TEXTOUT_P("DONE!",146,220,4,#FF0000h);
WAIT(-1);
END;
If you want to slow down the timing between mouse clicks, a well-placed WAIT command is
useful after the coordinates of the mouse click is determined.
53
The Program TALLY
The program TALLY counts votes for up to five candidates. The first five soft keys allow to tally
votes, when the sixth key exits the loop.
EXPORT TALLY()
BEGIN
// tally list
LOCAL tally:={0,0,0,0,0};
LOCAL total;
// Initialize
// Mouse coordinates
LOCAL m,m1,mx,my;
WHILE MOUSE(1)≥0 DO END;
// Clear Canvas
RECT;
// Menu - to be redrawn
DRAWMENU("Vote1","Vote2","Vote3","Vote4","Vote5","Exit");
54
// vote for candidate 4
IF (my≥220 AND my≤319) AND (mx≥159 AND mx≤210) THEN
tally(4):=tally(4)+1;
END;
// Exit Key
IF (my≥220 AND my≤319) AND (mx≥256 AND mx≤319) THEN
BREAK;
END;
// results
total:=ΣLIST(tally);
TEXTOUT_P("Candidate 1: "+tally(1)+
", "+%TOTAL(total,tally(1))+"%",
0,10,4,#0000FFh); // blue
TEXTOUT_P("Candidate 2: "+tally(2)+
", "+%TOTAL(total,tally(2))+"%",
0,30,4,#FF0000h); // red
TEXTOUT_P("Candidate 3: "+tally(3)+
", "+%TOTAL(total,tally(3))+"%",
0,50,4,#008000h); // office green
TEXTOUT_P("Candidate 4: "+tally(4)+
", "+%TOTAL(total,tally(4))+"%",
0,70,4,#FF8000h); // orange
TEXTOUT_P("Candidate 5: "+tally(5)+
", "+%TOTAL(total,tally(5))+"%",
0,90,4,#000000h); // black
// redraw menu
DRAWMENU("Vote1","Vote2","Vote3",
"Vote4","Vote5","Exit");
RECT_P(0,220,319,239);
TEXTOUT_P("FINAL RESULTS",146,220,4,#000000h);
55
WAIT(0);
END;
56
Tutorial #12: Introduction to Creating Custom Apps
With the new firmware (13441), we now have the ability to create customized apps, fresh from
scratch. This tutorial will show how the process generally works and a sample app.
2. In the Application Library screen, select the soft (Save) key (furthest to the left).
3. On the Base App dropdown box, select None. Its icon is gold with a person in front of a
clipboard.
4. Name your app and press (OK). Your newly created app will be added to the end of the
applications in the Application Library.
57
How to Access the App’s Program: Where the Magic Happens
1. Select the new app by pressing the [Apps] key and selecting it.
2. Press [Shift], [ 1 ] (Program). The programs attached to the app is always at the top of the
program, regardless whether the other programs are sorted chronologically and alphabetically.
58
Info() – the note shown by pressing [Shift] [ Apps ] key sequence, only accepts PRINT
commands to display information
START() – the commands the app executes when the app is started
RESET() – the commands the app executes when the app is reset (through the Apps menu)
VIEW “title”, program() – Each of these are the options presented by pressing the [Views]
key. You can have more than one VIEW structure.
Notes:
1. This is a clean app. Everything must be programmed and all variables must be
created. Global and local rules still apply. That means there is no default plot apps Xmin,
Xmax, Ymin, Ymax, Xtick, Ytick, etc. We must completely program all of the graph screen
should plotting be involved.
2. The following app variables are included. Each value of setting determines the
mode. Unless noted, the value of 0 uses the same setting as home.
AFiles deals with any additional files attached with the app, with AFilesB being the binary
version. Use the DelAFiles to delete associated files.
AProgram and AVars deals with specific programs and variables associated with the
app. DelAVars deletes such variables.
where all angles are in radians. The app uses the global variables A through L.
Keys
[ Num ]: The user enters values for A – L. They must be real (not complex or have a √(-1)
component)
[ Plot ]: Enter plot parameters and choose the color of the plot (purple, blue, green, gold,
red). The plot is against a black background.
59
[ View ], Erase A-L: Sets the variables A through L to 0 (zero).
Notes
Info()
BEGIN
// This is when the user presses
// Shift+Apps (Info), use Print
// commands
PRINT();
PRINT("TrigPlot App");
PRINT("------------");
PRINT("By Edward Shore");
PRINT("------------");
PRINT("This app plots the equation");
PRINT("Y = A*SIN(B*X+C) + D*COS(E*X+F) +");
PRINT("G*SIN(H*X+I)^2 + J*COS(K*X+L)^2");
PRINT("------------");
PRINT("February 2018");
END;
60
To ensure the app always runs in Radians mode, I store the value 1 to AAngle during startup
(START). In addition, I added the Info(); to show the Info screen.
START()
BEGIN
// This happens when the app is started.
END;
//Symb()
//BEGIN
// MSGBOX("Symb");
//END;
Plot()
BEGIN
// runs the Plot routine
// set color scheme
LOCAL col1;
col1:={#BF00FFh,#7DF9FFh,
#00FF00h,#D4AF37h,#FF0000h};
// Radians
HAngle:=0;
// localize variables
LOCAL xm,xn,ym,yn;
LOCAL xs,ys,xp,yp;
LOCAL x,y,ch;
// input screen
INPUT({
xm,xn,ym,yn,
{ch,
{"Purple","Blue","Green",
61
"Gold","Red"}}},
"TrigPlot Setup: Plot",
{"x-min: ","x-max: ",
"y-min: ","y-max: ",
"Color: "});
// drawing
// color choice
LOCAL c1:=col1[ch];
// axis information
LOCAL st1,st2;
st1:="x:["+xm+","+xn+"]";
st2:="y:["+ym+","+yn+"]";
TEXTOUT_P(st1,0,0,2,#C0C0C0h);
TEXTOUT_P(st2,0,20,2,#C0C0C0h);
// function
FOR x FROM xm TO xn STEP xs DO
// function
y:=A*SIN(B*x+C)+D*COS(E*x+F)+
G*SIN(H*x+I)^2+J*COS(K*x+L)^2;
// point→pixel, plot
xp:=(x-xm)/xs;
yp:=(y-yn)/ys;
PIXON_P(xp,yp,c1);
END;
// freeze screen
FREEZE;
END;
Num()
BEGIN
// This is where all the variables are
// entered, in one easy spot. A-L are
// global in this application.
INPUT({A,B,C,D,E,F,G,H,I,J,K,L},
"TrigPlot Variables");
END;
62
//SymbSetup()
//BEGIN
// MSGBOX("SymbSetup");
//END;
//PlotSetup()
//BEGIN
// MSGBOX("PlotSetup");
//END;
//NumSetup()
//BEGIN
// MSGBOX("NumSetup");
//END;
Info()
BEGIN
// This is when the user presses
// Shift+Apps (Info), use Print
// commands
PRINT();
PRINT("TrigPlot App");
PRINT("------------");
PRINT("By Edward Shore");
PRINT("------------");
PRINT("This app plots the equation");
PRINT("Y = A*SIN(B*X+C) + D*COS(E*X+F) +");
PRINT("G*SIN(H*X+I)^2 + J*COS(K*X+L)^2");
PRINT("------------");
PRINT("February 2018");
END;
START()
BEGIN
// This happens when the app is started.
END;
//RESET()
63
//BEGIN
//MSGBOX("RESET");
//END;
Examples
64
65
Index
%TOTAL, 54 PredX, 49
ARC, 42 PredY, 49
AREA, 47 PRINT, 10
Area between Curves, 48 RANDINT, 9
Cartesian, 34 Regression Type, 48
CASE, 23 REPEAT, 19
CHECK, 26 RETURN, 6
CHOOSE, 22 RGB, 27
customized apps, 57 ROOT, 47
Definite Integrals, 45 SetDepend, 48
Designating Colors, 27 SetIndep, 48
DIM, 12 SIZE, 12
Do2VStats, 49 SLOPE, 48
DRAWMENU, 51 SOLVE, 48
FILLPOLY, 41 STARTAPP, 25
FOR, 11 STARTVIEW, 26
FOR Loop with STEP, 13 Storing Values to Variables, 7
FREEZE, 37 Subroutines, 32
GETKEY, 20 Substitution, 45
HAngle, 28 Summation, 45
HComplex, 10 System Equation Variables, 25
Help Key, 5 TEXTOUT, 37
idivis, 12 TEXTOUT_P, 37
IF-THEN-ELSE, 9 Time Value of Money Functions, 49
INPUT, 15, 16, 17 TvmFV, 49
ISECT, 47 TvmIPYR, 49
KILL, 15 TvmNbPmt, 49
LINE, 40 TvmPMT, 49
LOCAL, 7
TvmPV, 49
MOUSE, 51
UNCHECK, 26
MSGBOX, 9
WAIT, 37
Numerical Derivatives, 45
when, 11
Pixel, 34
WHILE, 15
66