Objectives of the Week


Much of tonight should considered a review of prerequisite material. This will include variable declaration and scope, basic arithmetic operators, the logic required to maintain counts and totals, and finally how to display the results of calculated values.

Variables

A variable is a reference to a location in memory interpreted based on a specific type. The specific type describes the type of information that is being stored at the memory location. For example, a variable that is a string will be interpreted differently that a variable that is an integer. More on types in just a moment. Variables have unique names and are used to temporarily store a piece of information. A couple of quick clarifications: First, the variable name may be better described as being uniquely identifiable. So two variables may have the same name as long as a reference to one of the variable can be fully qualified. Second, when referring to the information as being stored temporarily, it is as opposed to being permanently stored on disk. The data can reside in memory for, at most, the duration of the program.

Constants

A constant is exactly the same thing as a variable except that when you specify that the memory location being defined is to be a constant, the compiler sets up the checks necessary to make sure that your program does not change this value. If you do attempt to change the value, the compiler catches this, and flags it as a syntax (compile) error. You must also give the constant a value when it is defined.

There was some brief discussion of Intrinsic Constants from Week 02. The Intrinsic Constants are built in to the VB Run Time. Information on these constants is available in the Help related to some specific controls. It is also available in the Object Browser. Select View | Object Browser from the VB Menu Bar. Select the VBRUN Library and select the Global class and you can see a list and a brief description some of the Intrinsic Constants available to you.

Object Browser

A variable represents a location in memory that is designed to store a specific type of value. This value may be modified by the program as part of the logic of the application. A constant is a reference to a location in memory, but is not allowed to be modified during program execution. This is a feature of VB and other languages that prevents accidental changes to values that were, by design, not supposed to be changed. The compiler will flag as an error any instruction that attempts to change the value of a constant.

Variables and Constants are declared using a mix of upper and lower case. Always type in lower case when referencing a variable in your event handler. You will begin to get an eye for the case change. If the case does not change, the chances are you have an error in the variable reference.

Naming Conventions

Just like the controls, a three character prefix (Lower Case) followed by a meaningful name

bln   Boolean   True / False
byt  Byte   ASCII characters
cur   Currency   Decimal values (Obsolete)
dtm   Date/Time   8 Character Date
dbl   Double   Double precision Floating point
int   Integer   Whole Numbers  -32,768 thru 32,767
lng   Long   Larger Whole Numbers
sng Single Single precision Floating point
str   String   Characters, AlphaNumeric
vnt   Variant   Undetermined

Variable Declaration

To define a variable you must give it a name and know the type. The Dim or dimension statement is the most common way to perform the variable declaration.

Dim variable as type

While the "as type" is optional and will default to Variant, not specifying the type is a poor programming practice.

String   Dim strLastName as String
Integer   Dim intCount as Integer

The AutoFill feature of VB will also prompt you for a variable type as seen here:

autolist

To define a constant, use the Const key word rather than Dim and specify an initial value.

Const sngBase as Single = 250.00

Make sure that you follow the standards by using the three character prefix representing the type as lower case followed by a meaningful name beginning with an upper case character. Later in the event handlers, specify the variable or constant name in all lower case and watch for the case to change. If you see this change to match the case in the Dim, you have specified the correct variable. If you do not see this case change, make sure you look it over again very well as you have probably miskeyed the variable name.


Variable Scope

Scope describes the availability of the variable. The scope is determined by the placement of the Dim statement.

Scope In the code example notice the  Module Level Variables and Local Variables. These Module Level Variables are visible or available to every event handler on the form while the Local Variables are available only to the event handler in which they are declared.

The values of the  Module Level Variables are maintained throughout the life of the application. The values of Local Variables are reinitialized each time the event handler is invoked. They are not maintained between the associated events.

cmdCalc_Click has access to the Module Level Variables and also to its own Local Variables. The Local Variables are reinitialized each time the event handler is invoked.

cmdClear can reference only the Module Level Variables as it has no locally declared variables.

The m_ prefix on Module Level Variables is important as it lets the programmer know that this is module level and it also prevents hiding the Module Level Variables. If a Local Variable is declared with the same name as the Module Level, the reference to the Local Variable would override access to the Module Level Variable. The m_ prefix prevents this from happening.


Arithmetic Operations

I'm really hoping that what you see next is mostly a review, although I expect that everyone will probably see at least one new operator.

+   Addition   2 + 3 = 5
-   Subtraction   5 - 3 = 2
*   Multiplication   5 * 3 = 15 and note the use of the * as the multiply symbol
/   Division   15 / 3 = 5 or 5 / 2 = 2.5
^   Exponentiation   2 ^ 3 = 8 That's 2 raised to the 3rd power is 8
Mod  Modulo   9 Mod 4 = 1 What? Modulo is the remainder after division
\   Integer Division   5 \ 2 = 2 as compared with decimal division

In order to perform an arithmetic operation on user input, the Text property of the Text Box (currently the only method for requesting user input), must be converted to a numeric value. The Val() function will perform the conversion.

intQuantity = Val(txtQuantity.Text)

The variable intQuantity is a Local Variable and the Alphanumeric contents of the Text Box txtQuantity is convered to a number so it can be used in a calculation. While it is true that VB will perform this conversion for you, performing the conversion is a good programming practice.


Precedence

When performing calculations on more that two variables in a single statement, there are some evaluation rules that must me considered. The Precedence of Operations determines the order in which calculations are performed.

From left to right:

Some examples of precedence

3 + 7 * 4 / 2 - 1
3 + 28 / 2 -1
3 + 14 - 1
16
(3+7) * (4/2) - 1
10 * 2 - 1
20 - 1
19
3 + (7*4) / (2-1)
3 + 28 / 1
3 + 28
31

Counters and Accumulators

Using a counter generally means that you add 1 to a Module Level integer each time you repeat a process.
For example:

   m_intCounter = m_intCounter + 1

Working with an accumulator generally means that you are maintaining a running total after you have completed a calculation.
For example:

   m_sngGroupTotal = m_sngGroupTotal + sngCalculatedAmount

These are very general examples but you will see them put to use in the Step By Step example and in the lab.

Also note that without having to see the Dim statements for each of these variables, it is crystal clear as to the type and the scope of each of the variables references in this example.


Format Functions

A series of format functions are available in Visual Basic. These functions allow

FormatCurrency   Returns an expression formatted as a currency value using the currency symbol.

FormatCurrency(0.1, 2) results in $0.10

FormatPercent   Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.

FormatPercent(0.1, 3) results in 10.000%

FormatNumber   Returns an expression formatted as a number.

FormatNumber(123.4567, 2) results in 123.46 (Note the rounding)
FormatNumber(123.1234, 2) results in 123.12

FormatDateTime   Returns an expression formatted as a date or time.

FormatDateTime(Date,vbGeneralDate) results in 1/10/01
FormatDateTime(Time,vbGeneralDate) results in 8:02:23 AM

There are a number of Intrinsic Constants to provide the formatting of many different type of Date and Time display


Build the Example

Step by Step through the First Example

Make sure that you:


Lab 1 -From the text - Page 122, VB Mail Order

Step by Step through the First Lab

Let me know when you are done and I will check you off as Complete

Lab 2  - From the Text - Page 122, VB Auto Center

You are on your own.


Assignment

Reading Assignment

Programming Assignment

As Always: The assignment is due before the start of class next week

Calorie Calculator

Page 118, Problem 3.1
Make sure you follow the class standards for the Form's Caption

Here is a list of the Program Grading Criteria