VB Lecture Notes - Counter Statements
Objective #3: Use counter statements in For loops.
- A counter statement is an assignment statement that adds a fixed amount to a variable each time it executes. Usually a counter statement is found inside of
a loop. Here are some examples of counter statements:
count = count + 1
In the above assignment statement, the computer first adds 1 to the "old value" of the variable count. Then, the computer assigns
that new larger value to the same variable count. This type of counter statement can be very handy when allowing a program to run over and over again until the variable
gets to a certain size. For example, this could allow a computer game of PacMan give the user three lives and when he has been eaten the third time, the game knows to end.
However the value 1 doesn't have to be used in a counter statement. In these examples, other values are used....
score = score + 3
leftEdge = leftEdge - 10
The counter statement inside of this For loop counts the number of iterations of the loop...
Dim count As Integer = 0
For J = 1 To 5
sum = sum + 1
Next
The final value of sum is 5 and represents the number of iterations of the For loop.
- The verb to increment means to add one to a variable. So the statement count = count + 1 is
"increments" the variable count.
- A simpler way to write a counter statement is
count += 1
where the compound operator ( += ) is used as shorthand to the longer version of the statement. Other compound operators such as -= , *= , and /= can be used as well. For example the statement
count *= 2
will cause the variable count to be doubled each time it executes.
- A counter statement can be used inside of a loop to keep track of a running total. Unlike the version above, this version does not add the exact same increment to the
variable each time it is executed. It is useful therefore to keep a running total of things like points in a computer game or a bank balance in a banking program. For example, J is
added to the running total sum in
each loop iteration below and J varies on each loop iteration:
Dim sum As Integer = 0
Dim J As Integer = 0
For J = 1 To 5
sum = sum + J
Next