Visual Basic/Control Structures and Logical Expressions
- This lesson is part of the course on Visual Basic. Previous lesson: Variables and Types in VB6. Next lesson: Functions and Subroutines in VB6.
This lesson will cover the most fundamental elements of every Visual Basic program--control structures and logical expressions. Before reading any further, please review the lesson on Control structures from the Introduction to Computer Science, as you will need to understand what is meant by control structures in order to get anything out of this lesson. Please also ensure that you have read and understood Introduction to VB6 and Variables and Types in VB6 before proceeding.
Overview[edit | edit source]
"Control Structures and Logical Expressions"--wow, what a terrifying title! This should not, however, be a terrifying topic; rather, it's actually quite simple to understand. Basically, what the title can be simplified to is: "How to make your programs do more than one thing."
Up until now, you have learned how to develop VB6 applications that store values, perform mathematical computations on these values, and display the results of these computations--all of which is swell and dandy, but no more useful than your average calculator. What if you want, for instance, to determine if a number is odd, to find the factorial of a number, or to generate the Fibonacci Series? None of these tasks can be done through simple arithmetic, but rather they require something known as control structures.
Control structures in Visual Basic take two primary forms: if-statements and loops. With an if-statement, you can evaluate an expression, and perform one task if that expression is True and perform another if it's False. This allows your program to respond differently to different values and inputs, which allows for far more advanced calculations and a far wider range of possible behaviors. Loops, on the other hand, allow you to repeat the same task a given number of times, making it possible to go far beyond basic arithmetic to achieve goals such as calculating the Fibonacci series.
Logical Expressions and Operators[edit | edit source]
Before we can proceed to learning about if-statements, we must first learn about logical expressions in Visual Basic. In Variables and Types in VB6 you learned about a type of variable called a Boolean, which has only two possible values: True and False. A Boolean value can be defined explicitly using
bl = True, but this usage of Booleans is rare and not particularly useful. The more common application of a Boolean is in evaluating a logical expression, any expression which can be evaluated as either True or False.
A typical logical expression in Visual Basic takes the following form:
<Boolean> = P <Operator> Q. P and Q can be either constants, variables, or logical expressions themselves. The <Operator> is a logical or comparative operator, anything that performs a comparison between P and Q and returns a Boolean value. Here's an example of a logical expression in Visual Basic:
Public Sub Main() Dim B As Boolean Dim P As Integer, Q As Integer P = 5 Q = 7 B = (P = Q) MsgBox B End Sub
In this example, we used the logical operator of equality, denoted by the "=" sign. This operator returns True if P is equal to Q and False if it does not. In this example, B is False because P (5) does not equal Q (7). The parentheses, though not needed, are placed around
P = Q to make clear that this is a logical expression, rather than some form of assignment.
Now, let's take a look at a few other logical operators in Visual Basic. Please note that these are not anywhere near all of the comparison and logical operators available in Visual Basic, but they are the ones you'll use most frequently.
Comparison Operators[edit | edit source]
The following operators are all comparison operators, meaning that they compare one expression to another and return a Boolean. They are all overloaded, meaning that their left-hand and right-hand expressions can be of (almost) any type.
Equality "="[edit | edit source]
As you saw in the example above, the equality operator is denoted by an equals sign ("="). This operator can be quite confusing because it is both an assignment operator and a logical operator. The distinction between whether it is acting as a logical or an assignment operator is made solely upon context--if a line begins with a variable, followed by an equals sign, followed by an expression, then the equals sign is treated as an assignment operator, meaning that the value of the following expression is written to the variable. If it is found anywhere else in a program, then it is treated as a logical operator.
- Syntax: P = Q
- Returns: True if P is equal to Q, and False if it is not.
Inequality "<>"[edit | edit source]
This operator is synonymous with:
(P = Q) = False. In this format,
(P = Q) is the left hand expression, and
False is the right hand expression, which is evaluated for equality. If
(P = Q) is True, then (True = False) is false, but if
(P = Q) is True, then (True = True) is True.
- Syntax: P <> Q
- Returns: True if P is not equal to Q, and False if P is equal to Q.
Greater Than ">"[edit | edit source]
- Syntax: P > Q
- Returns: True if P is greater Q, and False if P is less than or equal to Q.
Less Than "<"[edit | edit source]
- Syntax: P < Q
- Returns: True if P is less than Q, and False if P is greater than or equal to Q.
Greater Than Or Equal To ">="[edit | edit source]
- Syntax: P >= Q
- Returns: True if P is greater than or equal to Q, and False if P is less than Q.
Less Than Or Equal To "<="[edit | edit source]
- Syntax: P <= Q
- Returns: True if P is less than or equal to Q, and False if P is greater than Q.
Logical Operators[edit | edit source]
The following operators are logical operators that can take only Boolean values as arguments; this means that both P and Q can each be only true or false. Keep in mind that the evaluation of every logical expression returns a Boolean, thus P and Q can also be logical expressions.
While this lesson will not go into this in depth, all of these operators can also be used as bitwise operators, in which case they do not require that the expressions be Boolean, nor do they truly return Boolean. For the time being, please only use them as logical operators, as it will save you many headaches.
Negation "Not"[edit | edit source]
This operator does not take the standard form of
P <operator> Q. Instead it is a single-argument operator, that takes only one Boolean expression. The negation operator ("Not") quite simply returns the opposite of the given Boolean expression--it is synonymous with
(P = False).
- Syntax: Not P.
Conjunction "And"[edit | edit source]
The Conjunction operator ("And") takes two or more Boolean expressions and returns true if both expressions are True.
- Syntax: P And Q
|P||Q||P And Q|
Disjunction "Or"[edit | edit source]
The Disjunction operator ("Or") takes two or more Boolean expressions and returns true if any of them is True.
- Syntax: P Or Q
|P||Q||P Or Q|
Exclusive Disjunction "Xor"[edit | edit source]
The Exclusive Disjunction, also known as "exclusive or", operator ("Xor") takes two Boolean arguments and returns true if one, and only one, of them is True.
- Syntax: P Xor Q
|P||Q||P Xor Q|
If-Statements[edit | edit source]
As you learned about in Control structures, the If-Then statement is the most simplistic and widely used form of flow control. In short, an If-Statement evaluates a logical expression, performs one task if that expression is True, and does either nothing or performs a seperate task if it is False. And so how do we write one in Visual Basic?
If-Statements in both VB6 and BASIC fall under three categories: the simple If-Then statement, the If-Then-Else statement, and the If-Then-ElseIf statement. If-statements may be nested inside of any other control block, including inside of other If-Statements. Nesting will be covered in depth later.
The If-Then Statement[edit | edit source]
VB6 uses the same simplistic and easily comprehendible syntax for If-Then Statements as BASIC. The If-Then Statement can be written two ways:
If <Expression> Then <Line of code to execute> --OR-- If <Expression> Then <Multiple lines of code to execute> End If
The <Expression> parameter can be any Boolean value or logical expression. If the code you want to execute when <Expression> is True can fit on one line, then you can write the entire If-Then statement on one line with no enclosing "End If".
The If-Then-Else Statement[edit | edit source]
But now what if you want certain code to be executed when the expression you are evaluating is true and certain code to be executed when the expression is false? You could of course write:
If a Then MsgBox "A is True!" If Not a Then MsgBox "A is False!"
But instead of having to write that every time, VB6 provides an additional "Else" clause for your If-Statements. The usage is very simple:
If <Expression> Then <Code to execute if True> Else <Code to execute if False> End If
One Step Further: ElseIf[edit | edit source]
Okay, so now that you can perform two different actions depending upon a variable's state, but what if that's just not enough? That's why VB6 also has an ElseIf statement, which has the following syntax:
If <Expression1> Then <Code to execute if Expression1 is True> ElseIf <Expression2> Then <Code to execute if Expression1 is False and Expression2 is True> ElseIf <Expression3> Then <Code to execute if Expression1 and Expression2 are False, but Expression3 is True> Else <Code to execute if neither Expression1, Expression2 nor Expression3 is True> End If
You can use as many Else-If statements as you want, though you may have no more than one Else statement for every If statement.
Examples[edit | edit source]
So now that we know everything we need to know to begin using If-Statements in our code, let's look at some examples.
Public Sub Main() Dim S1 As String, S2 As String S1 = "Foo" S2 = "BAR" Dim X As Integer X = 0 If X < 5 Then Debug.Print "X is less than 5" If X > 3 Then Debug.Print "X is greater than 3." Else X = 3 Debug.Print "The value of X was changed from 0 to 3" End If If S1 = "FOO" Then If S2 <> "BAR" Then Debug.Print "S2 is not BAR." ElseIf (X > 0 And X <= 3) And (S2 = "BAR") Then Debug.Print "X is greater than 0 and less than or equal to 3, and S2 = 'BAR'." ElseIf X = 3 Then Debug.Print "X is 3 and S2 is not BAR." Else End End If End If End Sub
Loops[edit | edit source]
Now let's return to our original problem of generating the Fibonacci series. Its formula is relatively simple:
- Let x = 1, let y = 0.
- Print x.
- Let x = y + x
- Let y = x - y
- Repeat from 2.
This pseudo code will print out: 1, 1, 2, 3, 5, 8, 13, 21, ... as expected. But now how do we tell a Visual Basic program how to do this? The answer lies in using loops.
Loops provide the ability to repeatedly execute the same block of code, and to each time change values such that each run through the loop produces different results. Visual Basic provides four main kinds of loops: the classic Do-Loop, the Do-Until Loop, the Do-While Loop, and the For-Next Loop.
Do-Loops[edit | edit source]
The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple:
Do <Code to execute> Loop
This, quite simply, executes the block of code, and when it reaches
Loop, returns to the beginning of the Do Loop and executes the same block of code again. The same block of code will be repeatedly executed until it is told to stop executing. So let's try to apply this to our problem of generating the Fibonacci series:
Dim X As Integer Dim Y As Integer X=1 'Initializing the values Y=0 Do Debug.Print X X = Y + X Y = X - Y Loop
And, believe it or not, this code works! Well, sorta. If you try to run this code, it will indeed generate the Fibonacci series; however, it will continually generate and print out the next number infinitely--or, in this case, until it reaches an overflow error. This is known as the problem of the infinite do-loop, one that all programmers will experience, and some quite frequently.
Exit Do[edit | edit source]
So we clearly need some way to escape from the Do-Loop. You could, of course, simply End the program once you have calculated enough values, but what if you still need to perform tasks after you're done calculating? The answer is to use the
Exit Do statement. Whenever your program reaches an Exit Do statement within a loop, it will exit the current loop.
So, let's try a somewhat different approach to the Fibonacci problem. We decide that we want to calculate only eight values of the Fibonacci series, so we'll keep a counter and increment it each time throughout the loop. Then, once the counter reaches eight, we'll exit the loop.
Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do Debug.Print X X = Y + X Y = X - Y If cnt >= 8 Then Exit Do Else cnt = cnt + 1 End If Loop End Sub
And now we're talking! This program successfully computes and prints out the first eight values of the Fibonacci series.
Do Until[edit | edit source]
As an alternative approach to nesting an If-Statement inside the loop, and invoking
Exit Do once we're done looping, Visual Basic provides a
Do Until statement. Its syntax is the following:
Do Until <Expression> <Code to execute> Loop
<Expression> can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches
Loop it will evaluate this expression. If the expression is True, it will exit the loop for us, but otherwise it will continue looping.. So let's try rewriting our Fibonacci program to use a Do-Until loop instead of Exit Do.
Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do Until cnt >= 8 Debug.Print X X = Y + X Y = X - Y cnt = cnt + 1 Loop End Sub
Here we've replaced the hideous
If cnt >= 8 Then ... Else: Exit Do with a very simple
Until cnt >= 8. We must, however, still be sure to increment our counter every time through the loop, or else the Until expression will never be True, resulting in an infinite Do Loop.
Do While[edit | edit source]
In the place of
Do Until, you can also use
Do While. Its syntax is the following:
Do While <Expression> <Code to execute> Loop
<Expression> can be any legal logical expression that we wish to evaluate to determine whether or not to exit the loop. Each time the program reaches
Loop it will verify that this expression is True, and if it is False, it will exit the loop for us. Thus, instead of exiting when an expression is True, it now exits only once this expression is false. Let's try rewriting our Fibonacci program to use a Do-While loop instead of a Do-Until loop.
Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. cnt = 1 Do While cnt < 8 Debug.Print X X = Y + X Y = X - Y cnt = cnt + 1 Loop End Sub
For-Next Loops[edit | edit source]
In situations where you merely want to run the loop a predefined number of times, it can become quite tiresome to have to create and manage a counter for each loop, which is why we also have something called a For-Next Loop. This kind of loop allows you to specify a counter, to tell it to count from one number to another each time through the loop, and to exit once the counter has reached its upper limit. The syntax is as follows:
Dim I As Integer For I = <Integer> To <Integer> step <Integer> <Code to execute> Next
We used the variable name "I" above, as it is the most common name used for For-Loops; however, you can use any variable name you want, so long as the variable is of the type Integer. Now, let's improve our Fibonacci program even further:
Public Sub Main() Dim X As Integer Dim Y As Integer Dim cnt As Integer 'Our counter. For cnt = 1 To 8 Debug.Print X X = Y + X Y = X - Y Next End Sub
In the example above, we first dimensioned cnt as an Integer, and then, in the declaration of the For-Next loop, set its value to 1. Each time through the loop, the value of cnt was incremented by 1 until it reached 8, at which point the loop was executed.
Exit For[edit | edit source]
As with Do Loops, there is a statement that can be used to exit a For-Next loop, and it is called
Exit For. Simply invoke this statement anywhere within a For-Next loop and the current loop will be exited.
Step[edit | edit source]
By default, the variable used in the declaration of the For-Next loop is incremented by 1 each time through the loop; however, if you want to increment this value by a different amount each time through the loop, you can simply append
Step <Integer> to the end of the For-Next loop declaration. If, for instance, we wanted to print out every even number counting backward from 20 to 0, we could do this using the following code:
Dim I As Integer For I = 20 To 0 Step -2 Debug.Print I Next I
Assorted Examples[edit | edit source]
The following programs are all examples that make use of many of the topics covered here. Please read through them and try to make sense of how they work. You are free to use any code present in this lesson, in part or in whole, for whatever purpose you want.
Better Fibonacci[edit | edit source]
This program takes the Fibonacci example used throughout this lesson, and modifies it slightly by adding a star next to each odd number in the series.
Public Sub Main() Dim X As Integer Dim Y As Integer Dim strOut As String 'This will store the strings we output. Dim cnt As Integer 'Our counter. For cnt = 1 To 8 strOut = Trim(CStr(c)) + ". " + Trim(CStr(X)) 'We will cover the modulus operator later. 'In short, this appends an asterisk to the string if 'the value of X is odd. If (X Mod 2) > 0 Then strOut = strOut + " *" Debug.Print strOut X = Y + X Y = X - Y Loop End Sub
Factorial Calculator[edit | edit source]
This program makes use of two nested For-Next loops to print out the factorial of every number from 0 to 10.
Public Sub Main() Dim I As Integer, J As Integer, Val As Long For I = 0 To 10 Val = 1 If I > 0 Then For J = 1 To I Val = Val * J Next J End If Debug.Print Trim(CStr(I)) + "! = " + Trim(CStr(Val)) Next I End Sub
|Learning Visual Basic|
|Previous: Visual Basic/Variables and Types — Next: Visual Basic/Functions and Subroutines|