z/OS TSO/E REXX User's Guide
Previous topic | Next topic | Contents | Contact z/OS | Library | PDF


Exercise - Writing a Function

z/OS TSO/E REXX User's Guide
SA32-0982-00

Write a function named "AVG" that receives a list of numbers separated by blanks, and computes their average as a decimal number. The function is called as follows:
AVG(number1 number2 number3 ...)

Use the WORDS and WORD built-in functions. For more information about these built-in functions, see z/OS TSO/E REXX Reference.

ANSWER

Possible Solution

/****************************** REXX *******************************/
/* This function receives a list of numbers, adds them, computes   */
/* their average and returns the average to the calling exec.      */
/*******************************************************************/

 ARG numlist           /* receive the numbers in a single variable */

 sum = 0               /* initialize sum to zero                   */

 DO n = 1 TO WORDS(numlist)   /* Repeat for as many times as there */
                              /* are numbers                       */

    number = WORD(numlist,n)  /* Word #n goes to number            */
    sum = sum + number        /* Sum increases by number           */
 END

 average = sum / WORDS(numlist)   /* Compute the average           */

 RETURN average

Go to the previous page Go to the next page




Copyright IBM Corporation 1990, 2014