Reputation: 11
I have this code
Dim intPerson As Integer
For Each intPerson In intAge
Next
intPerson holds a different number every time the loop is executed because intAge is an array. Is there a way I can find the average of intPerson by adding each number each time and then dividing it by the amount of numbers there are in the array?
Upvotes: 1
Views: 48
Reputation: 27342
The easiest way is to use Linq:
'create an array with some sample ages
Dim intAge As Integer() = {22, 34, 56, 87, 19}
'find the average
Dim averageAge = intAge.Average 'averageAge = 43.6
If you wanto do this longhand you can sum up the values and divide by the number:
Dim totalAges As Integer = 0
For i As Integer = 0 To intAge.Count - 1
totalAges += intAge(i)
Next
averageAge = totalAges / intAge.Count 'averageAge = 43.6
Upvotes: 2