1.
'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)
WHILE Loops
A while loop is known as a condition controlled loop, you should use it when you do not know how
many times the code needs to repeat as you can say repeat while a condition is True.
Dim userentry As String = "y"
WHILE Loops
A while loop is known as a condition controlled loop, you should use it when you do not know how
many times the code needs to repeat as you can say repeat while a condition is True.
Dim userentry As String = "y"
While userentry <> "n"
userentry = InputBox("Play again? y/n")
End While
MessageBox.Show("Game over")
This is what happens when the button is clicked:
How the while loop works
there is a condition after the word while, it works like an if condition. while the
variable userentry is not equal to n the code inside the loop (that is indented) will repeat
when n is entered by the user, the loop will end and it will continue with the code after the
loop. In this case it will display a message box saying “Game Over”.
While userentry <> "n"
userentry = InputBox("Play again? y/n")
End While
MessageBox.Show("Game over")
This is what happens when the button is clicked:
How the while loop works
there is a condition after the word while, it works like an if condition. while the
variable userentry is not equal to n the code inside the loop (that is indented) will repeat
when n is entered by the user, the loop will end and it will continue with the code after the
loop. In this case it will display a message box saying “Game Over”.
Example 12.3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your
message?", "Message Entry Form", "Enter your messge here",
500, 700)
If userMsg <> "" Then
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub
The inputbox will appear as shown in the figure below when you press the
command button
Figure 12.2 The InputBox