Wyo VB Lecture Notes
Objective #1: Use While loops.
- A While loop can be used to execute a block of code many times over and over. The loop below causes a message box to appear 4 times.
Dim num As Integer = 0
While (num <= 3)
MessageBox.Show("Hello World")
num = num + 1
End While
In the While loop above (num <= 3) is a control
expression just like the control expressions in If statements that you studied earlier in this course.
The statements
MessageBox.Show("Hello World")
num = num + 1
are considered the body of this loop since they are indented and placed between the While and the End While.
- The loop only iterates if the control expression is True. If the control
expression is True then VB executes the indented statements in the body of the loop. The body of the loop executes over and over again until the control expression becomes False. Each time a loop executes, it is called an iteration of the loop.
- When the control expression evaluates to False, the code inside the loop is not executed and the loop terminates. If the control expression never becomes false, the loop would execute forever. A loop that executes forever is called an infinite loop.
- For good style, you should indent the statements inside the body of the loop and you should place parentheses around the control expression for readability. You should always surround your loops with blank lines in your code. This makes your program easier to read and debug. That is, above all While and For loops
you should include a blank line and below all End While and Next statements, you should include a blank line. Blank lines used to make code easier to read are called white
space. Tabs and blank spaces that are also used for the same purpose of making white space.
Objective #2: Trace While loops.
- Here is an example of a While loop that adds up the numbers from 1 to 5
Dim num As Integer = 1
Dim sum As Integer = 0
While (num <= 5)
sum += num
num += 1
End While
The variable num will end up having the values: 1, 2, 3, 4, 5, 6
The variable sum will end up having the values: 1, 3, 6, 10, 15
- However the loop can be modified to add up the values from 1 to 10 by changing the 5 in the control expression to 10
Dim num As Integer = 1
Dim sum As Integer = 0
While (num <= 10)
sum += num
num += 1
End While
The loop can be modified to add the values from 5 to 10 by changing the initial value of num
Dim num As Integer = 5
Dim sum As Integer = 0
While (num <= 10)
sum += num
num += 1
End While
or the loop could be used to add up the even numbers between 2 and 10 by setting the initial value of num to 2 and changing one of the body statements
Dim num As Integer = 2
Dim sum As Integer = 0
While (num <= 10)
sum += num
num += 2
End While
- Here is an example of a While loop that determines how many years it would take to make $100 turn into $150 at a 5% interest rate compounded yearly.
balance = 100
years = 0
While (balance < 150)
balance = balance + balance * 0.05
years += 1
End While
Objective #3: Use sentinel values to control While loops.
Objective #4: Use flag variables to control While loops.
- A flag variable is
often used to store the value 1 (meaning True) or 0 (meaning False). The
programmer uses the flag variable as a way of controlling some process
in an algorithm. Flag variables are often used in While loops to send a signal
to the control expression. They are not used in For loops since a For loop executes a predetemined, definite number of times.
For example, in the code segment below gameIsOver is
used as a flag variable. It sends a signal to the control expression of
the loop if the user has scored enough points to end the game and exit
the loop. gameIsOver is
initially set to the value 0 which indicates False (the game is NOT over).
You should name flag variables appropriately. The variable should be named
in a way that it's name indicates a True condition. (For example, in the
segment below, you should not use a flag variable with the name, gameIsNotOver,
since it would probably make the logic of the algorithm harder for most
fellow programmers to follow.)
Dim gameIsOver As Integer = 0
While (gameIsOver = 0)
userPointsScored = userPointsScored + lastRoundScore
If (userPointsScored > 1000) Then
gameIsOver = 1
End If
End While
Often programmers use variables with the Boolean data
type as flag variables. A Boolean variable
can be set to either True or False.
Here is an example:
Dim
gameIsOver As Boolean = False
While (gameIsOver = False)
userPointsScored
= userPointsScored + lastRoundScore
If (userPointsScored > 1000)
Then
gameIsOver
= True
End If
End While
By using a Boolean variable
you can simplify the loops control expression to this:
While
(Not(gameIsOver))
Here's another example of a While loop that uses a flag variable. In this case, the flag variable has the Boolean data
type.
Dim outOfBounds As Boolean = False
While (outOfBounds = False)
picPlayer.Left = picPlayer.Left + 10
If (picPlayer.Left > 300) Then
outOfBounds = True
End If
End While
Objective #5: Know when to use While loops rather than For loops.
- A While loop should be used instead of a For loop
when you do not know the exact number of iterations that the loop must
make. If there is a situation in which some process must occur
over and over again within a loop but you do not know when exactly it will
end then you should use a While loop.
- Typically a While loop is used when a user provides input and the numbers or data that the user is inputs is unpredictable. For example, if a customer is making a number of purchases and the programmer does not know exactly how many items will be purchased beforehand. Or, if a user is moving an object across the screen but the programmer does not know exactly where the object will stop.
- A While loop is called an indefinite loop (or indeterminate
loop) because the programmer does not know beforehand exactly how many times it will iterate. Remember that a For loop is a
definite loop (or determinate loop) because a programmer can count how many times it will iterate based on its initial value, limit value, and step value.
- Technically though any For loop could be rewritten as a While loop and any While loop could be rewritten as a For loop. Consider this For loop
For J = 1 To 3
sum += J
Next
It could be rewritten as
While (J <= 3)
sum += J
J += 1
End While
Even this While loop that uses a sentinel value and a flag variable
While (Not (exitLoop))
num = InputBox("Enter a number: ")
If (num = -1) Then
exitLoop = True
Else
sum += num
End If
End While
could be rewritten as a For loop
For J = 1 to 2
num = InputBox("Enter a number: ")
If (num = -1) Then
J = 3
Else
sum += num
J -= 1
End If
Next
though this is horrible style since the control variable J is not being allowed to step to 2 as is meant with a For loop.
The bottom line is that if the user is inputing numbers and the programmer is not sure how many numbers will be inputed, the programmer should use an indefinite While loop along with a sentinel value and/or a flag variable.
If the programmer knows exactly how many loop iterations he/she is expecting to occur, he/she should use a definite For loop.