Example programs
Here are a few worked examples. To be improved and added to soon.
This program displays "What is the capital of X?" questions in a random order. This example has only 4 questions but that can obviously be increased. It ensures that a questions are not repeated (but it doesn't necessarily use the most efficient approach).
Dim countries(3) As String
Dim capitals(3) As String
Dim guess As String = ""
Dim score As Integer = 0
Dim used(3) As Boolean
Dim chosen As Integer = 0
'initialise arrays
countries(0) = "Scotland"
countries(1) = "France"
countries(2) = "Norway"
countries(3) = "England"
capitals(0) = "Edinburgh"
capitals(1) = "Paris"
capitals(2) = "Oslo"
capitals(3) = "London"
'initialise used array - loop through it and set every index to false
For counter = 0 To 3
used(counter) = False
Next
'seed the random number generator
Randomize()
'Start loop from 0 to 3 - this is how many questions we'll be asked
For counter = 0 To 3
'repeat - start looping until we find a question which hasn't been used yet
Do
'this generates a random number from 0 to 3
chosen = Int(Rnd() * 4)
'keep choosing random numbers until we get a question which hasn't been used yet
Loop Until used(chosen) = False
'mark that question as used
used(chosen) = True
'display question and get guess from user
guess = InputBox("What is the capital of " & countries(chosen) & "?")
'check if guess is correct
If guess = capitals(chosen) Then
'display message and add 1 to score
MsgBox("Correct")
score = score + 1
Else
MsgBox("Incorrect")
End If
'end of loop
Next
MsgBox("You got " & score & " questions correct")
Password verification
show
This program asks the user to enter a new password (minimum 8 characters in length) then verify it by re-entering. If the two passwords don't match then the user is asked to re-enter them.
'declare local variables
Dim password1 As String = ""
Dim password2 As String = ""
'start of conditional loop - keep going until the user has input 2 matching passwords
Do
'input validation for first input of password
'make sure it's at least 8 characters long
Do
password1 = InputBox("Enter your new password")
'if it's less than 8 chars long then display error message
If Len(password1) < 8 Then
MsgBox("Please re-enter. Your password must be at least 8 characters")
End If
Loop Until Len(password1) >= 8
'get user to re-enter password
password2 = InputBox("Please confirm your new password")
'check if passwords match
If password1 <> password2 Then
MsgBox("Your passwords didn't match. Please start again.")
End If
Loop Until password1 = password2
'passwords match so display message
MsgBox("Password accepted")