# Function to Compute Average of the Elements in an Array

ID: Q106700

• Microsoft FoxPro for Windows, versions 2.5, 2.5a, and 2.5b
• Microsoft FoxPro for MS-DOS, versions 2.0, 2.5, 2.5a, and 2.5b

## 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.

```   CLEAR
SET CURSOR OFF
SET TALK OFF
DECLARE TheArray
TheArray  = 1
TheArray  = 2
TheArray  = 3
TheArray  = 4
TheArray  = 5
TheArray  = 6
TheArray  = 7
TheArray  = 8
TheArray  = 9
TheArray = 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