Function to Compute Average of the Elements in an Array

ID: Q106700

The information in this article applies to:

SUMMARY

The user-defined function (UDF) shown below uses a DO WHILE loop to sum the elements of the passed array and then divides the total by the number of elements in the array to obtain the average.

MORE INFORMATION

   CLEAR
   SET CURSOR OFF
   SET TALK OFF
   DECLARE TheArray[10]
   TheArray[1]  = 1
   TheArray[2]  = 2
   TheArray[3]  = 3
   TheArray[4]  = 4
   TheArray[5]  = 5
   TheArray[6]  = 6
   TheArray[7]  = 7
   TheArray[8]  = 8
   TheArray[9]  = 9
   TheArray[10] = 10
   TheAvg =Aavg(@TheArray,10)
   WAIT WINDOW "The average of the array is " + ALLTRIM(STR(TheAvg,8,2))
   RETURN


**********************************************************************
   * Function.....: AAVG
   * Notes........: This function computes the average of the elements
   *                in an array.
   * Parameters:    Aname     - The name of an array containing
   *                            numeric elements to average.
   *                Aelements - The numeric of elements to average.
**********************************************************************
   FUNCTION AAVG
   PARAMETERS Aname, Aelements
   STORE 0 TO Atotal, Avg
   STORE 1 TO Acount
   DO WHILE Acount <= Aelements
       Atotal     =  Atotal + Aname[Acount]
       Acount  =  Acount + 1
   ENDDO
   RETURN(Atotal/Aelements)
* To return the sum of all the elements in the array, use RETURN(Atotal).

Additional reference words: FoxDos FoxWin 2.00 2.50 2.50a 2.50b KBCategory: kbprg kbcode KBSubcategory: FxprgGeneral

Last Reviewed: June 27, 1995