How to Make a Loop in Visual Basic
- 1). Open Visual Basic and create a new console application. Click "File," "New Project." Choose "Windows" under "Visual Basic" in the tree view. Click "Console Application," "OK." The code window for the new console application will appear. Enter all code between the two lines shown below.
Sub Main()
' -- code goes here --
End Sub - 2). Create a For loop. This repeats a block of code while varying an index from one value to another. Enter the code as follows:
Dim i As Integer
For i = 2 To 10 Step 2
Console.Write(i)
Console.Write(" ")
Next
Console.WriteLine()
This loop varies the integer I from 2 to 10, stepping by 2. The loop repeats for the values 2, 4, 6, 8 and 10, each time printing the number to the console. After the loop completes, the console cursor is advanced to the next line. When run, the output appears as follows:
2 4 6 8 10 - 3). Create a While loop. This repeats as long as a condition is met. Enter the code as follows:
i = 1
While i <= 5
Console.Write(i)
Console.Write(" ")
i += 1
End While
Console.WriteLine()
In this example, the loop counts from 1 to 5. The index I is set to 1, then the while loop repeatedly prints the value of I to the console then adds 1. The while loop says that it will repeat while I is less than or equal to 5, so when I gets to 6, the loop stops. The output appears as follows:
1 2 3 4 5 - 4). Create a Do loop. This is similar to a
While loop but continues until a condition is met. A Do loop always runs at least once. Enter the code as follows:
i = 1
Do
Console.Write(i)
Console.Write(" ")
i += 1 Do
Loop Until i > 5
Console.WriteLine()
This example looks similar to the While loop but notice that the condition appears after the loop and that the loop repeats until the condition is met. The output is the same as the previous example.