Get up to 80 % extra points for free! More info:

Lesson 6 - Loops in VB.NET

In the previous exercise, Solved tasks for Visual Basic .NET lesson 5, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on For and While loops in VB.NET instead of a thorough-full lesson? Here it is:

Using a For loop to execute code 3 times:

For i As Integer = 0 To 2 ' runs 3 times in total
    Console.WriteLine("Knock")
Next
Console.WriteLine("Penny!")
Console.ReadKey()

Accessing the loop control variable each iteration:

For i As Integer = 1 To 10
    Console.Write("{0} ", i) ' prints the current value of the loop control variable
Next
Console.ReadKey()

Nesting loops to work with tabular data:

Console.WriteLine("Here's a simple multiplication table using nested loops:")
For j As Integer = 1 To 10
    For i As Integer = 1 To 10
        Console.Write("{0} ", i * j)
    Next
    Console.WriteLine()
Next
Console.ReadKey()

Using a While loop when we don't know how many times the code is going to repeat:

Dim goOn As String = "yes"
While goOn = "yes"
    Console.WriteLine("Enter the first number:")
    Dim a As Double = Console.ReadLine()
    Console.WriteLine("Enter the second number:")
    Dim b As Double = Console.ReadLine()
    Console.WriteLine("Choose one of the following operations:")
    Console.WriteLine("1 - addition")
    Console.WriteLine("2 - subtraction")
    Console.WriteLine("3 - multiplication")
    Console.WriteLine("4 - division")
    Dim choice As Integer = Console.ReadLine()
    Dim result As Double = 0
    Select Case choice
        Case 1
            result = a + b
        Case 2
            result = a - b
        Case 3
            result = a * b
        Case 4
            result = a / b
    End Select
    If choice > 0 And choice < 5 Then
        Console.WriteLine("Result: {0}", result)
    Else
        Console.WriteLine("Invalid choice")
    End If
    Console.WriteLine("Would you like to make another calculation? [yes/no]")
    goOn = Console.ReadLine()
End While
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

Would you like to learn more? A complete lesson on this topic follows.

In the previous tutorial, Solved tasks for Visual Basic .NET lesson 5, we learned about conditions in Visual Basic .NET. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.

Loops

The word loop suggests that something is going to repeat. When we want a program to do something 100 times, certainly we'll not write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

The For loop

This loop has a determined fixed number of steps and contains a control variable, typically an integer, which changes values gradually during the loop. The for loop syntax is the following:

For variable As Integer = initialValue To finalValue [Step 1]
'Some commands...
Next
  • variable is the control variable which is set to an initial value (usually 0, because in programming, everything starts from zero, never from one). For example: i As Integer = 0. Of course, we could also create the variable somewhere above it. There is one of the few exceptions with variable declarations - we don't have to use the Dim keyword when declaring the variable in the loop. We usually use the name i for the control variable (as Index).
  • finalValue specifies how many times the loop will be executed (more precisely to what value the loop should count to). The commands in the loop are actually executed when the value of the control variable is <= finalValue. The finalValue is typically integer.
  • [Step] - The Step keyword is optional. If we omit it, the variable will be always incremented by 1 every step. If we specify the Step keyword followed by a value, we can specify which value will be added to the variable each step. We can add e.g. Step -1 to make the loop decrease the variable instead of increasing it. Of course, the finalValue would have to be lesser than the initialValue in this case so the loop would actually end. We don't write square brackets in the code, they just mean that the Step part is optional.

Let's create a simple example, most of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:

Console.WriteLine("Knock")
Console.WriteLine("Knock")
Console.WriteLine("Knock")
Console.WriteLine("Penny!")
Console.ReadKey()

However, using loops, we no longer have to copy the same code over and over:

For i As Integer = 0 To 2
    Console.WriteLine("Knock")
Next
Console.WriteLine("Penny!")
Console.ReadKey()

Console application
Knock
Knock
Knock
Penny!

The loop will run through 3 times. At the very beginning, i is set to zero, the loop then prints "Knock" and increases i by one. It continues in the same way with values one and two. Now, we can simply change value 2 to 9 in the loop declaration. The command will execute 10x without writing anything extra. Surely you can see that loops are a very powerful tool.

Now let's put the variable incrementation to use. We'll print the numbers from one to ten. Since we don't want our output to be on separate lines, we'll use the Write() method rather than WriteLine().

For i As Integer = 1 To 10
    Console.Write("{0} ", i)
Next
Console.ReadKey()

We can see that the control variable has a different value after each iteration (iteration is one step of the loop). Notice that this time, the loop doesn't start from zero because we want the initial value to be 1 and the last one to be 10. Just keep in mind that in programming, almost everything starts from zero, we'll find out why later.

Now let's print a simple multiplication table that contains multiples of numbers from 1 to 10. All we need to do is to declare a loop from 1 to 10 and multiply the control variable with the current multiplier. It might look like this:

Console.WriteLine("Here's a simple multiplication table using loops:")
For i As Integer = 1 To 10
    Console.Write("{0} ", i)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 2)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 3)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 4)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 5)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 6)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 7)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 8)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 9)
Next
Console.WriteLine()
For i As Integer = 1 To 10
    Console.Write("{0} ", i * 10)
Next
Console.ReadKey()

The result:

Console application
Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):

Console.WriteLine("Here's a simple multiplication table using nested loops:")
For j As Integer = 1 To 10
    Console.WriteLine()
    For i As Integer = 1 To 10
        Console.Write("{0} ", i * j)
    Next
Next
Console.ReadKey()

Makes a big difference, doesn't it? Obviously, we can't use i in both loops since they are nested and would count as a re-declaration. The variable j of the outer loop gains the values from 1 to 10. During each iteration of the loop, another inner loop with the variable i is executed. We already know that it'll write the multiples, in this case, it multiplies by the variable j. After each time the inner loop terminates it's necessary to break the line, it's done by Console.WriteLine(). You can try to align printed rows by using the PadLeft() method, so the numbers will be printed nicely in columns.

Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate an arbitrary power of an arbitrary number:

Console.WriteLine("Exponent calculator")
Console.WriteLine("===================")
Console.WriteLine("Enter the base: ")
Dim a As Integer = Console.ReadLine()
Console.WriteLine("Enter the exponent: ")
Dim n As Integer = Console.ReadLine()

Dim result = a
For i As Integer = 1 To n - 1
    result = result * a
Next
Console.WriteLine("Result: {0}", result)
Console.WriteLine("Thank you for using our exponent calculator")
Console.ReadKey()

I'm sure we all know how powers (exponents) work. But just to be sure, let me remind that, e.g. 2^3 = 2 * 2 * 2. So, we compute a^n by multiplying the number a by the number a for n-1 times. Of course, the result must be stored in a variable. Initially, it'll have a value of a and this value will be gradually multiplying during the loop. We can see that our result variable in the loop body is normally accessible. If, however, we create a variable in a loop body, this variable will be no longer accessible after the loop terminates.

Console application
Exponent calculator
==========================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator

Note: In VB.NET, we can also use the ^ operator. So we could replace the loop with this:

Console.WriteLine("Exponent calculator")
Console.WriteLine("===================")
Console.WriteLine("Enter the base: ")
Dim a As Integer = Console.ReadLine()
Console.WriteLine("Enter the exponent: ")
Dim n As Integer = Console.ReadLine()
Dim result = a ^ n
Console.WriteLine("Result: {0}", result)
Console.WriteLine("Thank you for using our exponent calculator")
Console.ReadKey()

Now, we know what some practical uses of the for loop are. Remember that it has a fixed amount of iterations. We shouldn't modify the control variable from inside the loop since the program could get stuck in an infinite loop. Here's the last example of what you should not do:

' this code is wrong
For i As Integer = 1 To 10
    i = 1
Next
Console.ReadKey()

Ouch, we can see that the program is stuck. The loop always increments the variable i, but it is always set back to 1. Meaning that it never reaches values > 10 and the loop never ends. Close the program window or use the Stop button in the Visual Studio toolbar.

The While loop

The While loop works differently, it simply repeats the commands in a block while a condition is true. The syntax of the loop is the following:

While condition
    'commands
End While

If you realized that the For loop can be simulated using the While loop, you are right :) The For loop is actually a special case of the While loop. However, the While loop is used for slightly different things. Typically, we call some method returning a logical True/False value, in the while loop condition. We could rewrite the original For-loop example to use the While loop instead:

Dim i As Integer = 1
While i <= 10
    Console.Write("{0} ", i)
    i += 1
End While
Console.ReadKey()

But this is not an ideal example of using the While loop. Let's take our calculator from previous lessons and improve it a little bit. We'll add an ability to enter more math problems. The program will not end immediately, but it'll ask the user whether they wish to calculate another math problem. Let's remind the original version of the code (this is the version with Select Case, but feel free to use the If-Else version, it depends on you):

Console.WriteLine("Welcome to our calculator")
Console.WriteLine("Enter the first number:")
Dim a As Double = Console.ReadLine()
Console.WriteLine("Enter the second number:")
Dim b As Double = Console.ReadLine()
Console.WriteLine("Choose one of the following operations:")
Console.WriteLine("1 - addition")
Console.WriteLine("2 - subtraction")
Console.WriteLine("3 - multiplication")
Console.WriteLine("4 - division")
Dim choice As Integer = Console.ReadLine()
Dim result As Double = 0
Select Case choice
    Case 1
        result = a + b
    Case 2
        result = a - b
    Case 3
        result = a * b
    Case 4
        result = a / b
End Select
If choice > 0 And choice < 5
    Console.WriteLine("result: {0}", result)
Else
    Console.WriteLine("Invalid choice")
End If
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

Now, we'll put almost all the code into a While loop. Our condition will be that the user entered "yes", so we'll check the content of a goOn variable. This variable will be set to "yes" at the beginning since the program has to begin somehow, then we'll assign the user's input to it:

Dim goOn As String = "yes"
While goOn = "yes"
    Console.WriteLine("Enter the first number:")
    Dim a As Double = Console.ReadLine()
    Console.WriteLine("Enter the second number:")
    Dim b As Double = Console.ReadLine()
    Console.WriteLine("Choose one of the following operations:")
    Console.WriteLine("1 - addition")
    Console.WriteLine("2 - subtraction")
    Console.WriteLine("3 - multiplication")
    Console.WriteLine("4 - division")
    Dim choice As Integer = Console.ReadLine()
    Dim result As Double = 0
    Select Case choice
        Case 1
            result = a + b
        Case 2
            result = a - b
        Case 3
            result = a * b
        Case 4
            result = a / b
    End Select
    If choice > 0 And choice < 5 Then
        Console.WriteLine("Result: {0}", result)
    Else
        Console.WriteLine("Invalid choice")
    End If
    Console.WriteLine("Would you like to make another calculation? [yes/no]")
    goOn = Console.ReadLine()
End While
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

The result:

Console application
Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140
Would you like to make another calculation? [yes/no]
yes
Enter the first number
-10.5
Enter the second number:

Our application can now be used multiple times and is almost complete. Note: this is one of the few codes that cannot be run online since our user bot would have to repeat inputs. In the next lesson, Solved tasks for Visual Basic .NET lesson 6, we'll show you how to sanitize user inputs. You've already learned quite a lot! Nothing better than a little noggin exercise, right? :)

In the following exercise, Solved tasks for Visual Basic .NET lesson 6, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 51x (317.75 kB)
Application includes source codes in language VB.NET

 

Previous article
Solved tasks for Visual Basic .NET lesson 5
All articles in this section
Visual Basic (VB.NET) Basic Constructs
Skip article
(not recommended)
Solved tasks for Visual Basic .NET lesson 6
Article has been written for you by Michal Zurek
Avatar
User rating:
3 votes
Activities