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
"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
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, 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:. P and Q can be either constants, variables, or logical expressions themselves. The  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:

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  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
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 "="
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 "<>"
This operator is synonymous with:. In this format,  is the left hand expression, and   is the right hand expression, which is evaluated for equality. If  is True, then (True = False) is false, but if   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 ">"

 * Syntax: P > Q
 * Returns: True if P is greater Q, and False if P is less than or equal to Q.

Less Than "<"

 * 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 ">="

 * 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 "<="

 * Syntax: P <= Q
 * Returns: True if P is less than or equal to Q, and False if P is greater than Q.

Logical Operators
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"
This operator does not take the standard form of. 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.


 * Syntax: Not P.
 * Returns:

Conjunction "And"
The Conjunction operator ("And") takes two or more Boolean expressions and returns true if both expressions are True.


 * Syntax: P And Q
 * Returns:

Disjunction "Or"
The Disjunction operator ("Or") takes two or more Boolean expressions and returns true if any of them is True.


 * Syntax: P Or Q
 * Returns:

Exclusive Disjunction "Xor"
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
 * Returns:

If-Statements
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 separate 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
VB6 uses the same simplistic and easily comprehendible syntax for If-Then Statements as BASIC. The If-Then Statement can be written two ways:

The  parameter can be any Boolean value or logical expression. If the code you want to execute when  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
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:

But instead of having to write that every time, VB6 provides an additional "Else" clause for your If-Statements. The usage is very simple:

One Step Further: ElseIf
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:

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
So now that we know everything we need to know to begin using If-Statements in our code, let's look at some examples.

Loops
Now let's return to our original problem of generating the Fibonacci series. Its formula is relatively simple:
 * 1) Let x = 1, let y = 0.
 * 2) Print x.
 * 3) Let x = y + x
 * 4) Let y = x - y
 * 5) 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
The most basic form of loop in Visual Basic is the Do-Loop. Its construct is very simple:

This, quite simply, executes the block of code, and when it reaches, 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:

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
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  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.

And now we're talking! This program successfully computes and prints out the first eight values of the Fibonacci series.

Do Until
As an alternative approach to nesting an If-Statement inside the loop, and invoking  once we're done looping, Visual Basic provides a   statement. Its syntax is the following:

 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  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.

Here we've replaced the hideous  with a very simple. 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
In the place of, you can also use. Its syntax is the following:

 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  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.

For-Next Loops
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:

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:

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
As with Do Loops, there is a statement that can be used to exit a For-Next loop, and it is called. Simply invoke this statement anywhere within a For-Next loop and the current loop will be exited.

Step
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  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:

Assorted Examples
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
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.

Factorial Calculator
This program makes use of two nested For-Next loops to print out the factorial of every number from 0 to 10.

Visual Basic/Conditionnelles et boucles