Working with Loops, Arrays, and Collections in VBNET Game Development
(Page 1 of 4 )
This is the fifth article of a nine part series that teaches VB.NET via the development of a text-based game. The last article started the discussion of loops, specifically the While loop and the Do loop. This article will complete the discussion of loops and also go over arrays and collections. Please join us as we continue our journey.
For...Next
Loops are commonly used to loop a set number of times. You're probably familiar with the for loop in other languages. The for loop iterates over a set of numbers. This can allow you to perform some sort of operation on a specific range of numbers, or it can allow you to loop over a set of instructions a set number of times. Either way, it's extremely useful, and Visual Basic, of course, has its own implementation of it in the For ...Next structure.
Visual Basic's For loop is fairly straightforward -- more straightforward, perhaps, than other languages' implementations. We define the counter variable, giving it an initial value, and then we specify an end value. After each iteration of the loop, the counter variable will be incremented, and when it reaches the end value, execution will skip to the next line after the loop. For example, let's write the first hundred numbers out to the console:
For i As Integer = 1 To 100
Console.WriteLine(i)
Next
There's not much to say about the above code. Again, it's fairly straightforward. One more thing we can do with the For loop is specify the step. The step is simply the value that the counter is incremented by after each iteration. For example, we can modify the above code to display only odd numbers, which is done by specifying a step of two:
For i As Integer = 1 To 100 Step 2
Console.WriteLine(i)
Next
The step doesn't have to be positive, either. If we want, instead of incrementing the counter, we can decrement it by simply specifying a negative step. Let's count backward from one hundred to one:
For i As Integer = 100 To 1 Step -1
Console.WriteLine(i)
Next
So far, we've defined the counter as an Integer . However, it's possible to use any object that supports greater-than comparison, less-than comparison, addition and subtraction. For example, let's make our counter a Double:
For i As Double = 1 To 100 Step 0.5
Console.WriteLine(i)
Next
Next: For Each...Next >>
More Visual Basic.NET Articles
More By Peyton McCullough