You can place, or nest, control structures inside other control structures (such as an If. . .Then block within a For. . .Next loop). Control structures in Visual Basic can be nested in as many levels as you want. The editor automatically indents the bodies of nested decision and loop structures to make the program easier to read.
When you nest control structures, you must make sure that they open and close within the same structure. In other words, you can’t start a For. . .Next loop in an If statement and close the loop after the corresponding End If. The following code segment demonstrates how to nest several flow-control statements. (The curly brackets denote that regular statements should appear in their place and will not compile, of course.)
For a = 1 To 100
{ statements }
If a = 99 Then
{ statements }
End If
While b < a
{ statements }
If total <= 0 Then
{ statements }
End If
End While
For c = 1 to a
{ statements }
Next c
Next a
Code language: VB.NET (vbnet)
I’m showing the names of the counter variables after the Next statements to make the code more readable. To find the matching closing statement (Next, End If, or End While), move down from the opening statement until you hit a line that starts at the same column. This is the matching closing statement. Notice that you don’t have to align the nested structures yourself; the editor reformats the code automatically as you edit. It also inserts the matching closing statement— the End If statement is inserted automatically as soon as you enter an If statement, for example.
Listing 3.6 shows the structure of a nested For. . .Next loop that scans all the elements of a two-dimensional array.
Listing 3.6: Iterating through a Two-Dimensional Array
Dim Array2D(6, 4) As Integer
Dim iRow, iCol As Integer
For iRow = 0 To Array2D.GetUpperBound(0)
For iCol = 0 To Array2D.GetUpperBound(1)
Array2D(iRow, iCol) = iRow * 100 + iCol
Debug.Write(iRow & ", " & iCol & " = " & _
Array2D(iRow, iCol) & " ")
Next iCol
Debug.WriteLine()
Next iRow
Code language: VB.NET (vbnet)
The outer loop (with the iRow counter) scans each row of the array. At each iteration, the inner loop scans all the elements in the row specified by the counter of the outer loop (iRow). After the inner loop completes, the counter of the outer loop is increased by one, and the inner loop is executed again — this time to scan the elements of the next row. The loop’s body consists of two statements that assign a value to the current array element and then print it in the Output window. The current element at each iteration is Array2D(iRow, iCol).
You can also nest multiple If statements. The code in Listing 3.7 tests a user-supplied value to determine whether it’s positive; if so, it determines whether the value exceeds a certain limit.
Listing 3.7: Simple Nested If Statements
Dim Income As Decimal
Income = Convert.ToDecimal(InputBox("Enter your income"))
If Income > 0 Then
If Income > 12000 Then
MsgBox "You will pay taxes this year"
Else
MsgBox "You won't pay any taxes this year"
End If
Else
MsgBox "Bummer"
End If
Code language: VB.NET (vbnet)
The Income variable is first compared with zero. If it’s negative, the Else clause of the If. . .Then statement is executed. If it’s positive, it’s compared with the value 12,000, and depending on the outcome, a different message is displayed. The code segment shown here doesn’t perform any extensive validations and assumes that the user won’t enter a string when prompted for her income.
The Exit Statement
The Exit statement allows you to exit prematurely from a block of statements in a control structure, from a loop, or even from a procedure. Suppose that you have a For. . .Next loop that calculates the square root of a series of numbers. Because the square root of negative numbers can’t be calculated (the Math.Sqrt method will generate a runtime error), you might want to halt the operation if the array contains an invalid value. To exit the loop prematurely, use the Exit For statement as follows:
For i = 0 To UBound(nArray)
If nArray(i) < 0 Then
MsgBox("Can't complete calculations" & vbCrLf & _
"Item " & i.ToString & " is negative! "
Exit For
End If
nArray(i) = Math.Sqrt(nArray(i))
Next
Code language: VB.NET (vbnet)
If a negative element is found in this loop, the program exits the loop and continues with the statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), the While loop (Exit While), the Select statement (Exit Select), and for functions and subroutines (Exit Function and Exit Sub). If the previous loop was part of a function, you might want to display an error and exit not only the loop, but also the function itself by using the Exit Function statement.