Visual Basic Exit Statement
Visual Basic Exit Statement
In visual basic, the Exit statement is useful to terminate the execution of loops (for, while, do-while, etc.) and transfers
the control immediately to the next statements that follow a terminated loops or statements.
In visual basic, we can also use Exit statement in nested loops to stop or terminate the execution of inner loops based
on our requirements.
Now, we will see how to use Exit statement in for loop, while loop, do-while loop to terminate the execution of loops
in a visual basic programming language with examples.
Following is the example of terminating the execution of for loop with Exit statement.
Module Module1
Sub Main()
For i As Integer = 1 To 4
If i = 3 Then Exit For
Console.WriteLine("i value: {0}", i)
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above code, we used the Exit statement to terminate the for loop whenever the variable i value
equals 3.
When we execute the above visual basic program, we will get the result as shown below.
If you observe the above result, whenever the variable i value equals 3, the for loop execution automatically stops.
This is how we can use the Exit statement in for loop to terminate the execution of for loop based on our
requirements.
Following is the example of using Exit keyword in a while loop to terminate loop execution in a visual basic
programming language.
Module Module1
Sub Main()
Dim i As Integer = 1
While i < 4
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit While
End While
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, whenever the variable (i) value become 2, we are terminating the while
loop using Exit statement.
When we execute the above visual basic program, we will get the result as shown below.
This is how we can use the Exit statement with the while loop to terminate the execution of the loop based on our
requirements.
Following is the example of using Exit keyword in a do-while loop to terminate loop execution in a visual basic
programming language.
Module Module1
Sub Main()
Dim i As Integer = 1
Do
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit Do
Loop While i < 4
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, whenever the variable (i) value become 2, we are terminating the loop
using Exit statement.
We will get the following result when we execute the above visual basic program.
This is how we can use the Exit statement in the do-while loop to terminate the execution of the loop based on our
requirements.
This is how we can use the Exit statement in our visual basic applications to terminate the execution of loops or
statements based on our requirements.