Programming. Texas Instruments TI-NSPIRE CAS, TI-Nspire CX, TI-nspire CX CAS, TI-Nspire
Annonce
Annonce
Programming
You can create user-defined functions or programs by typing definition statements on the Calculator entry line or by using the Program Editor.
The Program Editor offers some advantages, and it is covered in this section. For information on defining programs and functions in
Calculator, see the “Calculator” chapter.
Overview of the Program Editor
The Program Editor helps you define, edit, and manage user-defined functions and programs.
• The editor has programming templates and dialog boxes to help you define functions and programs using correct syntax.
• The editor lets you enter multiple-line programming statements without requiring a special key sequence to add each line.
• You can easily create private and public library objects (variables, functions, and programs). For details, see the “Libraries” chapter.
• The editor is accessible from the main
Insert
menu as well as from the
Calculator’s
Functions & Programs
menu.
À
Â
Á
À
Program Editor menu – This menu is available anytime you are in the
Program Editor work area using the Normal view mode. On the handheld, press b
to display the menu.
Programming 673
Á
Program Editor work area
Â
Status line shows line number information and the name of the function or program being edited. An asterisk (*) indicates that this function is “dirty,” which means that it has changed since the last time its syntax has been checked and it has been stored.
Program Editor menu
Actions
New
Open
Import
View
Create Copy
Rename
Displays a dialog box for defining a new function or program.
Lets you open an existing library function or program for editing.
Imports a program or function from a library.
Lets you view (and optionally, edit) an existing library function or program.
Lets you copy the current function or program.
Lets you rename the current function or program.
Change Library Access Lets you change the access level of a library object to private (LibPriv), public
(LibPub), or none.
Insert Comment
Find
Inserts a comment (
©
) at the cursor position.
Displays a dialog box for text search.
Find and Replace
Go to Line
Go Back
Lets you find and, optionally, replace occurrences of specified text.
Moves the cursor to a specified line number.
Lets you easily return from the Program
Editor to the Calculator or Notes application after a runtime error occurs.
Close Closes the current function or program.
674 Programming
Check Syntax &
Store
Check Syntax & Store Finds syntax errors and tries to put the cursor near the first error. If no errors, stores current function or program.
Check Syntax Finds syntax errors and tries to put the cursor near the first error.
Define Variables
Local
Define
Delete Variable
Func...EndFunc
Prgm...EndPrgm
Lock
Inserts
Local
.
Inserts
Define
.
Inserts
DelVar
.
Inserts
Func...EndFunc
template.
Inserts
Prgm...EndPrgm
template.
Inserts
Lock
,
unLock
, or
getLockInfo()
.
Control
If Inserts
If
statement.
If...Then...EndIf
Inserts
If...Then...EndIf
template.
If...Then...Else...EndIf
Inserts
If...Then...Else...EndIf
template.
ElseIf...Then
For...EndFor
While...EndWhile
Loop...EndLoop
Inserts
Inserts
ElseIf...Then
For...EndFor
template.
template.
Inserts
While...EndWhile
template.
Inserts
Loop...EndLoop
template.
Try...Else...EndTry
ClrErr
PassErr
Inserts
Try...Else...EndTry
template.
Inserts
ClrErr
.
Inserts
PassErr
.
Programming 675
Control
Inserts variable name .
Inserts
()
.
Transfer
Return
Cycle
Exit
Lbl
Go to Lbl
Stop
Input/Output
Disp
Inserts
Inserts
Inserts
return()
Cycle
Inserts
Exit
.
Stop
.
.
.
Inserts
Lbl
(label).
Inserts
Goto
.
Inserts the
Disp
(display) command.
Inserts the command.
Inserts the command.
Inserts the command.
Mode
Display Digits
Angle
Exponential Format
Real or Complex
Auto or Approx
Lets you select from several Float and Fix settings.
Lets you select Degrees, Radians, or
Gradians.
Lets you select Normal, Scientific, or
Engineering.
Lets you select Real, Rectangular, or Polar.
CAS: Lets you select Auto, Approximate, or Exact results.
676 Programming
Mode
Vector Format
Base
CAS: Unit System
GetMode
Get Language Info
Lets you select Rectangular, Cylindrical, or
Spherical.
Lets you select Decimal, Hex, or Binary.
Lets you select SI or Eng/US.
Inserts
getMode()
.
Inserts
getLangInfo()
.
Defining a program or function
Starting a new Program Editor
1. To start the editor from a Calculator page,
– From the
Insert
menu, select
Program Editor
, and select
New
.
Handheld: Press b 9 1 1
.
2. To start the editor when not on a Calculator page,
– From the
Insert
menu, select
Program Editor
, and select
New
.
Handheld: Press
/ b 4 8 1
.
3. Type a name for the function or program you are defining.
4. Select the
Type
(
Program
or
Function
).
5. Set the
Library Access
:
– To use the function or program only from the current document and problem, select
None
.
– To make the function or program accessible from any document but not visible in the Catalog, select
LibPriv
.
Programming 677
– To make the function or program accessible from any document and also visible in the Catalog, select
LibPub (Show in Catalog)
.
For details, see the “Libraries” chapter.
6. Click
OK
.
A new instance of the Program Editor opens, with a template matching the selections you made.
Entering lines into a function or program
The Program Editor does not execute the commands or evaluate expressions as you enter them. They are executed only when you evaluate the function or run the program.
1. If your function or program will require the user to supply arguments, type parameter names in the parentheses that follow the name.
Separate parameters with a comma.
2. Between the Func and EndFunc (or Prgm and EndPrgm) lines, enter the lines of statements that make up your function or program.
– You can either type the names of functions and commands or insert them from the Catalog.
– A line can be longer than the width of the screen; if so, you might have to scroll to view the entire statement.
678 Programming
– After typing each line, press
·
. This inserts a new blank line and lets you continue entering another line.
– Use the
¡
,
¢
,
£
, and
¤
arrow keys to scroll through the function or program for entering or editing commands.
Inserting comments
A comment symbol (©) lets you enter a remark. Comments can be useful to someone viewing or editing the program. Comments do not display when the program runs, and they have no effect on program flow.
Define LibPub volcyl(ht,r) =
Prgm
©volcyl(ht,r) => volume of cylinder
Disp “Volume =”, approx(
p ¦
r
2
¦
ht)
©This is another comment.
EndPrgm
À
À
Comment showing required syntax. Because this library object is public and this comment is the first line in a Func or Prgm block, the comment displays in the Catalog as help. For details, see the
“Libraries” chapter.
To insert a comment:
1. Position the cursor at the end of the line where you want to insert a comment.
2. From the
Actions
menu, select
Insert Comment
.
3. Type the text of the comment after the © symbol.
Checking syntax
The Program Editor lets you check the function or program for correct syntax.
` From the
Check Syntax & Store
menu, select
Check Syntax
.
If the syntax checker finds any syntax errors, it displays an error message and tries to position the cursor near the first error so you can correct it.
Programming 679
Storing the function or program
You must store your function or program to make it accessible. The
Program Editor automatically checks the syntax before storing.
An asterisk (*) is displayed in the upper left corner of the Program Editor to indicate that the function or program has not been stored.
` From the
Check Syntax & Store
menu, select
Check Syntax & Store
.
If the syntax checker finds any syntax errors, it displays an error message and tries to position the cursor near the first error.
If no syntax errors are found, the message “Stored successfully“ is displayed in the status line at the top of the Program Editor.
Note: If the function or program is defined as a library object, you must also save the document in the designated library folder and refresh libraries to make the object accessible to other documents. For details, see the “Libraries” chapter.
Viewing a program or function
1. From the
Actions
menu, select
View
.
2. If the function or program is a library object, select its library from the
Location
list.
3. Select the function or program name from the
Name
list.
680 Programming
The function or program displays in a viewer.
4. Use the arrow keys to view the function or program.
5. If you want to edit the program, click
Edit
.
Note: The
Edit
selection is available only for functions and programs defined in the current problem. To edit a library object, you must first open its library document.
Opening a function or program for editing
You can open a function or program from the current problem only.
Note: You cannot modify a locked program or function. To unlock the object, go to a Calculator page and use the
unLock
command.
1. Display the list of available functions and programs.
– From the
Actions
menu, select
Open
.
2. Select the item to open.
Importing a program from a library
You can import a function or program defined as a library object into a
Program Editor within the current problem. The imported copy is not locked, even if the original is locked.
1. From the
Actions
menu, select
Import
.
Programming 681
2. Select the
Library Name
.
3. Select the
Name
of the object.
4. If you want the imported object to have a different name, type the name under
Import As
.
Creating a copy of a function or program
When creating a new function or program, you might find it easier to start with a copy of the current one. The copy that you create is not locked, even if the original is locked.
1. From the
Actions
menu, select
Create Copy
.
2. Type a new name, or click
OK
to accept the proposed name.
3. If you want to change the access level, select
Library Access
, and select a new level.
Renaming a program or function
You can rename and (optionally) change the access level of the current function or program.
1. From the
Actions
menu, select
Rename
.
2. Type a new name, or click
OK
to accept the proposed name.
682 Programming
3. If you want to change the access level, select
Library Access
, and select a new level.
Changing the library access level
1. From the
Actions
menu, select
Change Library Access
.
2. Select the
Library Access
:
– To use the function or program only from the current Calculator problem, select
None
.
– To make function or program accessible from any document but not visible in the Catalog, select
LibPriv
.
– To make the function or program accessible from any document and also visible in the Catalog, select
LibPub
.
Finding text
1. From the
Actions
menu, select
Find
.
2. Type the text that you want to find, and click
OK
.
– If the text is found, it is highlighted in the program.
– If the text is not found, a notification message displays.
Finding and replacing text
1. From the
Actions
menu, select
Find and Replace
.
Programming 683
2. Type the text that you want to find.
3. Type the replacement text.
4. Click
Replace
to replace the first occurrence after the cursor position, or click
Replace All
to replace every occurrence.
Note: If the text is found in a math template, a message is displayed to warn you that your replacement text will replace the whole template—not just the found text.
Closing the current function or program
` From the
Actions
menu, select
Close
.
If the function or program has unstored changes, you are prompted to check syntax and store before closing.
Running programs and evaluating functions
After defining and storing a function or program, you can use it from an application. All the applications can evaluate functions, but only the
Calculator and Notes applications can run programs.
The program statements are executed in sequential order (although some commands alter the program flow). The output, if any, is displayed in the application’s work area.
• Program execution continues until it reaches the last statement or a
Stop
command.
• Function execution continues until it reaches a
Return
command.
• To stop a program or function manually,
– Windows®: Hold down the
F12
key and press
Enter
repeatedly.
– Macintosh®: Hold down the
F5
key and press
Enter
repeatedly.
– Handheld: Hold down the c
key and press
·
repeatedly.
684 Programming
Using short and long names
Anytime you are in the same problem where an object is defined, you can access it by entering its short name (the name given in the object’s
Define
command). This is the case for all defined objects, including private, public, and non-library objects.
You can access a library object from any document by typing the object’s long name. A long name consists of the name of the object’s library document followed by a backslash “\” followed by the name of the object. For example, the long name of the object defined as
func1
in the library document
lib1
is
lib1\func1
. To type the “\” character on the handheld, press g p
.
Note: If you cannot remember the exact name or the order of arguments required for a private library object, you can open the library document or use the Program Editor to view the object. You also can use
getVarInfo
to view a list of objects in a library.
Using a Public library function or program
1. Make sure you have defined the object in the document’s first problem, stored the object, saved the library document in the MyLib folder, and refreshed the libraries.
2. Open the TI-Nspire™ application in which you want to use the function or program.
Note: All applications can evaluate functions, but only the Calculator and Notes applications can run programs.
3. Open the Catalog and use the library tab to find and insert the object.
- or -
Type the name of the object. In the case of a function or program, always follow the name with parentheses.
libs2\func1()
4. If the program requires you to supply one or more arguments, type the values or variable names inside the parentheses.
libs2\func1(34,power)
5. Press
·
.
Programming 685
Using a Private library function or program
To use a Private library object, you must know its long name. For example, the long name of the object defined as
func1
in the library document
lib1
is
lib1\func1
.
Note: If you cannot remember the exact name or the order of arguments required for a private library object, you can open the library document or use the Program Editor to view the object.
1. Make sure you have defined the object in the document’s first problem, stored the object, saved the library document in the MyLib folder, and refreshed the libraries.
2. Open the TI-Nspire™ application in which you want to use the function or program.
Note: All applications can evaluate functions, but only the Calculator and Notes applications can run programs.
3. Type the name of the object. In the case of a function or program, always follow the name with parentheses.
libs2\func1()
4. If the object requires you to supply one or more arguments, type the values or variable names inside the parentheses.
libs2\func1(34,power)
5. Press
·
.
Running a non-library program or function
1. Make sure you are in the same problem in which the function or program is defined.
2. Type the name of the function or program on the entry line, or press h
to select the name from a list.
You must always include a set of parentheses after the name.
prog1()
If the function or program requires you to supply one or more arguments, type the values or variable names inside the parentheses.
prog1(34,power)
3. Press
·
.
686 Programming
Interrupting a running program
While a function or program is running, the busy pointer
}
displays.
` To stop the function or program,
– Windows®: Hold down the
F12
key and press
Enter
repeatedly.
– Macintosh®: Hold down the
F5
key and press
Enter
repeatedly.
– Handheld: Hold down the c
key and press
·
repeatedly.
A message displays. To edit the function or program in the Program
Editor, select
Go To
. The cursor appears at the command where the break occurred.
Getting values into a program
You can choose from several methods to supply the values that a function or program uses in calculations.
Embedding the values within the program or function
This method is useful primarily for values that must be the same each time the program or function is used.
1. Define the program.
2. Run the program.
Letting the user assign the values to variables
A program or function can refer to variables created beforehand. This method requires users to remember the variable names and to assign values to them before using the object.
1. Define the program.
Programming 687
2. Supply the variables, and then run the program.
Letting the user supply the values as arguments
This method lets users pass one or more values as arguments within the expression that calls the program or function.
The following program, , calculates the volume of a cylinder. It requires the user to supply two values: height and radius of the cylinder.
1. Define the program.
(height,radius) =
"Volume =", (
p ¦
radius
2
¦
height
)
2. Run the program to display the volume of a cylinder with a height of
34 mm and a radius of 5 mm.
(34,5) Volume = 534.071
Note: You do not have to use the parameter names when you run the program, but you must supply two arguments (as values, variables, or expressions). The first must represent the height, and the second must represent the radius.
Requesting the values from the user (programs only)
You can use the and commands in a program to make the program pause and display a dialog box prompting the user for information. This method does not require users to remember variable names or the order in which they are needed.
You cannot use the or command in a function.
1. Define the program.
"Width: ",
"Height: ",
688 Programming
2. Run the program and respond to the requests.
Width: 3 (3 entered as a response)
Height: 23.64 (23.64 entered as a response)
Use instead of when you want the program to interpret the user’s response as a character string rather than a math expression. This avoids requiring the user to enclose the response in quotation marks (““).
Displaying information
A running function or program does not display intermediate calculated results unless you include a command to display them. This is an important difference between performing a calculation on the entry line and performing it in a function or program.
The following calculations, for example, do not display a result in a function or program (although they do from the entry line).
©
:=12
¦
6
(
p
/4)
©
Displaying information in the history
You can use the command in a program or function to display information, including intermediate results, in the history.
©
12
¦
6
"Result:",(
p
/4)
©
Displaying information in a dialog box
You can use the command to pause a running program and display information in a dialog box. The user selects to continue or selects to stop the program.
You cannot use the command in a function.
©
"Area=" &
©
Programming 689
Note: Displaying a result with or does not store that result. If you expect to refer later to a result, store it to a global variable.
©
(
p
/4)
&
maximum
maximum
©
Using local variables
A local variable is a temporary variable that exists only while a userdefined function is being evaluated or a user-defined program is running.
Example of a local variable
The following program segment shows a
For...EndFor
loop (which is discussed later in this module). The variable
i
is the loop counter. In most cases, the variable
i
is used only while the program is running.
Local i
For i,0,5,1
Disp i
EndFor
Disp i
À
À
Declares variable
i
as local.
Note: When possible, declare as local any variable that is used only within the program and does not need to be available after the program stops.
What causes an undefined variable error message?
An
Undefined
variable error message displays when you evaluate a userdefined function or run a user-defined program that references a local variable that is not initialized (assigned a value).
For example:
Define fact(n)=Func
Local m
EndWhile
Return m
EndFunc
À
While n>1 n
¦
m
&
m: n–1
&
n
À
Local variable
m
is not assigned an initial value.
690 Programming
Initialize local variables
All local variables must be assigned an initial value before they are referenced.
Define fact(n)=Func
Local m: 1
&
m
While n>1 n
¦
m
&
m: n–1
&
n
EndWhile
Return m
EndFunc
À
À
1 is stored as the initial value for
m
.
Note (CAS): Functions and programs cannot use a local variable to perform symbolic calculations.
CAS: Performing symbolic calculations
If you want a function or program to perform symbolic calculations, you must use a global variable instead of a local. However, you must be certain that the global variable does not already exist outside of the program. The following methods can help.
• Refer to a global variable name, typically with two or more characters, that is not likely to exist outside of the function or program.
• Include
DelVar
within a program to delete the global variable, if it exists, before referring to it. (
DelVar
does not delete locked or linked variables.)
Differences between functions and programs
A function defined in the Program Editor is similar to the functions built into the TI-Nspire™ Software.
• Functions must return a result, which can be graphed or entered in a table. Programs cannot return a result.
• You can use a function (but not a program) within an expression. For example:
3
¦
func1(3)
is valid, but not
3
¦
prog1(3)
.
• You can run programs from Calculator and Notes applications only.
However, you can evaluate functions in Calculator, Notes, Lists &
Spreadsheet, Graphs & Geometry, and Data & Statistics.
Programming 691
• A function can refer to any variable; however, it can store a value to a local variable only. Programs can store to local and global variables.
Note: Arguments used to pass values to a function are treated as local variables automatically. If you want to store to any other variables, you must declare them as
Local
from within the function.
• A function cannot call a program as a subroutine, but it can call another user-defined function.
• You cannot define a program within a function.
• A function cannot define a global function, but it can define a local function.
Calling one program from another
One program can call another program as a subroutine. The subroutine can be external (a separate program) or internal (included in the main program). Subroutines are useful when a program needs to repeat the same group of commands at several different places.
Calling a separate program
To call a separate program, use the same syntax that you use to run the program from the entry line.
Define subtest1()=
Prgm
For i,1,4,1 subtest2(i,i
¦
1000)
EndFor
EndPrgm
Define subtest2(x,y)=
Prgm
Disp x,y
EndPrgm
Defining and calling an internal subroutine
To define an internal subroutine, use the
Define
command with
Prgm...EndPrgm
. Because a subroutine must be defined before it can be called, it is a good practice to define subroutines at the beginning of the main program.
An internal subroutine is called and executed in the same way as a separate program.
692 Programming
Define subtest1()=
Prgm local subtest2
À
Define subtest2(x,y)=
Prgm
Disp x,y
EndPrgm
Â
Á
©Beginning of main program
For i,1,4,1 subtest2(i,I*1000)
EndFor
EndPrgm
À
Declares the subroutine as a local variable.
Á
Defines the subroutine.
Â
Calls the subroutine.
Note: Use the Program Editor’s
Var
menu to enter the
Define
and
Prgm...EndPrgm
commands.
Notes about using subroutines
At the end of a subroutine, execution returns to the calling program. To exit a subroutine at any other time, use
Return
with no argument.
A subroutine cannot access local variables declared in the calling program. Likewise, the calling program cannot access local variables declared in a subroutine.
Lbl
commands are local to the programs in which they are located.
Therefore, a
Goto
command in the calling program cannot branch to a label in a subroutine or vice versa.
Avoiding circular-definition errors
When evaluating a user-defined function or running a program, you can specify an argument that includes the same variable that was used to define the function or create the program. However, to avoid circulardefinition errors, you must assign a value for variables that are used in evaluating the function or running the program. For example:
x+1
&
x
À
– or –
Programming 693
For i,i,10,1
Disp i
EndFor
À
À
Causes a
Circular definition
error message if x or i does not have a value. The error does not occur if x or i has already been assigned a value.
Controlling the flow of a function or program
When you run a program or evaluate a function, the program lines are executed in sequential order. However, some commands alter the program flow. For example:
• Control structures such as
If...EndIf
commands use a conditional test to decide which part of a program to execute.
• Loop commands such as
For...EndFor
repeat a group of commands.
Using If, Lbl, and Goto to control program flow
The
If
command and several
If...EndIf
structures let you execute a statement or block of statements conditionally, that is, based on the result of a test (such as x>5).
Lbl
(label) and
Goto
commands let you branch, or jump, from one place to another in a function or program.
The
If
command and several
If...EndIf
structures reside on the Program
Editor’s
Control
menu.
When you insert a structure such as
If...Then...EndIf
, a template is inserted at the cursor location. The cursor is positioned so that you can enter a conditional test.
If command
To execute a single command when a conditional test is true, use the general form:
If x>5
Disp "x is greater than 5"
Disp x
Á
À
À
Executed only if x>5; otherwise, skipped.
Á
Always displays the value of x.
In this example, you must store a value to x before executing the
If
command.
694 Programming
If...Then...EndIf structures
To execute one group of commands if a conditional test is true, use the structure:
If x>5 Then
Disp "x is greater than 5"
2
¦
x
&
x
EndIf
Disp x
À
Á
À
À
Executed only if x>5.
Á
Displays the value of:
2x if x>5 x if x
{5
Note:
EndIf
marks the end of the
Then
block that is executed if the condition is true.
If...Then...Else...EndIf structures
To execute one group of commands if a conditional test is true and a different group if the condition is false, use this structure:
If x>5 Then
Disp "x is greater than 5"
5
¦
x
&
x
EndIf
Disp x
Â
À
2
¦
x
&
x
Else
À
Disp "x is less than or equal to 5"
Á
Á
À
Executed only if x>5.
Á
Executed only if x
{5.
Â
Displays value of:
2x if x>5
5x if x
{5
If...Then...ElseIf... EndIf structures
A more complex form of the
If
command lets you test for multiple conditions. Suppose you want a program to test a user-supplied argument that signifies one of four options.
Programming 695
To test for each option (If Choice=1, If Choice=2, and so on), use the
If...Then...ElseIf...EndIf
structure.
Lbl and Goto commands
You can also control the flow by using
Lbl
(label) and
Goto
commands.
These commands reside on the Program Editor’s
Transfers
menu.
Use the
Lbl
command to label (assign a name to) a particular location in the function or program.
Lbl
labelName
name to assign to this location (use the same naming convention as a variable name)
You can then use the
Goto
command at any point in the function or program to branch to the location that corresponds to the specified label.
Goto
labelName
specifies which
Lbl
command to branch to
Because a
Goto
command is unconditional (it always branches to the specified label), it is often used with an
If
command so that you can specify a conditional test. For example:
If x>5
Goto GT5
Disp x
--------
Á
À
--------
Lbl GT5
Disp "The number was > 5"
À
If x>5, branches directly to label GT5.
Á
For this example, the program must include commands (such as
Stop
) that prevent
Lbl
GT5 from being executed if x
{5.
Using loops to repeat a group of commands
To repeat the same group of commands successively, use one of the loop structures. Several types of loops are available. Each type gives you a different way to exit the loop, based on a conditional test.
696 Programming
Loop and loop-related commands reside on the Program Editor’s
Control
and
Transfers
menus.
When you insert one of the loop structures, its template is inserted at the cursor location. You can then begin entering the commands that will be executed within the loop.
For...EndFor loops
A
For...EndFor
loop uses a counter to control the number of times the loop is repeated. The syntax of the
For
command is:
Note: The ending value can be less than the beginning value, provided the increment is negative.
For
variable, begin, end [, increment]
À Á Â Ã
À
Variable used as a counter
Á
Counter value used the first time
For
is executed
Â
Exits the loop when
variable exceeds this value
Ã
Added to the counter each subsequent time
For
is executed (If this optional value is omitted, the
increment is 1.)
When
For
is executed, the
variable value is compared to the end value. If
variable does not exceed end, the loop is executed; otherwise, control jumps to the command following
EndFor
.
i > 5 i
{
5
For i,0,5,1
--------
--------
EndFor
--------
Note: The
For
command automatically increments the counter variable so that the function or program can exit the loop after a certain number of repetitions.
At the end of the loop (
EndFor
), control jumps back to the
For
command, where the variable is incremented and compared to
end
.
For example:
Programming 697
For i,0,5,1
Disp i
EndFor
Disp i
À
Á
À
Displays 0, 1, 2, 3, 4, and 5.
Á
Displays 6. When
variable increments to 6, the loop is not executed.
Note: You can declare the counter variable as local if it does not need to be saved after the function or program stops.
While...EndWhile loops
A
While...EndWhile
loop repeats a block of commands as long as a specified condition is true. The syntax of the
While
command is:
While
condition
When
While
is executed,
condition is evaluated. If condition is true, the loop is executed; otherwise, control jumps to the command following
EndWhile
.
x
|
5 x < 5
While x<5
--------
--------
EndWhile
--------
Note: The
While
command does not automatically change the condition.
You must include commands that allow the function or program to exit the loop.
At the end of the loop (
EndWhile
), control jumps back to the
While
command, where condition is re-evaluated.
To execute the loop the first time, the condition must initially be true.
• Any variables referenced in the condition must be set before the
While
command. (You can build the values into the function or program, or you can prompt the user to enter the values.)
• The loop must contain commands that change the values in the condition, eventually causing it to be false. Otherwise, the condition is always true and the function or program cannot exit the loop
(called an infinite loop).
For example:
698 Programming
0
&
x
À
While x<5
Disp x
Á
x+1
&
x
EndWhile
Disp x
Â
Ã
À
Initially sets x.
Á
Displays 0, 1, 2, 3, and 4.
Â
Increments x.
Ã
Displays 5. When x increments to 5, the loop is not executed.
Loop...EndLoop loops
A
Loop...EndLoop
creates an infinite loop, which is repeated endlessly.
The
Loop
command does not have any arguments.
Loop
--------
--------
EndLoop
--------
Typically, you insert commands in the loop that let the program exit from the loop. Commonly used commands are:
If
,
Exit
,
Goto
, and
Lbl
(label).
For example:
0
&
x
Loop
Disp x x+1
&
x
If x>5
Exit
EndLoop
Disp x
À
Á
À
An
If
command checks the condition.
Á
Exits the loop and jumps to here when
x
increments to 6.
Note: The
Exit
command exits from the current loop.
Programming 699
In this example, the
If
command can be anywhere in the loop.
When the If command is:
At the beginning of the loop
At the end of the loop
The loop is:
Executed only if the condition is true.
Executed at least once and repeated only if the condition is true.
The
If
command could also use a
Goto
command to transfer program control to a specified
Lbl
(label) command.
Repeating a loop immediately
The
Cycle
command immediately transfers program control to the next iteration of a loop (before the current iteration is complete). This command works with
For...EndFor
,
While...EndWhile
, and
Loop...EndLoop
.
Lbl and Goto loops
Although the
Lbl
(label) and
Goto
commands are not strictly loop commands, they can be used to create an infinite loop. For example:
Lbl START
--------
--------
Goto START
--------
As with
Loop...EndLoop
, the loop should contain commands that let the function or program exit from the loop.
Changing mode settings
Functions and programs can use the
setMode()
function to temporarily set specific calculation or result modes. The Program Editor’s
Mode
menu makes it easy to enter the correct syntax without requiring you to memorize numeric codes.
Note: Mode changes made within a function or program definition do not persist outside the function or program.
Setting a mode
1. Position the cursor where you want to insert the
setMode
function.
2. From the
Mode
menu, select the mode to change, and select the new setting.
The correct syntax is inserted at the cursor location. For example:
700 Programming
Debugging programs and handling errors
After you write a function or program, you can use several techniques to find and correct errors. You can also build an error-handling command into the function or program itself.
If your function or program allows the user to select from several options, be sure to run it and test each option.
Techniques for debugging
Run-time error messages can locate syntax errors but not errors in program logic. The following techniques may be useful.
• Temporarily insert
Disp
commands to display the values of critical variables.
• To confirm that a loop is executed the correct number of times, use
Disp
to display the counter variable or the values in the conditional test.
• To confirm that a subroutine is executed, use
Disp
to display messages such as “Entering subroutine” and “Exiting subroutine” at the beginning and end of the subroutine.
• To stop a program or function manually,
– Windows®: Hold down the
F12
key and press
Enter
repeatedly.
– Macintosh®: Hold down the
F5
key and press
Enter
repeatedly.
– Handheld: Hold down the c
key and press
·
repeatedly.
Error-handling commands
Command
Try...EndTry
PassErr
Description
Defines a block that lets a function or program execute a command and, if necessary, recover from an error generated by that command.
Clears the error status and sets system variable to zero.
For an example of using , see the command in the
Reference Guide
.
Passes an error to the next level of the
Try...EndTry
block.
Programming 701
702 Programming
Download
Annonce