ArrayAvg

Description

Returns the average of the values in an array.

Category

Array functions

Syntax

ArrayAvg(array) 

Parameters

Parameter
Description
array
Name of an array that contains values to average.

Example

<!--- This example shows the use of ArrayAvg --->

<!--------------------------------------------------------------------- 
This following six lines of code keep track of the form fields that can 
be dynamically generated on the screen. It uses the Fieldnames variable
with the ListLen function to determine the number of fields on the form.
---------------------------------------------------------------------->

<cfset FormElem = 2>
  <cfif Isdefined("Form.Submit")>
    <cfif Form.Submit is "More">
      <cfset FormElem = ListLen(Form.Fieldnames)>
    </cfif>
  </cfif>

<html>
<head>
<title>ArrayAvg Example</title>
</head>

<body>
<H3>ArrayAvg Example</H3>
<P>
This example uses ArrayAvg to find the average of the numbers that 
you enter into an array.<BR> 
If you would like to enter more than two numbers press the 
<b>more</b> button.
</P>

<form action = "arrayavg.cfm" method = "post">

<!--------------------------------------------------------------------- 
The following code initially creates two fields. It adds fields
if the user presses MORE. FormElem is initialized to two at the
beginning of this code to show that the form has two fields. 
---------------------------------------------------------------------->

<input type = "submit" name = "submit" value = "more">

<table cellspacing = "2" cellpadding = "2" border = "0">
<CFLOOP index = "LoopItem" from = "1" to = "#FormElem#">
  <tr>
    <cfoutput>
      <th align = "left">Number #LoopItem#</th>
      <td><input type = "text" name = "number#LoopItem#"></td>
    </cfoutput>
  </tr>
</CFLOOP>
</table>

<input type = "submit" name = "submit" value = "get the average">
</FORM>

<!--- create an array --->

<cfif IsDefined("FORM.submit")>
  <cfset myNumberArray = ArrayNew(1)>
  <cfset Count = 1>
  <CFLOOP index = "ListItem" list = "#Form.Fieldnames#">
     <cfif Left(ListItem,3) is "Num">
      <cfset myNumberArray[Count] = Val(Evaluate("number#Count#"))>
      <cfset count = IncrementValue(Count)>
    </cfif> 
  </CFLOOP>
    
  <cfif Form.Submit is "get the average">  
    <!--- use ArrayAvg to get the average of the two numbers --->
    <P>The average of the numbers that you entered is
    <cfoutput>#ArrayAvg(myNumberArray)#.</cfoutput>
  <cfelse>
    <cfoutput>Try again. You must enter at least two numeric values.
    </cfoutput>
  </cfif>  
</cfif>  
</body>
</html>