The loops is a subject often hard to understand by new programmers. I think it might have a link with the fact that they learn debugging too late. But we already have and this should make loops easier!
Our usual definition part! What is a loop? Sometimes you will want to execute one part of your code multiple times. That is exactly what a loop is used for. It’s a special block of code that gets executed while, until or for a certain amount of times according to a (or multiple) condition(S).
There are many types of loops, but the most common are For, While and Foreach. We are in luck! Visual Basic and C# implements all of them!
For (the classic loop)
The For loop has been used for a long time and is, in my opinion, one of the most versatile of them all. You can use it for a lot of situations. A simple example would be going through a table or a list while keeping in mind where you are in this table/list.
Here is the template we will use.
For (Index to count on at the first position) To (Target maximum number) Step (A count speed) 'Code to execute for the number of times specified Next
It can seem a bit complicated so here is our real example to illustrate better.
Option Strict On Option Explicit On Module Program Sub Main() 'Declaration and initialization Dim TableOfStudents = New String() {"Alexandre", "Daniel", "Maxime"} Dim TableOfMarks = New Integer() {80, 85, 90} Dim OutputString As String = String.Empty For Index As Integer = 0 To 2 Step 1 OutputString = String.Format("Student: {0} has a mark of: {1}", TableOfStudents.GetValue(Index), TableOfMarks.GetValue(Index)) Console.WriteLine(OutputString) Next Console.ReadKey() End Sub End Module
What is the first thing that seems different here? I merged the declaration and the initialization, that’s a little trick to make things faster, do I recommend it? I would say choose one method and stick to it, either you declare everything and initialize at the same time or you don’t for the whole project. What’s important is to stay consistent.
The second thing is the For statement. Index As Integer = 0 is the reason why I showed you the declaration and initialization at the same time in the first part. We declare a new Index variable of type Integer and we set it to 0. Why 0? Because our goal is to fetch both tables (TableOfStudents and TableOfMarks) at the same time and a table’s first index is 0, remember I told you that lots of things start with 0 in programming.
Wait what is a table?! A table is a special variable containing multiple values of a single type in memory. In this example we have a table of String and a table of Integer with values in it. Visually this is what it looks like.
[“Alexandre”, “Daniel”, “Maxime”]
[80, 85, 90]
Here is what it might look like at the memory address of the table.
Elements of the table are separated by a comma. In the first table, “Alexandre” is the element at position 0 in the table and it is of type String because the table is a table of String. “Daniel is the element at position 1, and so on. You can initialize as many elements as you want or give the table a fix length. But tables like this cannot be expanded technically.
We will have a look at tables in more details later, back to our loops! Our Index variable is going to start at 0 To 2 with steps of 1. Here is what Index is going to do each time Visual Basic goes through a loop.
0 – first execution
1 – second execution
2 – third execution
3? exit loop before it gets executed.
During all the executions, Index will be set to the current iteration. For example, if we are at the second execution, the value of Index will be? 1!
Then comes the execution block, in other words, what will be executed each time the loop is set to go and finally we have the Next statement which marks the end of the loop execution block.
Here is what I have as a result from executing the preceding code.
As for an explanation: each time visual basic goes through a loop, it takes, in both tables, the value at the Index position and displays it.
I suggest that you experiment with the for loop, create only one table with a certain amount of values and go through it while displaying the values in the console.
While!
The While loop can be very useful if you are not sure how many times you will have to loop. A classic example is reading a file where the number of lines remains unknown.
While template:
While Condition 'Execution End While
As you can see, it’s a little easier to visualize than the For loop, While a certain condition is meet, Visual Basic is going to stay in the loop indefinitely.
Also, you can turn this upside down by adding a Not before the condition which will make it While Not a certain condition is meet, I find that easier to understand this way but it all depends on what you find easier. Here is real example.
Option Strict On Option Explicit On Module Program Sub Main() 'Declaration and initialization Dim OutputString As String = String.Empty Dim Counter As Integer = 5 'While loop While Not Counter = 0 Counter -= 1 OutputString = String.Format("Counter value is: {0}", Counter) Console.WriteLine(OutputString) End While Console.ReadKey() End Sub End Module
What is going on in this code? I declare and initialize a Counter variable to 5. Then comes the While loop, while the value of Counter is not 0 (that’s how you read the line While Not Counter = 0), execute what is inside the loop block. My first step here is to remove 1 from the Counter variable which will make it 4 the next time While Not Counter = 0 will be checked. Then I simply output the value of Counter.
You can now execute the code and it should give you the output above. Why is it telling us that the value of Counter is 4 while we set it to 5 in first place? That’s because we remove 1 from the value before displaying it. Careful with the order of your code. If we move the remove 1 after we display the value of Counter, it’s going to start at 5 and finish at 1. You can try it out!
I don’t quite understand what Counter -= 1 does? Counter -= 1 is the same as writing Counter = Counter – 1.
Remember that you can chain multiple conditions like we did with the If statement with And and Or. Try to remove the Not and make the While do the exact same thing as it’s doing now.
Sub Main() 'Declaration and initialization Dim OutputString As String = String.Empty Dim Counter As Integer = 5 While Counter > 0 Counter -= 1 OutputString = String.Format("Counter value is: {0}", Counter) Console.WriteLine(OutputString) End While Console.ReadKey() End Sub
For Each (The easiest!)
Personally, I think this loop is the easiest and the most intuitive of them all. You might get addicted to this loop if you’re not careful!
ForEach goes like this: For Each element in a specific Array/Collection or whatever, execute a certain block of code. Here is the template.
For Each (Variable) As (Type) In (Array/Collection etc) 'Code to execute Next
The important part is that the Type of the variable you create must be the same as what is in the Array/Collection you want to fetch.
What is going to happen is that every time the loop turns, Visual Basic is going to put the current element in the variable for you to use in the code to execute.
For example, if my list contains “Alexandre”, “Daniel”, “Maxime”
First loop will set Alexandre in the variable,
Second loop will set Daniel in the variable, and so on.
Here is a real code example.
Option Strict On Option Explicit On Module Program Sub Main() 'Declaration and initialization Dim TableOfStudents = New String() {"Alexandre", "Daniel", "Maxime"} Dim OutputString As String = String.Empty 'ForEach loop For Each CurrentStudent As String In TableOfStudents Console.WriteLine(CurrentStudent) Next Console.ReadKey() End Sub End Module
You should put a break point at the line Dim OutputString As String = String.Empty and use step over (F11) to see what this loop does and don’t forget to put your mouse over CurrentStudent variable to constantly see its value. You should see that each time the code loops, the current value will be set to CurrentStudent. That’s what is really useful with the ForEach, you don’t have to handle anything else than the current value itself. No index or step etc.
More loop tools!
By tools, I mean that sometimes you will want to end the loop prematurely or simply skip a piece of the execution code. Continue and Exit are the two keywords you need. Continue will skip the rest of the code and go straight to the next loop check. Exit will end the loop right away.
Option Strict On Option Explicit On Module Program Sub Main() 'Declaration and initialization Dim TableOfStudents = New String() {"Alexandre", "Daniel", "Maxime"} Dim OutputString As String = String.Empty For Each CurrentStudent As String In TableOfStudents If CurrentStudent = "Daniel" Then Exit For End If Console.WriteLine(CurrentStudent) Next Console.ReadKey() End Sub End Module
You have to name what you want to Exit after the keyword, here we want to Exit the for loop only, that’s why we will put Exit For. If it was a While we would put Exit While. The same thing goes for Continue. In the code above, if the value of the CurrentStudent is Daniel, then we exit the ForEach completely.
The next exercise will be on loops! It is also an important subject we must make sure to understand perfectly. It does not only apply to Visual Basic, most if not all programming languages have loops.
In that case, it’s going to give the output below.
If you have any questions, feel free to post them in the comments and to check the Youtube channel associated with the tutorials! Sometimes it’s easier to understand when you can see it in action.
No Comments Yet!
You can be first to comment this post!