Professional Documents
Culture Documents
End if
If statement will evaluate the condition. If it is true, it will execute the statement(s) that follows it.
Otherwise, it will execute the statement(s) in else block.
if condition then
Statement1
Statement2
end if
If you use the above general form, The statements are executed when the condition is true. There is
no statement to execute when the condition is false.
The below syntax will exceute the false block when the condition is not true.
if condition then
Statement1
statement2
else
Statement3
statement4
end if
Example:
Module Module1
Sub Main()
Dim x As Integer
x = 10
If (x Mod 2) = 0 Then
Console.WriteLine("x is an even number")
Else
Console.WriteLine("x is an odd number")
End If
Console.ReadLine()
End Sub
End Module
If have multiple conditions to check, you can use the below form of the If stament:
If condition1 then
Statement1
statement2
Else If condition2 then
Statement13
statement24
Else
Statement15
statement6
End If
Example:
Module Module1
Sub Main()
Dim x As Integer
x = Integer.Parse(Console.ReadLine())
If x > 0 Then
Console.WriteLine("It is positive.")
Elseif x<0
Console.WriteLine("It is negative.")
Else
Console.WriteLine("It is zeo.")
End If
Console.Read()
End Sub
End Module
Module Module1
Sub Main()
Dim x As Integer
VB.NET Loops
Loops execute a block of code repeatedly while a condition is true. There are five types of loops in
VB.NET--For Next, For Each, While, Do While, and Do Until loops.
For Next loop
The For Next loop executes the statements from an initial value to the uper limit value. You
can use the Step keyword to specify the updating step of the loop.
Sub Main()
Dim i As Integer
'print numbers from 1 to 10 on the screen
For i = 1 To 10 Step 1
Console.WriteLine(i)
Next
Console.ReadLine()
End Sub
End Module
For Each loop
For Each loop is used to loop through a collection of items (e.g. array). Its general form is
shown below.
Sub Main()
'create and initialize the array
Dim arr() As Integer
arr=New Integer(2){}
arr(0) = 1
arr(1) = 2
arr(2) = 3
'loop through the array
For Each item In arr
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module
While loop
The while loop continuously executes statements as the condition is true. You must provide
end point for the loop, otherwise the statements will executed infinitely.
While condition
statements
End while
Example:
Module Module1
Sub Main()
Dim i As Integer
i = 1
'print numbers from 1 to 5 on the screen
While i <= 10
Console.WriteLine(i)
i = i + 1
If i > 5 Then
Exit While 'exit loop when i is greater than 5
End If
End While
Console.ReadLine()
End Sub
End Module
Do While loop
Syntax 1:
Do while condition
statements
loop
Example:
Module Module1
Console.WriteLine(i)
i += 1
Console.ReadLine()
End Module