CHAPTER 2 - Variable, Constants and Calculations

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 29

CHAPTER 2

VARIABLES, CONSTANTS, AND


CALCULATIONS
Reference to: Bradley | Millspaugh
Overview

• Distinguish between variables, constants


and controls.
• Differentiate among the various data
type.
• Format values for output using the
formatting functions.

2
Variables vs Constants

Variables Constants
Memory locations that hold data that CAN be Memory locations that hold data that CANNOT be
changed during project execution. changed during project execution.
 Dim strname As String  Const curDiscountRate As
 Dim intCounter As Integer Currency = .15
 Dim sngTemperature As  Const strMessage As String =
Single “VB is a lot of fun!”

2 categories of constants:
i.Named constant: constants that you define
ii.Intrinsic constant: constants that are built into
VB (system-defined) and do not have to declare.
E.g: vbBlue, vbRed, vbGreen.

The reserved word Dim is really short for dimension, which means “size”
3
Data Type

• The data type of a variable constant indicates what type of info


will be stored in the allocated memory space.
• The default data type is variant.
– If you DO NOT specify a data type, your variable will be a
variant. Prefix of variant
– Eg: Dim vntChanging
• Advantages using variant : easy and it changes it’s appearance as
needed for each institution
• Disadvantages using variant: require more memory and operate
less quickly
• The best practice is to always specify the data type.
4
Data Type

Data Type Use For Storage Size


in bytes
Boolean True or False value 2
Byte 0 to 255, binary data 1
Clear Single Unicode character 2
Date 1/1/0001 through 12/31/9999 8
Decimal Decimal fractions, such as dollars/cents 16
Single Single precision floating-point numbers with six digits of accuracy 4

Double Double precision floating-point numbers with 14 digits of accuracy 8

Short Small integer in the range -32,768 to 32,767 2


Integer Whole numbers in the range -2,147,483,648 to +2,147,483,647 4

Long Larger whole numbers 8


String Alphanumeric data: letters, digits, and other characters Varies
Object Any type of data 4
5
Data Type

Data Type Use For Storage Size in bytes


then it will be numeric (usually integer @ currency).

Boolean True or False value 2


Byte A single ANSI character code (0 to 255) 1
If it is not used in calculation, it will be string.

Currency Decimal fractions, such as dollars and cents 4


Date 1/1/0001 through 12/31/9999 (An eight character date) 8
If the data will be used in a calculation,

Single Single precision floating-point numbers with six digits of 4


accuracy
Double Double precision floating-point numbers with 14 digits of 8
accuracy
Integer Whole numbers in the range -32,768 to +32,767 2

Long Larger whole numbers 8


String Alphanumeric data: letters, digits, and other characters 10 bytes plus 1 byte for
each character in
the string
Variant Converts from one type to another, as needed 16 (numbers)
22 + 1 each character
string
6
The most common type of variables and constants
Naming Rules

• Names must be 1 to 255 characters in length.


• They may consist of letters, digits, and underscore.
• They cannot contains spaces or periods.
• They must not be a reserved word.

7
Naming Conventions

• Identifiers must be meaningful. Choose a name that


clearly indicates its purpose.
• Precede each identifier with a lowercase prefix that
specifies the data type.
• Capitalize each word of the name (following the
prefix). Always use mixed case, never all uppercase.
• Eg: Capitalize each word

curTaxRate
A lowercase prefix indicates
data type of currency
8
Common Type of Prefix

• Here is a list of the most common data types and their prefixes:
Prefix Data Types
bln Boolean
cur Currency
dbl Double-
precision
floating point
dtm Date/time
int Integer
lng Long integer

sng Single-precision
floating-point
str String
vnt Variant
9
Check Point 1

Indicate whether each following identifiers conforms to the rules of VB:

1. int#sold
2. i Number Sold
3. int.Number.Sold
4. Sub
5. strSub
6. Caption
7. conMaximum
8. MinimumRate
9. curMaximumCheck
10. strCompanyName
10
Assigning Value to Constant

• Numeric constants may • Example of constants:


contain only the digits (0-9), Data Types Constant Value Example
a decimal, a sign (+ or -) at
Integer 5
the left side. 125
• You cannot include a comma, 2170
$, or any other special 2000
characters or a sign at the Single or 101.25
currency -5.0
right side.
Example Single “Visual Basic”
literals “ABC Incorporated”
Const curNumber As Currency = 1.113 √ “1415 J Street”
Const curNumber As Currency = +1.113 √ “102”
Const curNumber As Currency = 1,001 × “She said “”Hello.”””
Const curNumber As Currency = $1.001 × 11
Const curNumber As Currency = 1.001% ×
Assigning Value to Constant

• String literals may contain letters, digits and


special characters such as $#@%&*.
• The only problems comes when you want to
include a quotation mark in the string literal
• Example: Use 2 quotation marks together inside the literal.
"He said, "" I like it."“”

He said, "I like it."


12
Check Point 2

• Write a declaration for the following situations:


– You need variable for inventory control to store:
• Integer quantity
• Description of the iterm
• Part number
• Cost
• Selling price
– You need variable for payroll processing to store:
• Single-precision number of hours
• String employee’s name
• Department number(not used in calculation)
13
Scope of the Variable

• Scope (visibility) of variable: the variable can be used or seen in


the location where you place the Dim statement.
Visibility Description
A global variable (entire project). May be used in all procedures of a project.
A module level variable (for only one form).  Accessible from all procedures of a form.
 The lifetime of a module-level variable is
the entire time the form is loaded.
A local variable (for only one procedure).  May be used within the procedure in which
it is declared.
 The lifetime of a local variable is normally
one execution of a procedure.

14
Local Declaration

• Any variable that you declare inside a procedure is local in


scope.
• It is known only to that procedure.
Private Sub cmdCalculate_Click()
‘Calculate the price and discount

Dim intQuantity As Integer


Dim curPrice As Currency Good practice: Dims appear at the top of the procedure,
prior to the 1st use of the variable in the statement.
:
‘Write the appropriate formula
:
End Sub

Local var and constant do not have an additional prefix.

15
Module-Level Declaration

• At times you need to be able to use a variable or constant in


more than one procedure of a form.
• It may be used anywhere in the form.

Place the declaration for module-level var and constant in


the General Declarations section of the form

16
Check Point 3

• Write the declarations (Dim or Const statement) for each of the


following situations and indicate where each statement will
appear:
1. The total of the payroll that will be needed in a Calculation
event procedure and in a Summary event procedure.
2. The sales tax rate that cannot ne changed during execution of
the program but will be used by multiple procedures.
3. The number of participants that are being counted in the
Calculate event procedure, but not displayed until the
Summary event procedure.

17
Calculation

• Use the Val function to convert the property of a control to its


numeric form before you use the value in a calculation.
Dim intQuantity As Integer
Dim curPrice As Currency

'Convert input values to numeric variables


intQuantity = Val(txtQuantity.Text)
curPrice = Val(txtPrice.Text)

'Calculate the extended price


curExtendedPrice = inQuantity*curPrice
The Val function converts text data into a numeric value.

18
The Val Function

• The Val function converts an argument to numeric, begins at the left most
character.
• If that character is a numeric digit, decimal point or sign, Val converts the
character to numeric and moves to the next character.
• As soon as a nonnumeric character is found, the operation stops.
• Eg:
Contents of Numeric Value Returned by Contents of Numeric Value Returned by
Argument the Val Function Argument the Val Function
(blank) 0 123A 123
123.45 123.45 4B5 4
$100 0 -123 -123
1,000 1 +123 +123
19
A123 0 12.34.8 12.34
Arithmetic Operations
• The order of precedence:
1. Parentheses
Operator Operation 2. Exponentiation
+ Addition 3. Multiplication and division
- Subtraction 4. Addition and subtraction
* Multiplication • The following expressions would
/ Division be valid in maths, but not valid in
^ Exponentiation
Basic:
Mathematical Equivalent Basic
Notation Function
2A 2*A
3(X+Y) 3*(X+Y)
(X+Y)(X-Y) (X+Y)*(X-Y)

20
Check Point 4

• What will be the result of the following calculations using the


order of precedence?
Assume that: X = 2, Y = 4, Z = 3
1. X+Y^2
2. 8/Y/X
3. X*(X+1)
4. X*X+1
5. Y^X+Z*2
6. Y^(X+Z)*2
7. (Y^X)+Z*2
8. ((Y^X)+Z)*2
21
Using Calculations in Code

• Calculations are performed in assignment statements.


• Whatever appears on the right side of an assignment operator
(=) is assigned to the item on the left side.
• The left side may be the property of a control or a variable. It
cannot be a constant. Eg:
curAverage = curSum/intCount
lblAmountDue.Caption = curPrice – (curPrice * curDiscountRate)
txtCommision.Text = curSalesTotal * curCommissionRate

22
Formatting Data

• Use the formatting functions to format data for display, either


on the printer or on the screen.
• Formatting data means to control the way the output will look.
• VB has 4 formatting functions:
1. FormatCurrency
2. FormatNumber
3. FormatPercent and
4. FormatDateTime

23
FormatCurrency Function

FormatCurrency(NumericExpressionToFormat)

• This function returns a string of characters formatted as dollars


and cents.
• By default, the currency value displays a dollar sign, commas
and 2 position to the right of the decimal point.
Variable Value Function Output
sngAmount .9 FormatCurrency(sngAmount) RM0.90
curBalance 1275.675 FormatCurrency(curBalance) RM1,275.68
curAmount 231.2382 FormatCurrency(curAmount, 3) RM231.238
You can specify the number of decimal positions to display.

24
FormatNumber Function

FormatNumber(ExpressionToFormat)

• This function is similar to FormatCurrency.


• Generally display commas and two digits to the right of the
decimal points.

Variable Value Function Output


mcurTotal 1125.67 FormatNumber(mcurTotal, 0) 1,126
curBalance 1234.567 FormatNumber(curBalance, 2) 1,234.57
You can specify the number of decimal positions to display.

25
FormatPercent Function

FormatPercent(ExpressionToFormat)

• To display numeric values as a percent.


• This function multiplies the argument by 100, adds a percent
sign, and rounds to two decimal places.
Variable Value Function Output
curCorrect .75 FormatPercent(curCorrect) 75%
curCorrect .75 FormatPercent(curCorrect,1) 75.0%
curRate .734 FormatPercent(curRate) 73%
curRate .734 FormatPercent(curRate,1) 73.4%
curRate .734 FormatPercent(curRate,2) 73.40%

You can specify the number of decimal positions to display.


26
Sample of coding:
Private Sub Command1_Click()
FormatDateTime Function
Dim dtmSomeDate As String
dtmSomeDate = "29/10/85"
Label1.Caption = FormatDateTime(dtmSomeDate, vbLongDate)
End Sub

FormatDateTime(ExpressionToFormat, NamedFormat)
• To format an expression as a date and/or time.
• The expression may be a string that holds a date or time value, or a data type variable. Eg:

• The namedFormat use


computer’s regional settings.

lblStartDate.Caption = FormatDateTime(dtmStartDate, vbShortDate)
If you omit the optional
named format, the function

lblStartTime.Caption = FormatDateTime(“1/1/00”, vbLongDate)


returns the date using
vbGeneralDate.
lblDateAndTime.Caption = FormatDateTime(dtmSomeDate)
Named Format Returns Example

vbGeneralDate A date and/or time. 29/10/1985 6:01:24 PM

vbLongDate Day of week, Month Day, Year 29 October 1985

vbShortDate MM/DD/YY 29/10/1985

vbLongTime HH:MM:SS AM/PM 6:01:24 PM


27
vbShortTime HH:MM (24 hour clock) 18:01
Check Point 5

• Give the line of code that assigns the formatted output and tell
how the output will display for the specified value.
1. A calculated variable called mcurAveragePay has a value of 123.456 and
should display in a label called lblAveragePay.
2. The variable sngCorrect, which contains .76, must be displayed as a
percentage in the labele called lblPercentCorrect.
3. The total amount collected in a fund drive is being accumulated in a
variable called mcurTotalCollected. What statement will display the
variable in a label called lblTotal with commas and two decimal positions
but no ringgit signs?

28
ANY QUESTION…?

29

You might also like