Conditional Statements and Loops in VB


The If . . . Then statement

The If . . . Then statement evaluates whether or not an expression is true. The construct is used as follows:

If ConditionToCheck Then Statement

The program examines a condition (ConditionToCheck) , which can be a simple expression or a combination of expressions. If ConditionToCheck evaluates to true, the program will execute Statement. Any number of statements can be executed following the Then keyword. If only one statement is to be executed, the If . . . Then statement can be written on one line, as shown above. If a number of statements are to be executed, each statement should appear on a separate line, as shown below.

If ConditionToCheck Then
  Statement 1
  Statement 2
  ...........
  Statement n
End If

Note the use of the End If keywords to terminate this construct.


Exercise

  1. Create a new Visual Basic project called "Constructs"
  2. Right-click the form and click View Code
  3. Select Form1 Events using the drop-down list at the top of the code editor window
  4. Select the Click event using the drop-down list at the top of the code editor window.
  5. Implement the event handler as follows:

Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
  If BackColor <> Color.Red Then
     BackColor = Color.Red
     Exit Sub
  End If

  If BackColor = Color.Red Then
     BackColor = Color.Blue
     Exit Sub
  End If
End Sub

Run the application and test it by clicking anywhere in the form to toggle the form's background colour between blue and red.


The If . . . Then . . . Else statement

This construct offers two alternative courses of action. The first alternative is chosen if the specified condition is true, otherwise the second alternative is chosen. The construct is used as follows:

If ConditionToCheck Then
  Statement1
Else
  Statement 2
End If


Exercise

Reopen the Constructs project if you have closed it, and change the form's Click event as follows:

Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
  If BackColor = Color.Red Then
     BackColor = Color.Blue
  Else
     BackColor = Color.Red
  End If
End Sub

This code does exactly the same as the previous example, but in a slightly different way. Run the application and test it by clicking anywhere in the form to toggle its colour.


The If . . . Then . . . ElseIf statement

This construct is similar to If . . . Then . . . Else, except that it offers a number of choices. The construct is used as follows:

If Condition1 Then
  Statement1
ElseIf Condition2 Then
  Statement2
  .
  .
ElseIf Conditionk Then
  Statementk
End If

The program will examine each condition in turn until it finds a condition that is true. Once a true condition is found, and its statement has been executed, the program terminates the conditional search at End If. If none of the conditions are true, a default condition can be provided by adding a final Else section. The default condition must be the last in the list, and its associated statement will be executed only if none of the other conditions are true.


Exercise

Reopen the Constructs project if you have closed it, and change the form's Click event as follows:

Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
  If BackColor = Color.Red Then
     BackColor = Color.Blue
  ElseIf BackColor = Color.Blue Then
     BackColor = Color.Green
  ElseIf BackColor = Color.Green Then
     BackColor = Color.Black
  Else
     BackColor = Color.Red
  End If
End Sub

Run the application and test it by clicking anywhere in the form to cycle its colour.


The Select Case statement

If there are a large number of conditions to be tested, an alternative approach is to use the Select Case statement. The construct used is as follows:

Select Case Expression
  Case Expression1
     Statement1
  Case Expression2
     Statement2
  Case Expressionk
     Statementk
End Select

The condition described by Expression is evaluated, and compared with each of the expressions (Expression1, Expression2 etc.) that follow. Once a match is found, the corresponding statement is executed. If none of the stated conditions are true, a default condition can be provided by adding a Case Else statement at the end of the list.


Exercise

Reopen the Constructs project if you have closed it, and change the form's Click event as follows:

Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
  Select Case BackColor
     Case Color.Red
        BackColor = Color.Blue
     Case Color.Blue
        BackColor = Color.Green
     Case Color.Green
        BackColor = Color.Black
     Case Else
        BackColor = Color.Red
  End Select
End Sub

Run the application and test it by clicking anywhere in the form to cycle its colour.


The Do While . . . Loop statement

A loop is a programming construct that is used to carry out an action repeatedly. Visual Basic provides a number of loop constructs. The first loop construct we will examine is the Do While . . . Loop, which examines a condition and executes the statement (or statements) within the loop if the condition is true, after which it will examine the condition once more.

As long as the condition remains true, the statement will continue to be executed and the condition re-examined. If the condition is false when the loop begins, the statement will never execute. Otherwise, once the condition becomes false, the program will exit the loop and the statement will not be executed again. Care must be taken to ensure that a false condition can exist at some point, or the program will be stuck in a loop it cannot break out of.

The construction of this loop is as follows:

Do While Condition
  Statement (s)
Loop


The Do . . . Loop While statement

The Do . . . Loop While construct is similar to the Do While . . . Loop construct, except that the statement(s) within the loop will always execute at least once, because the condition is not tested until the end of the loop.

The construction of this loop is as follows:

Do
  Statement (s)
Loop While Condition


Exercise

Reopen the Constructs project if you have closed it, and change the form's code as shown below. The code demonstrates the use of both the Do While . . . Loop construct and the Do . . . loop While construct. Note that we have added a timer subroutine that takes a number of ticks as its argument. Microsoft defines a tick as an interval of 100 nanoseconds.

Sub myTimer (Interval As Long)
  Dim StartTime As New DateTime ()
  Dim EndTime As New DateTime ()
  Dim TimeElapsed As Long

  TimeElapsed = 0
  StartTime = DateTime.Now ()
  Do While TimeElapsed < Interval
     EndTime = DateTime.Now ()
     'get time elapsed in 100 nanosecond intervals
     TimeElapsed = EndTime.Ticks () - StartTime.Ticks ()
  Loop
End Sub

Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
  Dim GreyScale As Integer
  BackColor = Color.Black

  Do
     BackColor = Color.FromArgb (GreyScale, GreyScale, GreyScale)
     Me.Refresh ()
     GreyScale = GreyScale + 1
     myTimer (1000000) 'one tenth of a second
  Loop While GreyScale < 255

  MsgBox ("Cycle complete.")

End Sub

Run the application and test it by clicking anywhere in the form. The form's background color should slowly fade from black to white. Note that the value passed to the myTimer() function represents a multiple of 100 nanoseconds and determines the time taken to complete the loop.


The Do Until . . . Loop statement

The Do Until . . . Loop construct is virtually identical to the Do While . . . Loop construct except that the statement(s) within the loop are executed only while the condition is false.

The construction of this loop is as follows:

Do Until Condition
  Statement(s)
Loop


The Do . . . Loop Until statement

The Do . . . Loop Until construct is virtually identical to the Do . . . Loop While construct, except that the statement(s) within the loop are executed only while the condition is false. As with the Do . . . Loop While construct, the statement(s) within the loop will always execute at least once, because the condition is not tested until the end of the loop.

The construction of this loop is as follows:

Do
  Statement(s)
Loop Until Condition


The For ... To ... Next loop

The keyword For indicates the start of a counting loop. Counting loops are used to execute a statement (or series of statements) a specific number of times. The first kind of counting loop we shall look at is the For . . . To . . . Next loop.

The construction of the For . . . To . . . Next loop is as follows:

For Counter = Start To End
  Statement(s)
Next

Execution of the loop begins with Counter set to the value specified by Start, and examines whether this value is greater than the value specified by End. If not, any statements within the loop are executed, and the value of Counter is incremented by 1.

This process continues until the value of Counter becomes equal to the value of End, at which point execution of the loop stops. A variation on the counting loop uses the Step keyword to set the value by which Counter is incremented each time through the loop by a specified value, as shown below.

For Counter = Start To End Step Increment
  Statement(s)
Next Counter


Exercise

Reopen the Constructs project if you have closed it, and change the form's code as shown below. The code does exactly the same thing as the previous example, but this time it uses the For . . . To . . . Next counting loop.

Sub myTimer (Interval As Long)
  Dim StartTime As New DateTime ()
  Dim EndTime As New DateTime ()
  Dim TimeElapsed As Long

  TimeElapsed = 0
  StartTime = DateTime.Now ()

  Do While TimeElapsed < Interval
     EndTime = DateTime.Now ()
     'get time elapsed in 100 nanosecond intervals
     TimeElapsed = EndTime.Ticks () - StartTime.Ticks ()
  Loop

End Sub

Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
  Dim GreyScale As Integer

  BackColor = Color.Black

  For GreyScale = 0 To 255
     BackColor = Color.FromArgb (GreyScale, GreyScale, GreyScale)
     Me.Refresh ()
     myTimer (1000000) 'one tenth of a second
  Next GreyScale

  MsgBox ("Cycle complete.")
End Sub