Previous Next Chapter

Square.rexx

This example introduces the concept of a function, a group of statements executed by mentioning the function name in a suitable context. Functions allow you to build large complex programs from smaller modules. Functions also permit the same code for similar operations in a different program.

Functions are specified in an expression as a name followed by an open parenthesis. (There is no space between the name and the parenthesis.) One or more expressions, called arguments, may follow the parenthesis. The last argument must be followed by a closing parenthesis. These arguments pass information to the function for processing.

Program 5. Square.rexx

/*Defining and calling a function.*/

DO i = 1 to 5
SAY i square (i) /*Call the "square" function*/
END
EXIT
square: /*Function name*/
ARG x /*Get the argument*/
RETURN x**2 /*Square it and return*/

Starting with DO and ending with END , a loop is set up with an index variable "i", that will increment by 1. The loop will iterate (repeat) five times. The loop contains an expression that calls the function " square " when the expression is evaluated. The function's result is displayed using the SAY instruction.

The function " square ", defined by the ARG and RETURN instructions, calculates the squared values. ARG retrieves the value of the argument string " i " and RETURN passes the function's result back to the SAY instruction.

Once the function is called by the loop, the program looks for the function name " square ", retrieves the argument " i ", performs a calculation, and returns to the line within the DO/END loop. The EXIT instruction ends the program after the final loop.

Top Previous Next Chapter