VB .NET Chapter 4 An Introduction to Loops in VB .NET




An Introduction to Loops

There are three types of loop for us to cover with VB.NET: a For loop, a Do loop, and a While … End While loop. This last one is almost the same as a Do loop, and we won't be covering it here. But the other two types of loop come in very handy, and a lot of the time you can't programme effectively without using loops.

What is a Loop?

A loop is something that goes round and round and round. If someone told you to move your finger around in a loop, you'd know what to do immediately. In programming, loops go round and round and round, too. In fact, they go round and round until you tell them to stop. You can programme without using loops. But it's an awful lot easier with them. Consider this.
You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this
Dim answer As Integer
answer = 1 + 2 + 3 + 4
MsgBox answer
Fairly simple, you think. And not much code, either. But what if you wanted to add up a thousand numbers? Are you really going to type them all out like that? It's an awful lot of typing. A loop would make life a lot simpler.
But don't get hung up too much on the name of the Loop. Just remember what they do: go round and round until you tell them to stop.
We'll discuss the For Loop first.

For Loops in VB .NET


This first type of loop we'll look at is called a For Loop. It is the most common type of loop you'll use when you programme. We'll use one to add up our 4 numbers, and then discuss the code. Study the following. In fact, create a new Project. Add a button to your new Form. Double click your new button and type the following code for it:
Dim answer As Integer
Dim startNumber As Integer
answer = 0
For startNumber = 1 To 4
answer = answer + startNumber
Next startNumber
MsgBox answer
Run the programme, and see what happens when you click the button. The number 10 should have been displayed in your message box.

The For loop code

We start by setting up two integer variables. We set one of these to zero. Then we start our loop code. Let's examine that in more detail.
For startNumber = 1 To 4
answer = answer + startNumber
Next startNumber
We start our loop by telling Visual Basic what type of loop we want to use. In this case it is a Forloop:
For startNumber = 1 To 4
The next thing you have to do is tell Visual Basic what number you want the loop to start at:
For startNumber = 1 To 4
Here we are saying "Start the loop at the number 1". The variable startNumber can be called anything you like. A popular name to call a start loop variable is the letter i ( i = 1). So what we're doing is setting up a variable - the start of the loop variable - and putting 1 into it;
Next, you have to Tell Visual Basic what number to end the loop on:
For startNumber = 1 To 4
The To word, followed by a number or variable, tells Visual Basic how many times you want the loop to go round and round. We're telling Visual Basic to loop until the startNumber variable equals 4
The command that tells Visual basic to grab the next number in the sequence is this:
Next startNumber
When Visual Basic reaches this line, it checks to see what is in the variable startNumber. It then adds one to it. In other words, "Get me the next number after the one I've just used."
The next thing that happens is that Visual Basic will return to the word For. It returns because it's in a loop. It needs to know if it can stop looping. To check to see if it can stop looping, it skips the startNumber = 1 part, and then jumps to your end number. In our case, the end number was 4. Because Next startNumber adds one to whatever is in startNumber, then startNumber is now 2 (It was 1 at the start. The next number after one is ... ?).
So if startNumber is now 2, can Visual Basic stop looping? No it can’t. Because we’ve told it to loop until it reaches number 4. It’s only reached number 2, so off it goes on another trip around the loop. When the startNumber is greater than the end number, Visual Basic drops out of the loop and continues on it’s way.
But remember why we're looping: so that we can execute some code over and over again.
To clarify things, change the above code to this:
Dim startNumber As Integer
For startNumber = 1 To 4
MsgBox("Start Number = " & startNumber)
Next startNumber
Run the programme, and click your button. What happens? You should have seen this in the message box, one after the other:
Start Number = 1
Start Number = 2
Start Number = 3
Start Number = 4
Each time round the loop, the code for the message box was executed. You had to click OK four times - startNumber = 1 To 4.


Summary

So to sum up:
  1. A For loop needs a start position and an end position, and all on the same line
  2. A For loop also needs a way to get the next number in the loop
  3. A loop without any code to execute looks like this:
For i = startNumber To endNumber
Next i
The above code uses two variables for the start and end numbers. The start number for the loop goes directly into the variable called i. When Visual Basic wants the next number, it just add one to whatever is in the variable i. You could use it like this:
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
Msgbox i
Next i
Change the code for your button to that new code, and test it out. Study the code so that you understand what is going on.
For Loops might not be easier to understand than just typing answer = 1 + 2 + 3 + 4, but they are a lot more powerful if you want to add up a thousand numbers!

Exercise

Put two textboxes on your form. The first box asks users to enter a start position for a For Loop; the second textbox asks user to enter an end position for the For loop. When a button is clicked, the programme will add up the numbers between the start position and the end position. Display the answer in a message box. You can use this For Loop code
For i = startNumber To endNumber
answer = answer + i
Next i
Get the startNumber and endNumber from the textboxes.

Exercise H

Amend your code to check that the user has entered numbers in the textboxes. You will need an If statement to do this. If there's nothing in the textboxes, you can halt the programme with this code
Exit Sub
For this exercise, you will be passing whatever is in the textboxes to integer variables. It is these variables you are checking with your If Statement. Because numbers will be entered into the textboxes, remember to convert the text to a value with Val( ).
But the Text property will return a zero if the box is empty. So your If statement will need to check the variables for a value of zero. If it finds a zero, Then you can use the Exit Sub code. The If statement should come first, before the For Loop code.

This has been quite a long section, and you may need a breather! Don't worry if you don't understand all that in one sitting. Come back to it, and it will sink in - eventaully! In the next section, we'll take a look at Do Loops.



Do Loops in VB .NET

We saw with the For Loop that a specific number of times to loop was coded into it. We said:
For startNumber = 1 To 4
We knew that we only wanted to loop four times. But what if we don't know how many times around the loop we want to go? Later, we'll be opening text files and reading the data from them. If we used a For loop to get every line of text, we'd have to know before hand how many lines the text file held. A For Loop would not be very efficient in this case.
But a Do Loop would be. With a Do Loop we can use word s like "While" and "Until". And then we can say, "Go round and round the loop While there's still text to be read from the file." An example might make things clearer.
Load the form you created for the last exercise, the one that has two textboxes and a Button and tested your understanding of For loops.
Add another button to the Form. Your form might look something like this:
Loop Form
Double click the new button to open the code window, and then type the following code for the new button:
Dim number as Integer
number = 1
Do While number < 5
MsgBox number
number = number + 1
Loop
When you've finished, run the programme and see what happens. The numbers 1 to 4 should have displayed in your message box.
So the Do loop keeps going round and around. And when it gets to the top, it tests the "While" part - Do While number is Less Than 5. It's really answering a Yes or No question: is the number inside the variable called number Less Than 5? If it is Less Than 5, go round the loop again. If it's not Less than 5, Visual Basic jumps out of the Loop entirely.
You can add the "While ... " part to the bottom, just after the word "Loop". Like this:
Do
number = number + 1
Loop While number < 5
Try it and see what difference it makes.
None, right? But there is a difference between the two. With the "While ... " part at the bottom, the code above it gets executed at least once. With the code on the first line after the word "Do", the code might not get executed at all. After all, the number inside the variable might already be Greater Than 5. If it is, Visual Basic won't execute the code.


Do ... Until

You have another choice for Do Loops - Do ... Until.
There's not much difference between the two, but a Do ... Until works like this. Change your Loop code to the following:
Do Until number < 5
MsgBox number
number = number + 1
Loop
Run the code and see what happens.
Nothing happened, right? That's because we "Keep looping UNTIL the number in the variable called number is Less Than 5" The problem is, the number inside the variable is already Less Than 5. And if the number is Less than 5, then the code won't execute - because it has already met the end condition.
Change that Less Than sign to a Greater Than sign, and then test your code again. Now what happens?
The numbers 1 to 5 should have displayed. Again, the loop keeps going round and around testing to see if our end condition is met, in this case Is Greater Than 5. If the condition is met, VB breaks out of the Loop; if not, keep going round.
Change the Greater Than sign to Greater Than or Equal to ( >= ), and test it again. It should now print 1 to 4.
The "Until" part can go at the bottom, just after the word Loop. Like this
Do
MsgBox number
number = number + 1
Loop Until number >= 5
To sum up, use a Do Loop if you don't know what the end number is going to be, otherwise a For Loop might be better.

A Times Table Programme

Start a new project for this. Onto your new Form, place two textboxes and a Button. Set the Text property of Textbox1 to 1, and the Text property of Textbox2 to 10. Set the Text property of the Button to "Go".
When the Go button is clicked, the programme will put the numbers from the Textbox into two variables. We'll then put a value into a variable called multiplier. If you're doing the times tables, the format is
X multiplied by Y = Z
(2 multiplied by 3 = 6)
We'll use a For Loop to work out the X part; we'll get the Y part from a multiplier variable. We'll then display the results in something called a Listbox.
So add a List Box to your form. It looks like this in the toolbox:
The ListBox control in the VB NET toolbox
The form you design should look something like this one:
Times Table Form
A List box is similar to a Combo Box, in that you have a list of items that the user can select. Here, we're just using it display the results of our programme. We'll add items to the List box with our code, rather than in design time like we did for the Combo box.
So, here's the code for the entire programme. Double click your Go button, and add the following:
Dim number1 As Integer
Dim number2 As Integer
Dim multiplier As Integer
Dim answer As Integer
Dim i As Integer
number1 = Val(TextBox1.Text)
number2 = Val(TextBox2.Text)
multiplier = 2
For i = number1 To number2
answer = i * multiplier
ListBox1.Items.Add(i & " Times " & multiplier & " = " & answer)
Next i
When you've finished, run the programme and see how it works. You should see this appear in your List box:
List Box with 2 Times Table
Let's run through the code to see how it works.

The Times Table Code

As you can see from our last lesson, we've set up five Integer variables - number1, number2, multiplier, answer and i.
The next thing we did was to pass whatever is in our two Textboxes straight into the two variable, number1 and number2. The start number goes into textbox one, and the end number goes into textbox2.
number1 = Val(TextBox1.Text)
number2 = Val(TextBox2.Text)
In the next line of code, we set a starting value for the multiplier variable:
multiplier = 2
The next thing we had was a For Loop. The For Loop was this:
For i = number1 To number2
answer = i * multiplier
ListBox1.Items.Add(i & " Times " & multiplier & " = " & answer)
Next i
Remember: the number1 and number2 variables hold our numbers from the Textboxes. We set these to 1 and 10. So our first line of the For Loop is really this:
For i = 1 To 10
We're saying, "Start a For Loop". Whatever is in the variable called number1, make that the starting number for the Loop. Put this value into the variable called i. The end of the Loop will come when the variable called i has the value 10. Stop looping when you reach this value.
The next part of the code reads this:
answer = i * multiplier
This means, Put into the variable called answer the following sum: whatever is in the variable called i multiplied by whatever is in the variable called multiplier.

Finally, a word about the line that displays your text in the list box. It was this:
ListBox1.Items.Add(i & " Times " & multiplier & " = " & answer)
To add items to a list box with code, first you type the name of your list box:
ListBox1
Type a full stop and a drop down list will appear. Select Items from the list.
ListBox1.Items
Type another full stop and again a drop down list will appear. Select the Add Method
ListBox1.Items.Add
This method, not surprisingly, lets you add items to your list box. Whatever you want to add goes between a pair of round brackets:
ListBox1.Items.Add( )
In between the round brackets, we have this for our code:
i & " Times " & multiplier & " = " & answer
It might be a bit long, but there are 5 parts to it, all joined together by the concatenate symbol (&):
i
" Times "
multiplier
" = "
answer
The variable i holds the current value of the For Loop; " Times " is just direct text; multiplier holds the value we're multiplying by (our times table); " = " is again direct text; and answer is the answer to our times table sum.
If you want to clear the items from a List box you can do this. At the top of the code, enter this line:
ListBox1.Items.Clear()
So instead of selecting Add from the final drop down list, select Clear.

Exercise

Add another textbox to your form. This will represent the "times table". So far you have been getting this value directly from the code. For this exercise, get the multiplier value directly from the textbox. Add appropriate labels to all your textboxes.

The Basic Math Symbols in VB .NET

If you're doing any programming, you need to know how to use the basic Math symbols. The basic Math symbols in Visual Basic .NET are these:
+ The Plus sign adds numbers together
- The minus sign takes one number away from another
* The asterisk symbol, above the number 8 on your keyboard, is used to multiply
/ The forward slash on your keyboard is the divide by symbol
= The equals sign
A word or two about how to use the mathematical symbols in Visual Basic. You can use the operators by themselves:
answer = 8 + 4
answer = 8 - 4
answer = 8 * 4
answer = 8 / 4
Or you can combine them by using parentheses.
Here, Visual Basic will work out the sums in parentheses first, and then add the two sums together
answer = (8 - 4) + (4 -2)
answer = 4 + 2
answer = 6
But you've got to be careful with parentheses, because there is a strict order that VB uses when it's doing maths. Consider this sum:
answer = 8 - 4 + 4 + 2 * 2
Try that code behind a new button. Display the result in a MsgBox. What answer did you get? 12! It's wrong! But why?
You would think it would work out the sum like we do - left to right
8 - 4 = 4
+ 4 = 8
+ 2 = 10
* 2 = 20
But VB doesn't work it out like that. Visual basic will do the multiplying first. So it will calculate like this
2 * 2 = 4
8 - 4 + 4 = 8
8 + 4 = 12
To make sure Visual Basic does your sums correctly you have to be careful of the parentheses. Try changing the code to this:
answer = (8 - 4) + (4 + 2) * 2
Now what happens. That's right - you get 16! It's still wrong! At least it is if you are working from left to right. But Visual Basic isn't. It will do the (4 + 2) * 2 part first, and then add that to 8 - 4. Which gives you 16.
In order to force Visual Basic to get the sum right, you need even more parentheses. Try this code and see what happens:
answer= ((8 - 4) + (4 + 2)) * 2
Finally we get the answer we've been expecting - 20! The parentheses above have grouped our sums into separate sections, thereby forcing VB to do the sums in the right order.
So take care when using parentheses to do your sums: the order that Visual Basic does its sums does matter!

In the next section of the course, we'll have some fun adding menus to a Visual basic .NET form.

Comments