The If
statement evaluates a Boolean expression and executes one of two code blocks.
Dim score As Integer = 85
If score >= 90 Then
Console.WriteLine("Grade: A")
ElseIf score >= 80 Then
Console.WriteLine("Grade: B")
Else
Console.WriteLine("Grade: C or lower")
End If
Use Select Case
for multi‑way branching based on a single expression.
Dim day As String = "Saturday"
Select Case day
Case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
Console.WriteLine("Weekday")
Case "Saturday", "Sunday"
Console.WriteLine("Weekend")
Case Else
Console.WriteLine("Invalid day")
End Select
The Loop
statement repeats a block of code until a condition is met.
Dim i As Integer = 0
Do
Console.WriteLine(i)
i += 1
Loop While i < 5
Two forms for pre‑condition and post‑condition loops.
' While loop (pre‑test)
Dim count As Integer = 0
While count < 3
Console.WriteLine("Count: " & count)
count += 1
End While
' Do...Loop Until (post‑test)
Dim n As Integer = 0
Do
Console.WriteLine("n = " & n)
n += 1
Loop Until n = 3
Iterate a known number of times.
For i As Integer = 1 To 5
Console.WriteLine("Iteration " & i)
Next
Handle exceptions with structured error handling.
Try
Dim number As Integer = Integer.Parse("ABC")
Catch ex As FormatException
Console.WriteLine("Invalid number format.")
Finally
Console.WriteLine("Attempt completed.")
End Try
Jump to a labeled line within the same procedure. Use sparingly.
Dim x As Integer = 5
If x > 0 Then GoTo Positive
Console.WriteLine("Zero or negative")
Exit Sub
Positive:
Console.WriteLine("Positive number")
This program demonstrates multiple control‑flow constructs together.
Module ControlFlowDemo
Sub Main()
Dim numbers() As Integer = {2, 5, 8, 3, 9}
Console.WriteLine("Processing numbers...")
For Each n In numbers
If n Mod 2 = 0 Then
Console.WriteLine($"{n} is even")
ElseIf n > 5 Then
Console.WriteLine($"{n} is odd and greater than 5")
Else
Console.WriteLine($"{n} is odd")
End If
Next
Dim choice As String = "B"
Select Case choice
Case "A"
Console.WriteLine("Choice A")
Case "B"
Console.WriteLine("Choice B")
Case Else
Console.WriteLine("Other choice")
End Select
Dim i As Integer = 0
Do While i < 3
Try
Dim result As Integer = 10 \ i
Console.WriteLine($"Result: {result}")
Catch ex As DivideByZeroException
Console.WriteLine("Cannot divide by zero.")
End Try
i += 1
Loop
Console.WriteLine("Done.")
End Sub
End Module