HP Prime Programming Tutorial

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33
At a glance
Powered by AI
The key takeaways are that the document discusses HP Prime programming tutorials, including how to write programs, use commands like LOCAL, RETURN, and TEXTOUT_P, and display graphics.

The LOCAL command declares variables to be local to a program, meaning they are created, used, and deleted within the program without affecting variables outside of it.

To draw a snowflake using TEXTOUT_P, the program SNOWFLAKE generates random coordinates, chooses a random color, and uses TEXTOUT_P to display an asterisk character at those coordinates.

HP Prime Programming Tutorial #1: LOCAL, RETURN

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.

Rules for Program Names:


1. Letters, numbers, and the underscore character (_) only.
2. The program name must start with a letter.

Structure of a HP Prime Program


A HPPP program is encased of an EXPORT - BEGIN - END structure. The layout is generally like
this:
EXPORTprogram_name(arguments)
BEGIN
commandsandcommentsgohere
END;
Each line containing a command generally must end with a semicolon (;). A semicolon can by type
by pressing ALPHA then the Plus key ( + ).

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.

How to run the programs:


Home Mode - Textbook Entry,
Home Mode - Algebraic Entry,
CAS Mode:
Type the program name. Follow the name with parenthesis 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), select the
User touch key, select the program, and input the required arguments.
Home Mode - RPN Entry:
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.

Examples to try with SQIN:


SQIN(5) returns .04
SQIN(36) returns .000771604938
The next program will demonstrate the concept of local variables.

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

HP Prime Programming Tutorial #2: MSGBOX, IF-THEN-ELSE, PRINT,


FOR

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.

Here is a sample output for COMLOCK:

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.

Featured Commands in SUMDIV:


idivis: idivis(integer) returns a sequence of all of the divisors if integer. Access: Toolbox, CAS, 5.
Integer, 1. Divisors
Any CAS command used in programming will be preceded by "CAS." Not all CAS commands can
be used in HP Prime programming at this time.
DIM: returns the dimensions of a sequence, string, or matrix. DIM must be used instead of SIZE to
prevent a Bad Argument error.
For sequences or vectors, DIM returns the length in a list {length}.

For strings, DIM returns length as a number.


For matrices, DIM returns the list {number of rows, number of columns}.
Access: Cmds, 1. Strings, 9. DIM

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.

HP Prime Programming Tutorial #3: WHILE, INPUT, KILL, REPEAT,


GETKEY
This tutorial is going to cover a lot, each with some new programming commands in this series. I
hope you are ready for the intensity. :)

WHILE, INPUT, KILL


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.
WHILE: Repeat a number of commands while a specific condition is test.
WHILEconditionistrueDO
commands
END;
Access: Tmplt, 3. Loop, 5. WHILE
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:
INPUT(variable,"title","label","helptext")
Multi-Variable:
INPUT(listofvariables,"title",listof"labels",listof"helptext")
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.
Access: Cmds, 6. I/O, 5. INPUT
KILL: Terminates program execution. Nothing dies, I promise.
Access: Tmplt. 1. Block, 3. KILL

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:

Access: Tmplt, 3. Loop, 6. REPEAT


Featured:
CONCAT(list1, list2): Melds list1 and list2 into one.
Access: Toolbox, Math, 6. List, 4. Concatenate

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;

Example Key Codes:


33: 8 key
2: up
7: left
8: right
12: down
50: plus
45: minus

HP Prime Programming Tutorial #4: CHOOSE and CASE, Tip about


INPUT
Welcome to Part 4 of our programming series for the Prime. Today's session will cover CHOOSE
and CASE.

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

AREAC - Area of Circles, Rings, and Sectors


EXPORTAREAC()
BEGIN
LOCALC,R,S,,A;
CHOOSE(C,"Areas","1.Circle","2.Ring","3.Sector");
INPUT(R,"InputRadius","R=");

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

HP Prime Programming Tutorial #5: STARTAPP, STARTVIEW, RGB


Today's session is about starting other apps in a program and using colors.

Defining equations in the Program Editor and Home


The equation must be a string and be stored to the appropriate designated variable.
F# is for functions of X. (Function app).
R# is for polar functions of . (Polar app).
U# is for sequences of N, N-1, N-2. (Sequence app).
X# and Y# for parametric equations of T. (Parametric App)
V# for open statements and equations in the Advanced Graphing App, which The independent
variables are X and Y.

# 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

CHECK and UNCHECK


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 F. As you should expect, UNCHECK(1) turns F1 off.
What does CHECK and UNCHECK affect?
1. Whether a function is plotted in Plot view.
2. Whether a function is analyzed in Num view.
Access for CHECK: Cmds, 4. App Functions, 1. CHECK
Access for UNCHECK: Cmds, 4. App Functions, 4. UNCHECK

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

Tip: Change a color of a graph

Use the syntax


F#(COLOR):=RGB(red,blue,green,[alpha]);
F stands for the designated function type (F for function, R for polar, etc)
# is the digit 0-9.
Example:
F8(COLOR):=RGB(0,0,255)
makes the function F8 plot in blue.

This is a lot, but this is doable. Let's see all these commands and tips in action and create some
magic.

Conic Drawing for HP Prime


Draws the conic section for the general equation
Ax^2 + By^2 + Cxy + Dx + Ey + F = 0
You can choose the color how the conic section is plotted, from red, blue, orange, and green.
(Game show enthusiasts take note of the order of the colors I listed... ;) ).
EXPORTCONIC()
BEGIN
LOCALcr,cg,cb,I;
INPUT({A,B,C,D,E,F},
"Ax^2+By^2+Cxy+Dx+Ey+F",{},{},
{0,0,0,0,0,0});
//Colors
CHOOSE(I,"ChooseaColor",
"Red","Blue","Orange","Green");
cr:={255,0,255,0};
cg:={0,0,127,255};
cb:={0,255,0,0};
STARTAPP("AdvancedGraphing");
V1:="A*X^2+B*Y^2+C*X*Y+D*X+E*Y+F=0";
V1(COLOR):=RGB(cr(I),cg(I),cb(I));
CHECK(1);
//PlotView
STARTVIEW(1,1);
END;

Below are some examples. Remember the form:


Ax^2 + By^2 + Cxy + Dx + Ey + F = 0

Projectile Motion for HP Prime


This program 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.
EXPORTPROJ13()
BEGIN
LOCALM,str;
//V,G,areglobal
//Degrees

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.

HP Prime Programming Tutorial #6: Subroutines


Subroutines

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;

(Thanks to Owitte for pointing out my typo)


Examples:
Days Between Dates:
7/3/1985 to 2/28/1995 is 3,527 days
3/14/1977 to 11/17/2013 is 13,397 days
12/10/2010 to 6/30/2014 is 1,298 days
1/5/2015 to 3/19/2227 returns 77,506 BUT this program treats 2100 and 2200 as leap years, which
in reality they are not. Subtract 2 to get the correct answer of 77,504 days.

HP Prime Programming Tutorial #7: TEXTOUT


Greetings everyone. It has been too long since I last posted. I hope everyone had a fantastic
Thanksgiving. For those of you who are battling cold and stormy weather, please be safe. For those
of you living in the Southern Hemisphere where summer is about to begin... I'm jealous! :) I love
summer.
Introduction
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, Advanced Grpahing).
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.
Cartesian vs Pixel
Each graphic object operates in either one of two coordinate systems: Cartesian and pixel. If you
worked with the Hewlett Packard HP 39gii calculator, this might look familiar to you.
The features of the Cartesian system (x,y) are these:
* The end points depend on the Plot variables Xmin, Xmax, Ymin, and Ymax.
* The system is familiar, having x increasing as we move to the right and y increasing as we move
up. (no shocker there).
* 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.
Below is a map of the Cartesian system:

The Pixel System (x,y):


* The boundaries are fixed. The pixel (0,0) is the top left hand corner, the pixel (318, 218) is the
lower right hand corner.
* The value of x still increases as we go to the right. However, y increases as we go down, opposite
of the Cartesian system. On the other hand, x and y are always non-negative.

The Drawing Commands


The HP Prime has two sets of drawing commands: one for the Cartesian system and one for the
Pixel system. All commands for the Pixel system will have a "_P" suffix attached. For example:
LINE draws a line using Cartesian coordinates, while LINE_P draws a line using Pixel coordinates.
General Access: (in the Programming Editor)
Drawing Commands for the Pixel system: Cmds, 2. Drawing, 6. Pixels
Drawing Commands for the Cartesian system: Cmds, 2. Drawing, 7. Cartsian
Clearing the GROB screen
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().
Hint: To paint an entire screen a specific color, use RECT(color).
Showing the Graphics Screen
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.


Access: Cmds, 2. Drawing, 3. FREEZE
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.
Of course, you can use WAIT(n) to make the calculator wait n seconds before executing the next
step.
TEXTOUT and TEXTOUT_P
TEXTOUT and TEXTOUT_P inserts text on a graphics object using Cartesian and Pixel
coordinates, respectively. They are also at the bottom of the Cartesian and Pixel Drawing sub
menus, respectively. (Use either the x,t,,n button or the up button followed by Enter).
Full Syntax (starred commands are optional):
Cartesian:
TEXTOUT(text,GROB*,x,y,fontsize*,textcolor*,width*,background
color*)
Pixel:
TEXTOUT_P(text,GROB*,x,y,fontsize*,textcolor*,width*,background
color*)
text: The text to be written. It can be a string, results, calculations, or any combination.
GROB*: Graphic Object G0 through G9 to be used. If left out, G0 is used.
x: x coordinate
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.
0: Current font size as set by Home Settings screen.
1: Size 10 font
2: Size 12 font
3: Size 14 font
4: Size 16 font
5: Size 18 font
6: Size 20 font
7: Size 22 font
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:
Black text at default font size:

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;

You might also like