Difference between revisions of "Visual Basic For Loops"

From Techotopia
Jump to: navigation, search
(Creating a Visual Basic For Loop)
(Creating a Visual Basic For Loop)
Line 8: Line 8:
 
...''VB Statements''...<br>
 
...''VB Statements''...<br>
 
'''Next''' ''counterVariable''<br>
 
'''Next''' ''counterVariable''<br>
 +
 +
The easiest way to gain an understanding of For loops is to see an example. The following code excerpt declares a variable to act as the loop counter and the performs a loop 5 times, displaying  the value of the counter on each loop iteration:
 +
 +
<pre>
 +
Dim intCount As Integer
 +
 +
For intCount = 0 To 5
 +
      MessageBox.Show("Counter is currently: " + CStr(intCount))
 +
Next intCount
 +
</pre>

Revision as of 18:01, 6 August 2007

Computers are incredibly good at repeating the same task over and over very quickly. One of the key functions of a programming language such as Visual Basic is to make it easy for a developer to program a computer to perform these repetitive tasks. Visual Basic provides a number of language structures which which tell a program to perform a task repeatedlyt, either a specific number of times, or until certain conditions are met. In this chapter of Visual Basic essentials we will look at each of these in detail.

Creating a Visual Basic For Loop

The Visual Basic For loop is ideal for situations wheer a task needs to be performed a specific number of times. For example, perhaps a value needs to be added to a variable 100 times. A Visual Basic For loop consists of a header, a code block and a next statement. The header copntains information about how many time the loop is to be performed, the code block contains the statements to be executed on each iteration and the next statement sends the loop back to the header to repeat. The syntax of a For loop is as follows:

For counterVariable = fromValue To toValue
...VB Statements...
Next counterVariable

The easiest way to gain an understanding of For loops is to see an example. The following code excerpt declares a variable to act as the loop counter and the performs a loop 5 times, displaying the value of the counter on each loop iteration:

Dim intCount As Integer

For intCount = 0 To 5
       MessageBox.Show("Counter is currently: " + CStr(intCount))
Next intCount