ISM 3230 Introduction to Programming
Chapter 3 Student Learning OBJECTIVES:
Upon completion of this chapter, your students will be able to
Data Type |
Value Range |
Boolean |
True or False |
Byte |
A single ASCII character |
Currency |
Dollars and cents (two decimal places) |
Date |
Eight character date (mm/dd/yy) |
Integer |
Small integers: + or - 32,767 |
Long |
Larger integers: (+ or - 2 Billion) |
Single |
Decimal numbers (floating point) |
Double |
14-digit floating point numbers |
String |
Character data |
Variant |
Converts from one type to another |
The most common data types, and the ones we'll be using mostly in this class, are String, Currency, and Integer.
The default data type is variant. If you do not specify a data type, then variant will be assigned to all variables. It is good practice to always specify the data type for a variable.
Declaring Variables & Constants.
As mentioned above, declaring a variable means telling the computer how much memory to reserve, giving it a name, and giving it a type.
Variables:Dim variable-name As data-type
Constants:Const constant-name As data-type = value
Important! Force variables to be explicitly declared in your VB environment:
Dim strName As String
Dim intNumber as Integer
Dim intNumber, intCount as Integer
Const curDISCOUNT_RATE As Currency = 0.15
When you declare constants, it is customary to use all uppercase letters
The text property of a text box is, actually, a variant data type. Because of this, you can check its data type to determine if it is text, numeric, date, and so on.
Naming Rules (required by VB):
Naming Conventions (not required by VB but good practice):
Examples:
strLongNameHere, intAnnualIncome
VB’s Auto Fill feature helps you complete writing a Dim statement by presenting a list of available options.
Using named constants follows conventional programming practice.
Use named constants in lieu of "magic numbers"
Examples of declaring Constants:
Const strRPTNAME As String = "October Report"
Const sngTAXRATE As Single = 0.075
Rather than coding
curStateTaxDue = curGrossPay * 0.078
code instead
curStateTaxDue = curGrossPay * sngSTATE_TAX_RATE
where sngSTATE_TAX_RATE is a named constant
Where do you place constant declarations?
Examples of Constant Declarations:
Dim strCompanyName As String = "Proflowers.com"
Dim sngTaxRateSingle As Single = 0.125
Dim intNumberOfCourses As Integer = 4
Intrinsic Constants
vb means Visual Basic
db means Data Access Objects
xl means Excel
Scope is the availability of a variable
Global Variables
Always keep a variable’s scope as small as possible. This greatly reduces the chances of error.
Variable lifetime:
Module level variables frequently have the prefix m added to indicate their scope:
mcurTakeHomePay As Currency
Calculations
and Assignment Statements
Standard Operators: (), ^, *, /, +, -
Assignment statement: Assigns a new value to a variable
When same variable on both the left and the right side of =, then the previous value on the right is used, then overwritten with the new value.intintSum = 3 + 7
intDifference = 3 - 7
txtTaxes.text = CurGrosspay * 0.35
intCount = intCount + 1
dblTotal = dblTotal * 100.00
Operator precedence: determines how an equation is evaluated
For expressions with more than 1 operator, which is calculated first?
Total = Hours * Rate + Overtime * Rate * 1.5
The order evaluation of operators, called precedence, is as follows (from first/highest to last/lowest)
Thus, there is a particular order in which every expression is evaluated:
dblAnswer = 1 + 17 * 24 - 15 * (201 - 6) / 8
intTotalScore = intTotalScore + Val(txtScore.Text)
If the text box called txtScore contains a character string that is not numeric, then the value zero is returned--a convenient behavior.
If a control contains a combination of numbers and non-numbers and begins with a series of digits (and decimal points or signs), then the leading digits right up to the first non-digit are returned as a value:
Val("1234BeThere") is 1234
Test Yourself: What is the value of intSum after each operation?
This means altering the displayed form of a number or string by formatting it. It does NOT affect the stored value in memory.
Special format functions exist to speed the process, such as FormatPercent
The form of a typical format function:
FormatCurrency(NumericExpressionToFormat)
FormatCurrency(curTotalDue)
When you want to format data for display or the printer, you use one of the four Format functions.
FormatCurrency
FormatNumber
FormatPercent
FormatDateTime
Examples:
FormatCurrency(12.345) $12.34
FormatNumber(1278.569,1) 1,278.6
FormatPercent(0.8326) 83%
FormatDateTime("3/15/2000",vbShortDate) 3/15/00
Format Function Examples
lblTot.Caption = FormatCurrency(curTotal)
lblDate.Caption = FormatDateTime(intBirth)
lblQuantity.Caption = FormatNumber(intDone)
lblPercentDone.Caption =
FormatPercent(txtDaysWork/txtTotalDays)
Note that format rounds fractional values to requested number of decimal places. This does not affect the stored value.
Counting and Accumulating intSums
Counting:
intCount = intCount + 1
Accumulating a sum:
intTotal = intTotal + intNew
Averaging:
sngAverage = intTotalScore / intCount
To sum sales, the trick is to define a module-level variable to hold the running total. Each time a new sale is made, add the new sale amount to the module-level variable. Doing so accumulates the sales over time.
Debugging Tip: You cannot declare a total inside a subprocedure that handles sales. That variable would be reinitialized each time the subprocedure is invoked.
totalSalesTax = totalSalesTax + taxThisSale
Counting things is the same as accumulating sums, except that you add one to the running count rather than a random sale amount. The basic form of counting across events of any kind is to define a module-level count accumulator and then to add one to it each time the countable event occurs:
totalWebPageHitCount = totalWebPageHitCount + 1
Calculation Program Example
Note: Be aware that there is a problem with the format command in general. The problem is that the discount amount is visually rounded by the FormatCurrency function to display in the "15% Discount" label. However, the calculation of the discount can create an answer that contains three or four decimal places. When the discount is subtracted from the Extended price, the answer can appear to be incorrect.
Convince yourself. Try this: 10 units at $39.95. The answer displayed for Extended price is $399.50, which is correct. The answer displayed for the discount is $59.93 (rounded up from the actual answer of 59.925). The amount displayed for the Discounted Price is $339.58, which is the rounded result of 399.50 – 59.925. The solution—without using the Round function because it has not been introduced yet—is to add 5/10ths of a penny (.005) to the discount. Then both the discount and the resulting discounted price will both appear to be correct and will be correct!
Hint: If you complete the Hands-On example at the end of the Chapter, you will know everything you need to complete your homework assignment.
Chapter Highlights:
STATEMENTS |
FUNCTIONS |
DATA TYPES |
||
Const |
FormatCurrency |
Boolean |
||
Dim |
FormatDateTime |
Byte |
||
Option Explicit |
FormatNumber |
Currency |
||
FormatPercent |
Date |
|||
Val |
Double |
|||
Integer |
||||
Long |
||||
Single |
||||
String |
||||
Variant |
Test Yourself: What is the output of the following code? (Type it into a new VB project in the code window under Form_Click and see what happens.)
Dim intNum1 as Integer
Dim intNum2 as Integer
Dim intResult as Integer
intNum1 = 5
intNum2 = 3
intResult = intNum1 + intNum2
Print "The sum is ", intResult
intResult = intNum1 * intNum2
txtResult.text = intResult
Debugging Hints
Test Yourself: What are the errors?