| |||||||||||
|
An example of a program using
PROG(),
LOOP(),
RETURN &
IF()
In this example we will program the function FACT(n), which computes the factorial of n. The algorithm we will employ is: Set a local variable total to n . Set up a loop so that total is multiplied by n-1 and then reduce n by 1, returning the value of total when n has reduced to the value 2. If we implement this algorithm step by step with n=4 the values of total and n are changed, (remembering to return the value of total when n reaches the value 2). The pseudo-code could be described as:
total=total*(n-1)
n=n-1 total=4
n=4 total=4*3
n=3 total=4*3*2
n=2 The Derive implementation of this code is, for all integer values of n > 2; FACT(n, total) := PROG(total := n, LOOP(IF(n = 2, RETURN total), total := total·(n - 1), n := n - 1)) which displays as
Notice that the LOOP() and IF() arguments are indented. Also, notice that the variable total is declared local by including it as a parameter of the function FACT(n). As an exercise you may like to open a new algebra window and write this function excluding the parameter total from the function definition and see what happens. We can test this function by checking FACT(100) with 100!
FACT(100)=9332621544394415268169923885626670049071596
100! =
9332621544394415268169923885626670049071596826 Success! Well nearly, I could have been slightly more efficient when updating the values of total and n. But I will revisit this program later when weve covered the relevant area. Now that we are in a position to start writing programs in Derive 5, you will notice that there are 2 kinds of parameters in function definitions. They are user parameters, i.e. the parameters that the user passes into the function, and local variables. All the user parameters should appear first in the list of arguments of the function. The user need not be concerned with the local variables. By definition user parameters are local. If an exit command is encountered within the body of a PROG() or LOOP(), evaluation of the PROG() or LOOP() immediately terminates and evaluation continues with the next expression in the program. exit is used when we need to jump out of a loop or even a prog, without terminating the program. As a simple example, the function FACT(n)is re-written using exit instead of RETURN.
Want to see another example? How about summation
Move on to Update Operators, or Go back to Programming basics
| ||||||||||||||||