During this hour you will learn
This hour's lesson furthers Hour 7's lesson by showing you how to formulate Visual Basic expressions. An expression is a math- or string-related set of variables, literals, and control values that combine with math- and string-related operators to produce a resulting value. Visual Basic assigns that produced value to the object to the left of the assignment's equal sign.
Reread the description of expressions above. Now that you have that out of the way, you'll be pleased to know that working with expressions is simpler than describing the process! Often, you'll put together fairly complex expressions in your assignment statements, even if you don't consider yourself a math wizard.
An operator is a symbol used for addition, subtraction, multiplication, division, and other calculations. In addition to symbols, the Visual Basic language includes some abbreviations that work as operators as well.
Operators aren't just for mathematical calculations. Visual Basic has operators that work with string expressions as well.
FAST TRACK |
If you know all about computer operators that manipulate data, such as * and /, read through this hour's operator tables to brush up on the ones that are new to you. Then move to Hour 9's lesson, "Working with Interactive Keyboard and Screen I/O", where you learn how to enter and display data by using special built-in Visual Basic routines. In particular, make sure that you understand Mod and Like, because both are limited to Visual Basic and other recent BASIC language descendants. |
This topic section explores the operators through tables that explain many of Visual Basic's more common operators. You'll see that Visual Basic does all your math for you, but you must set up the operations correctly.
Visual Basic's operators are similar to those you use to do arithmetic. Table 8.1 lists Visual Basic's common operators and their meanings.
Table 8.1 Visual Basic Common Operators
Operator | Meaning |
* | Multiplication |
/ | Division |
+ | Addition or concatenation |
- | Subtraction |
^ | Exponentiation |
\ | Integer division |
Mod | Modulus |
Most of these fundamental operators are mathematically related. The plus sign (+) sometimes operates on both string and numeric values (as you'll see), but you'll apply the rest of the operators to only mathematical calculations.
![]()
The Four Primary Operators
The four primary Visual Basic operators (*, /, +, and -) operate just as their counterparts in mathematics do. Multiplication, division, addition, and subtraction operations produce the same results as when you do these math functions with a calculator. The four examples in Table 8.2 illustrate each operator.
Table 8.2 Results of Calculations Done with Primary Operators
Formula | Result |
4 * 2 | 8 |
95 / 2 | 47.5 |
80 - 15 | 65 |
12 + 9 | 21 |
For multiplication, you must use an asterisk rather than an [ts] (a common multiplication symbol). Visual Basic reads [ts] as a variable named x.
You can use the addition and subtraction operators by themselves, in which case they're called unary operators. (The unary addition operator is optional because Visual Basic assumes a positive value unless you tell it otherwise.) By using the unary plus or minus, you can assign a positive or negative number to a variable or assign it a positive or negative variable, as the following code shows:
a = -25 ' Stores a negative 25 in a b = +26 ' Stores a positive 26 in b c = -a ' Stores a positive 25 (the inverse of a) d = +b ' Stores a positive 26 (the value of b)
This topic's "Next Step" section explains how to use the plus sign to work with string values.
![]()
Internally, your computer can perform addition only. This fact might seem strange, because computers are used for all kinds of powerful mathematical computations. Addition, however, is all that your computer needs to know.
At the binary level, your computer can add two binary numbers. Your computer has no problem adding 6 + 7. To subtract 6 from 7, however, your computer must use a modified form of addition, in which it adds a negative 6 to 7. When your program stores the result of 7 - 6 in a variable, your computer interprets it as 7 + -6. To simulate subtraction, all your computer needs to do is add and compute the negative of any number (called the two's complement).
Multiplication simply is repeated addition. Therefore, 6 * 7 is interpreted as 6 added to itself seven times, or 6 + 6 + 6 + 6 + 6 + 6 + 6.
Division is repeated subtraction. When you calculate 42 / 6, the computer repeatedly subtracts 6 from 42 until it gets to zero, and then adds the number of times it did that. This becomes 42 - 6 - 6 - 6 - 6 - 6 - 6 - 6 = 0. Reaching 0 takes seven subtractions of 6 (actually, seven additions of -6). Thus, the result of 42 / 6 is 7. Because division doesn't always result in a whole number, when the repeated subtraction results in a negative number, the computer uses that number to produce the remainder.
With the capability to add and to simulate subtraction, multiplication, and division, your computer has the tools required for every other math function as well.
Integer Division, Modulus, and Exponentiation
The three remaining fundamental operators--integer division (\), Mod, and exponentiation (^)--might be new to you, but they're as easy to use as the four operators in Table 8.2.
Use integer division to produce the integer (whole number) result of a division. Integer division always produces an integer result and discards any remainder. You don't have to put integers on both sides of the backslash (\); you can use floating-point numbers, integers, or both on each side. Table 8.3 shows the results of some sample integer-division code.
Table 8.3 Integer-Division Results
Formula | Result |
8 \ 2 | 4 |
95 \ 2 | 47 |
95.0 \ 2 | 47 |
95 \ 2.0 | 47 |
95.0 \ 2.0 | 47 |
The Mod operator is one of the few Visual Basic operators that doesn't appear in the form of a symbol. Mod produces the modulus, or integer remainder, of division. Table 8.4 shows the results of some simple Mod operations.
Table 8.4 Results of Simple Mod Operations
Formula | Result |
8 Mod 2 | 0 |
8 Mod 3 | 2 |
8 Mod 7 | 1 |
Use the exponentiation symbol (^) when you want to raise a number to a power. The number to the left of the caret (^) is the base, and the number to the right is the power. You can put integers, floating-point numbers, or a combination of both on each side of the caret. Table 8.5 shows the results of some exponentiation calculations.
Table 8.5 Exponentiation Results
Formula | Description | Result |
2^4 | 2 raised to the fourth power (24) | 16 |
16^2 | 16 raised to the second power (162) | 256 |
5.6 ^ 3 | 5.6 raised to the third power (5.63) | 175.616 |
144^O.5 | 144 raised to the .5 power (1441/2) | 12 |
The procedure in Listing 8.1 illustrates a payroll computation. It assigns to three variables the hours worked, the pay per hour (the rate), and the tax rate. It then uses those variables in calculations to create three new variables: the gross pay, the taxes, and the net pay. The procedure ends by assigning these values to labels so that the values appear on the users' form.
Listing 8.1 CalcPr.BAS: Payroll Computation
Private Sub Calc_Pr() ' Computes three payroll variables. Dim intHoursWorked As Integer Dim sngRate As Single, sngTaxRate As Single Dim curTaxes As Currency, curGrossPay As Currency Dim curNetPay As Currency ' Initialize the variables intHoursWorked = 40 ' Total hours worked sngRate = 7.80 ' Pay per hours sngTaxRate = .40 ' Tax rate percentage ' Calculate the amounts curGrossPay = intHoursWorked * sngRate curTaxes = sngTaxRate * curGrossPay curNetPay = curGrossPay - curTaxes ' Display results in labels lblGrossPay.Caption = curGrossPay lblTaxes.Caption = curTaxes lblNetPay.Caption = curNetPay End Sub
![]()
Whew, that's a long procedure! Actually, this procedure's length is fairly typical. You're beginning to see how a procedure's code does work inside a Visual Basic application when that procedure isn't an event procedure.
![]()
![]()
Notice the blank lines throughout Listing 8.1. These lines help separate parts of the procedures and make the procedures more readable. Add as much of this white space to your own programs as you need to make your programs easy to read and maintain. For more information about code remarks, you may want to review Hour 6, "Understanding the VB Program Structure."![]()
Notice that the code in Listing 8.1 mixes Single data type calculations with Currency data types in the same expressions. This mixing of data types isn't critical here because Visual Basic rounds the tax calculations and stores the results in the Currency data type format with the appropriate dollars and cents. The tax rate can't be Currency because a tax rate may need more than two decimal places; the pay rate per hour, however, could have been data typed as a Currency value. The choice won't affect these calculations.
In Listing 8.1, the labels lblGrossPay, lblTaxes, and lblNetPay are assumed to be on the form and set up with appropriate preceding label descriptions so users know what the three values represent.
When sending data to labels, you'll often format the output so that the labels display values in an appropriate format, such as with a dollar sign and commas in large numbers. You learn in Hour 14's lesson, "Using the Supplied Functions," how to format numeric data.
You can assign expressions to labels. In other words, you could have assigned the gross pay expression directly to the gross pay label in this example procedure. Nevertheless, the variables help you separate the calculations from the data display. Such separation often lends itself to more maintainable programs when your calculations change or when you must add additional calculations.
![]()
When you perform string concatenation, you merge two strings together to form a single string. Perhaps you need to take a user's first name and concatenate his last name onto the end of the first name and store the composed string into a third string. You can concatenate as many strings together as needed to form single strings.
Make sure that the target string that's receiving the concatenated strings (the string on the left of the assignment) is a variable-length string or, if fixed-length, long enough to hold the concatenated strings.
![]()
Visual Basic uses the plus sign (+) for string concatenation. Therefore, the following statement sends "Grant Holdorf" into the string named strFullName:
strFullName = "Grant" + " " + "Holdorf"
Without the center space, strFullName would receive "GrantHoldorf" because Visual Basic would never insert a space between two merged strings automatically. Be aware that your merged strings will appear next to each other when you concatenate and insert spaces if needed.
The plus sign is known as an overloaded operator, because it performs two separate operations: addition of numbers and concatenation of strings. Therefore, to reduce ambiguity, Microsoft added to Visual Basic a concatenation operation, &, that performs only string concatenation. Therefore, most Visual Basic programmers now use the plus sign only for numeric calculations and the ampersand (&) for string concatenations. The following statement performs the same concatenation as the preceding statement:
strFullName = "Grant" & " " & "Holdorf"
Knowing the meaning of the math operators is the first of two steps toward understanding Visual Basic calculations. You also must understand the order of operators. The order of operators (sometimes called operator hierarchy or operator precedence) determines exactly how Visual Basic computes formulas. The order of operators is exactly the same as that used in high-school algebra.
To see how the order of operators works, try to determine the result of the following calculation:
2 + 3 * 2
Many people would say that the answer is 10, but 10 is correct only if you interpret the formula from left to right. What if you calculated the multiplication first? If you first calculate the value of 3 * 2 to be 6 and then add 2 to that value, your answer for the calculation is 8. Visual Basic uses the latter technique to calculate the problem and therefore would produce 8 as the answer.
Visual Basic performs any exponentiation first, and then performs multiplication and division. Finally, it performs addition and subtraction. Table 8.6 shows this order of operators.
Table 8.6 The Order of Operators
Order | Operator |
1 | Exponentiation (^) |
2 | Unary positive and negation |
3 | Multiplication, division, integer division, Mod |
4 | Addition and subtraction |
You easily can follow Visual Basic's order of operators if you follow the intermediate results one at a time. The two calculations in Figure 8.1 show you how to follow Visual Basic's order of operators.
Visual Basic follows an operator order for calculations.
Parentheses Override the Order
If you want to override the order of operators, use parentheses in the calculation. Parentheses are operators just like + and *, except that they appear higher in Visual Basic's order of operator table. Thus, Visual Basic always performs calculations inside parentheses before any other operations in the expression. By using parentheses, you can write expressions in the order you prefer and specify the calculation order yourself.
The formula 2 + 3 * 2 produces 8 because multiplication is performed before addition. But if you put parentheses around the addition, as in (2 + 3) * 2, the answer becomes 10 because Visual Basic computes the calculation between the parentheses first.
If expressions with parentheses are inside other parentheses--for example, ((5 + 2) - 7 + (8 + 9 - (5 + 2)))--Visual Basic calculates the innermost parenthetical expressions first.
Consider the short expression evaluation shown in Figure 8.2. Although the expression is short, its result may at first surprise you.
Be careful when performing integer arithmetic.
The first step is probably no surprise. According to Table 8.6, the exponentiation must calculate first. But look at the second line carefully; notice that the expression contains an integer division operator, not a regular division operator. Therefore, Visual Basic will calculate 20 \ 9 as an integer division and throw away any remainder that may appear. 20 divided by 9 is 2 with 2 left over. When Visual Basic discards the remaining 2, the result is simply the integer 2.
For another example, look at the expressions in Figure 8.3. The formulas in the figure are the same formulas shown in Figure 8.1, but the calculations vary because the parentheses override the order of operators.
The parentheses take precedence over the operators.
In Table 8.6, notice that multiplication, division, integer division, and Mod appear on the same level. This arrangement implies that no hierarchy exists on that level. If more than one of these operators appears in a calculation, Visual Basic performs the math from left to right. The same is true for addition and subtraction; Visual Basic does the leftmost operation first if two or more addition or subtraction operators appear in an expression. Figure 8.4 shows an example of left-to-right division and multiplication. In this example, because the division appears to the left of the multiplication (and because division and multiplication are on the same level), Visual Basic computes the division first.
Operators on the same precedence level calculate from left to right.
See if you can spot a potential problem with the following procedure fragment:
sngGrade1 = 86.0 sngGrade2 = 98.0 sngGrade3 = 72.0 sngAverage = sngGrade1 + sngGrade2 + sngGrade3 / 3 lblAverage.Caption = sngAverage ' Oops!
The problem with this code results from the fact that Visual Basic performs division before addition. Therefore, the third grade is divided by 3 and then the other two grades add to that result. To fix the problem, you can add a set of parentheses, as shown in the following corrected code:
sngGrade1 = 86.0 sngGrade2 = 98.0 sngGrade3 = 72.0 sngAverage = (sngGrade1 + sngGrade2 + sngGrade3) / 3 lblAverage.Caption = sngAverage ' Now displays correctly
This average calculation illustrates why the parentheses can keep you out of trouble. If you find that a Visual Basic program won't return a result that you expect, scan all the expressions in the program's code to make sure that you've specified your expressions so they respect the order of operator table.
Use plenty of parentheses in your programs to make the order of operators clear to anyone who reads the program. Even if you don't need to override the order of operators, the parentheses make the calculations easier to understand if you modify the program later.
![]()
Believe it or not, not every Visual Basic statement should execute every time users run the program. Because your programs operate on data, they're known as data-driven programs. In other words, the data should dictate what the program does.
For example, you wouldn't want the computer to print a paycheck every pay period for every employee who works for you; some employees might have taken a leave of absence, or some might be on a sales commission and might not have made a sale during the pay period. Printing paychecks for no money would be ridiculous. You want your program to print checks only to those employees who have pay coming to them.
This topic section introduces conditional and compound logical operators. Unlike math operators, conditional operators don't perform calculations but instead compare data values against one another. Conditional operators form the basis for several Visual Basic statements. In fact, after you learn the Visual Basic statements that depend on the conditional operators, you'll know much of the Visual Basic language.
Conditional operators are sometimes called comparison operators because they compare data values. You'll also see them called relational operators occasionally.
![]()
Compound logical operators (often just called logical operators) let you combine two or more conditional expressions. By learning the compound operators now, you can see a more complete order of operator chart at the end of this topic.
The conditional operators compare data values against one another, and then tell your program the result of the comparison. Your program then can use control commands (which you'll learn about throughout this night-school course) to make decisions based on the conditional operator results. Table 8.7 lists VB's conditional operators.
Table 8.7 Conditional Operators
Operator | Description |
= | Equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal to |
<= | Less than or equal to |
<> | Not equal to |
These six operators form the foundation for comparing data in VB applications. The operators always appear with two literals, variables, controls, expressions--or a combination of the four--on each side. You should know these operators as well as you know the ^, +, -, *, and / mathematical operators.
The result of a mathematical operation is a number; the result of a conditional operation is a True or False data-typed result. (This result is often called a Boolean result, corresponding to Visual Basic's Boolean data type.) Depending on that result, your Visual Basic application code might take one of two possible execution paths.
Assume that a procedure initializes four integer variables, as follows:
A = 5 B = 10 C = 15 D = 5
The following statements are true and illustrate how the conditional operators compare data and return the True result:
These statements aren't Visual Basic statements, but they demonstrate the conditions tested by the conditional operators. Conditional logic is simple because it always produces a true or false result.
If the value on either side of the conditional operator is Null, Visual Basic returns Null for the comparison's result. If one side contains the Empty value, numeric comparisons assume that Empty is 0 and string comparisons (see the next section) assume that the Empty value is a null string ("").
![]()
Did you know that a conditional's True or False result occurs internally at the bit level? Look at the following conditional:
(A = 6)
To determine the truth of the relation (A = 6), the computer takes a binary 6, or 00000110, and compares it bit by bit with the variable named A. If A contains 7 (a binary 00000111), the result of the equal test is False because the right bit (called the least-significant bit) is different from the 6's least-significant bit.
Many people say they suffer from "math anxiety"--you might even be one of them. As mentioned earlier this hour, you don't have to be good at math to be a good computer programmer because Visual Basic does all the mathematical work. Don't be frightened by the term conditional logic; you use conditional logic every day. Nevertheless, some people see the conditional operators and get confused about their meanings.
The two primary conditional operators, less than (<) and greater than (>), are easy to remember. You might have been taught which is which in school but have forgotten. Actually, their symbols tell you exactly what each means. Notice that in the previous true examples, the small part of the operator (the point) always points to the smaller number. The large, open part indicates the larger value.
The relation is false if the arrow points in the wrong direction. In other words, 4 > 9 ("4 is greater than 9") is false because the small part of the operator points to the 9.
String Comparisons
In addition to comparing numeric data with conditional operators, you can compare character string data. Comparing strings is useful for alphabetizing, testing answers, comparing names, and much more. Generally, strings compare uppercase before lowercase, and special characters and numbers before alphabetic characters. This comparison technique, called a binary compare, results in case-sensitive and accurate alphabetizing of strings.
If you include the following statement in your module's Declarations procedure,
Option Compare Text
Visual Basic compares with a case-insensitive sequence, and A compares equally with a.
![]()
You know that A comes before B. Therefore, it's true that A is less than B. When comparing more than one character at a time, Visual Basic scans each character of each string being compared until it finds a difference. For example, "Adam" and "Adam" are exactly equal. "Jody" is less than "Judy", however, because o is less than u according to the normal Visual Basic binary comparison. Also, a longer string such as "Shopping" is greater than "Shop" because of the extra characters. The null string, "", always compares less than any other string except another null string.
All of the following string comparisons are true (assuming that the Option Compare Text statement doesn't appear in the module's Declarations section):
"abcdef" > "ABCDEF" "Yes!" < "Yes?" "Computers are fun!" = "Computers are fun!" "PC" <> "pc" "Books, Books, Books" >= "Books, Books"
Use string comparisons to check for a correct password entry. After users type a password, compare the control holding the password to an internal password string or one that your program reads from a file to see whether they match.
![]()
At times, you might need to conditionally test more than one set of variables or controls. You can combine more than one conditional test into a compound conditional test by using the following logical operators: And, Or, Xor, and Not. The logical operators combine two or more conditional expressions into one expression.
These might not seem like typical operators because they aren't symbols, but like Mod, the logical operators are word abbreviations that work as operators. The logical operators always appear between two or more conditional operations within the same expression.
Tables 8.8, 8.9, 8.10, and 8.11 show how each logical operator works. These tables, called truth tables, show how to achieve true results from a conditional test. Take a minute to study the tables.
Table 8.8 The And Truth Table (Both Sides Must Be True)
True | And | True | = | True |
True | And | False | = | False |
False | And | True | = | False |
False | And | False | = | False |
Table 8.9 The Or Truth Table (One Side or the Other Must Be True)
True | Or | True | = | True |
True | Or | False | = | True |
False | Or | True | = | True |
False | Or | False | = | False |
Table 8.10 The Xor Truth Table (One or the Other Must Be True, But Not Both)
True | Xor | True | = | False |
True | Xor | False | = | True |
False | Xor | True | = | True |
False | Xor | False | = | False |
Table 8.11 The Not Truth Table (Negates the Comparison)
Not True | = | False |
Not False | = | True |
The logical operators are difficult to describe in more detail until you get to Hour 10's lesson, which studies the If statement. Nevertheless, consider the following expression:
(1 < 3) And (9 > 3)
The expression doesn't comprise a complete Visual Basic statement, but it does test your knowledge of logical operators. The And truth table tells you that both sides of the And logical operator must be true before the entire expression is true. Therefore, because (1 < 3) returns a True result and because (9 > 3) returns a True result, the result of the entire expression is True. The following, however, is not true because of the first conditional expression:
(3 <> 3) And (5 <> 6)
If you replaced And with Or, the expression produces a True result again:
(3 <> 3) Or (5 <> 6)
Although the left side of the Or compares with a False value, the right side returns a True value. The Or truth table tells you that False Or True produces a True result.
The parentheses around individual conditional expressions of a compound conditional statement help you distinguish the sides of the logical operator. Also, the parentheses take precedence over both mathematical and compound conditional statements.
![]()
The Xor (for exclusive or) is often used as a mutually exclusive comparison, when one side or the other must be true but not both. The Not operator reverses comparison results. Visual Basic programmers generally use only And and Or in their applications because Xor and Not can produce confusing code.
FAST TRACK |
Do you understand file name wild-card characters? If so, you'll appreciate Visual Basic's Like operator. Like works like an equality comparison, with one exception--you can use wild-card characters on either side of Like to compare a variable, control, literal, or expression to a pattern. Use ? to compare against any single character match, * to compare against zero or more characters, and # to compare against numeric digits. You also can place brackets ([ and ]) around a character list you want to use for the comparison, and start a bracketed list with a ! if you want to compare against a single character not in the list. Therefore, "Bettye" Like "Be*" returns True, as does "A" Like "[ABC]" and "A" Like "[!XYZ]".
If you've programmed a lot before, the Like comparison operator is probably one of the few new operators for you. Now that you've seen Like, you may want to skip ahead to Hour 9's lesson, "Working with Interactive Keyboard and Screen I/O". |
The Complete Order of Operators
The order of the math operators that you saw earlier in Table 8.6 didn't include the conditional and logical operators. You need to be familiar with the entire order, shown in Table 8.12. As you can see, the math operators take precedence over the conditional and logical operators, but parentheses override any of the defaults.
Table 8.12 Complete Order of Operators
Order | Operator |
1 | Parentheses |
2 | Exponentiation (^) |
3 | Unary negation and the unary positive |
4 | Multiplication, division, integer division, Mod |
5 | Addition, subtraction |
6 | Conditional operators (=, <, >, >=, <=, and <>) and Like |
7 |
Not logical operator |
8 |
And |
9 |
Or |
10 |
Xor |
You might wonder why the conditional and logical operators are included in the order. The following expression helps show why:
curSales < curMinSales * 2 And intYrsEmp > 10 * intFactor
Without the complete order of operators, it would be impossible to determine how Visual Basic would interpret such a statement. According to the operator order, this expression would evaluate as follows:
((curSales < (curMinSales * 2)) And (intYrsEmp > (10 * intFactor))
This expression still is confusing, but it's less confusing than the preceding expression. The two multiplication operations would be performed first, followed by the conditionals < and >. The logical And is performed last because it's lowest in the order of operators.
To avoid problems with reading such code, use ample parentheses, even if you want the actions to be performed in the default operator order. Also, don't combine too many expressions together; break them up, if you can.
![]()
Again, return to these four integer variables initializations:
A = 5 B = 10 C = 15 D = 5
Each of the following conditional operations would result in false results:
Study these statements to see why each produces a false result. A and D are equal to the same value (5), so neither is greater than or less than the other.
You deal with conditional logic in everyday life. Think of the following statements that you might make:
Each statement can be only true or false--there are no other possible outcomes.
As is true of other relational operators, you use logical operators in everyday conversation, as in the following examples:
The first two examples are straightforward. The last example illustrates the Xor operator. Notice from the Xor truth table that one side of the Xor or the other side of the Xor can be true for the final result to be true, but not both sides. You're often faced with two choices, but you can do only one thing or the other; you don't have the time or resources to do both. The same is true sometimes with computer conditional tests. You might need to print an exception report if a customer's payment is late or if the customer's debt is forgiven, but not if both events occur.
After this hour's lesson, you now can write almost any math operation that you'll ever need. By understanding the order of operators, you know how to structure your formulas so that Visual Basic computes the answers the way you intend for them to be computed. You always can override the order of operators by using parentheses.
Computers do more than calculate arithmetic expressions, however. This hour's final topic introduced you to Visual Basic's conditional operators. With the conditionals, you'll be able to learn a lot of Visual Basic commands in Hour 10's lesson. At this point, you know only a few of Visual Basic's commands, especially how to code remarks and assignment statements (and remarks aren't even runtime commands). In a couple of lessons, you'll know several more statements and can begin to make Visual Basic perform complicated logic.
In Hour 9, you learn how to produce input and output by using special Visual Basic routines called input boxes and message boxes. At this point, you can display and accept user information with controls on a form, but form controls are limiting when you want to display messages for only short periods of time. The input boxes and message boxes will let you interact with users as your program runs without changing the form's appearance.
N = 0 N = N + 5