3.2.2 - Nested selection and iteration (VB.NET)

3.2.2 - Nested selection and iteration (VB.NET)

Trace control structures inside other control structures and use them to express repeated decisions. Native VB.NET code is written without Run; the optional Python demonstration explores a nested loop.

Selection within selection

Nested selection places an entire decision inside one branch of another decision.

VB.NET
If gameWon Then
    Console.WriteLine("Winner")
    If score > highScore Then
        highScore = score
        Console.WriteLine("New record")
    End If
Else
    Console.WriteLine("Try again")
End If

The inner comparison runs only if gameWon is true. For a win with score 20 and high score 15, the messages are Winner, then New record, and the stored high score becomes 20. A win with score 15 prints Winner only: equality does not beat the record. A loss prints Try again, even if its score exceeds the stored high score, because that path does not reach the inner test.

Follow the matching If/End If pair to identify each body. The Else above belongs to the outer decision. Indentation helps reveal this structure, but the native block endings define it. Replacing the two tests by one combined condition would need care: a simple combined test would omit the Winner message for wins that do not beat the record.

Iteration within iteration

A nested loop runs a complete inner loop for each pass through the outer loop.

VB.NET
For row As Integer = 1 To 2
    For column As Integer = 1 To 3
        Console.WriteLine(row & "," & column)
    Next
Next

The visited pairs are (1,1), (1,2), (1,3), (2,1), (2,2), (2,3). The inner counter begins at 1 again for the second row. There are 2 × 3 = 6 inner-body executions. Putting the loops one after another would instead give two separate sequences, not every row/column pair.

The loops need not have the same control type:

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account