1

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?

2
  • You don't need to dimension the iterator in a For Each loop. Commented Apr 26, 2016 at 13:12
  • Yeah that. My brain is was being a potato. What I should have typed was: "You don't need to Dim the iterator of a For Each loop beforehand." Commented Apr 26, 2016 at 13:21

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.