Sei sulla pagina 1di 2

Example 4 - Finding the

average of numbers in a list


This program has a list that contains test scores. The program will go
through the list and add together all the numbers to get a total. It then
works out the average of the test scores.
Interface

Code when btnFind is clicked

'an array called scores, that contains 5 test scores

Dim scores As Array = {10, 12, 7, 6, 10}

'the size of the array if found by using .Length, it will return 5

Dim size As Integer = scores.Length

Dim total As Integer = 0

'a loop that will repeat between 0 and the value of size - 1 (so it doesn't loop one
too many times)

For x = 0 To size - 1

'it will use x from the loop to add the correct element from the list to the
total

total = total + scores(x)

Next

'the loop has now finished, the average is calculated by dividing the total by the
size
Dim average As Decimal = total / size

MessageBox.Show("The average of the numbers is: " & average.ToString)

This is what happens when the button is clicked:

This program gives the average of 9 based on the values in the scores
array. This is because 10 + 12 + 7 + 6 + 10 = 45. This is then divided
by the size of the list (5) to give 9.

Potrebbero piacerti anche