Nested Control Structures in Visual Basic 2008
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.)
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
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
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.
Table of Contents
W3computing.com Copyright 2011 © All Rights Reserved
|Home | Useful links | Contact us|