Download - Data Type, Variables
-
7/28/2019 Data Type, Variables
1/59
DATA TYPE,VARIABLES AND
CONSTANTS
Chapter 21
-
7/28/2019 Data Type, Variables
2/59
Learning Objectives
By the end of this class, students should be able to :
Identify the various Visual Basic data types.
Use data types in programme.
Define local, module and global variable.
Use local, module and global variable.
Use constant in application.
2
-
7/28/2019 Data Type, Variables
3/59
Variables
Variables are named locations in memory (memorycells) in which we store data that will change at runtime. One value can be stored in a memory cell. If you put a new value in a memory cell, the old value will be
destroyed.
Variable names in VB: Are used to identify variables. Are different from the value of a variable. Must begin with letter and can use 0-9 in name. Cant include period, but can contain an underscore. Cant be over 255 characters. Not case-sensitive, but suggest using upper and lower case. Should not be a Visual Basic key word.
3
-
7/28/2019 Data Type, Variables
4/59
Variables (Cont.)
Example mnemonic variable names : sngProfitMargin
for Profit margin
curTaxes for taxes on this price
curAmountDue
for sum of price and taxes
curYTDEarnings for year to date earnings
4
-
7/28/2019 Data Type, Variables
5/59
Data Types
Data types indicates what types of information will bestored in the allocated memory space.
Two primary types of data: numeric and string (non-numeric).
5
-
7/28/2019 Data Type, Variables
6/59
2 categories :
Integer numbers without decimals.
e.g : 823 or -4560
Decimals numbers with decimal points.e.g : 8.23 or -400.25
Integers and decimals are stored differently inside
Visual Basic.Net and they are treated differently.e.g : -7 is not same as -7.00
Numeric6
-
7/28/2019 Data Type, Variables
7/59
Numeric
Numeric data can be used in arithmeticoperations : 3.154
2300 -34
0.0000354
7
-
7/28/2019 Data Type, Variables
8/59
String (non-numeric)
Is a non-numeric data consisting of a seriesof none or more characters.
A string may contain numeric digits, but isnever used for calculations.
Example :
Dogs 123-45-6789
Dr. Brown
8
-
7/28/2019 Data Type, Variables
9/59
Data Types (cont.)
Numeric data types can be subdivided into specific types: Currency
$55,567.78
Integer
255
Single 567.78
long (Integer)
35,455
Double
567.78129086
Boolean True (-1) or False (0)
9
-
7/28/2019 Data Type, Variables
10/59
Data Types (cont.)
String stores ASCII symbols (text) and numbers that are not used in
mathematical operations, but rather to provide for the input, output,and manipulation of sets of characters
Integers whole numbers (-32,768 to 32,767) Size 2 bytes
Long Integers whole numbers (-2,147,483,648 to 2,147,483,647) Size 4 bytes
Single
fractional numbers to seven significant digits - Size 4 bytes Double fractional numbers to 15 significant digits Size 8 bytes
10
-
7/28/2019 Data Type, Variables
11/59
Data Types (cont.)
Currency Use with monetary amounts and up to four digits to the right of the
decimal
Date
Use with dates Boolean Use only when the value of a variable is True or False
Variant Variable is assigned this type automatically if you dont declare the
variable as a specific data type, but takes up more memory
11
-
7/28/2019 Data Type, Variables
12/59
Variable Prefixes
Variable Type Prefix
String str
Integer int
Long Integer lng
Single sng
Double dbl
Currency cur
Date dtm
Boolean bln
12
-
7/28/2019 Data Type, Variables
13/59
Advantages of Coding Prefixes
Standard allows anyone who reads the code toimmediately determine data type of variable.
Words that are normally reserved words can beused. strPrint
Different objects can practically same name lblAge (label)
txtAge (text box)
13
-
7/28/2019 Data Type, Variables
14/59
Declaring Variables
Dim (Dimension) statement declares variables by assigning them aname and data type.
Declare ALL variables with the DIMstatement
General form:
Dim as
For example, Dim strHerName as String, sngMyValue as Single
Dim curAmountDue as Currency
* You can combine variable declarations in one Dim statement,separate by a comma, but you must use theAs Data Type clause foreach variable.
* Example :Dim Total As Integer, Sales As Currency.
*If you fail to declare a variable after the Option Explicit
statement has been entered, an error occurs at Run time
14
-
7/28/2019 Data Type, Variables
15/59
Option Explicit
Begin ALL Forms with the Option Explicit
command in the declarations procedure of thegeneral object.
This forces all variables to be declared. To automatically include Option Explicit,
go to the Tools|Options|Editor menuselection and check the box for Require
variable declaration.
15
-
7/28/2019 Data Type, Variables
16/59
Event-driven Input
In VB, we often use event-driven input where data istransferred from text boxes to variables by an event The user, not the program controls the sequence of events
An assignment statementgives a variable a value bysetting it equal either to an existing quantity or to a valuethat can be computed by the program.
Syntax of an assignment statement :
Control property or variable = value, variable, or property
Example : Company = Microsoft
16
-
7/28/2019 Data Type, Variables
17/59
Assignment Statement
Onlyvariables or controls can be on leftof the =sign statement while thevalue, variable or property
is on the right of the = sign.
17
-
7/28/2019 Data Type, Variables
18/59
Assignment Statement
sngPi = 3.141592
sngAlpha = 1
sngAlpha = sngAlpha
intN = intN + 1 3 = intN
intN +1 = intN
intN = "Five"
18
-
7/28/2019 Data Type, Variables
19/59
Comments
To explain the purpose of a statement, a commentstatement is added.
Any statement beginning with an apostrophe ()
or REM (Short for remark)is a comment. Comments can be added before statements or at the
end of statements by using an apostrophe.
Example :
This program displays the current date
or
Rem This program displays the current date
19
-
7/28/2019 Data Type, Variables
20/59
Simple Calculator20
-
7/28/2019 Data Type, Variables
21/59
Code for command button
Private Sub cmdSum_Click
Declare variablesDim intFirst as Integer, intSecond as Integer
Dim intSum as Integer
Assign values to variablesintFirst = txtFirstNum.Text
intSecond = txtSecondNum.TextEnd Sub
21
-
7/28/2019 Data Type, Variables
22/59
Functions
Function: Performs an action and returns a value.
an built-in operation that takes one or more more arguments andreturns a a single value.
A Common form of a function is :
variable=functionname(argument1, argument2 )
Not all functions require arguments such as the Date() function.
TheVAL() function is very common and is used to convert the Textproperty from a string to a number, which is assigned to Numericvariable.
E.g :
intQuantity = Val (txtQuantity.Text)
22
-
7/28/2019 Data Type, Variables
23/59
Using Functions
You cant use text boxes to do computations because the defaultproperty, Text, is a string and therefore must be converted to anumeric value before a calculation is performed.
It is necessary to convert the results of the computation that will
appear in another text box to a string value , using the Str()function, otherwise you would be assigning an integer value to it.
Example functions for converting data:
Val() to convert a string to a number
Str() to convert a number to a string
23
-
7/28/2019 Data Type, Variables
24/59
Code for Val() function
Private Sub cmdSum_Click()Declare variables
Dim intFirst as Integer,intSecond as Integer
Dim intSum as IntegerAssign values to variables as number
intFirst = Val(txtFirstNum.Text)intSecond = Val(txtSecondNum.Text)
End Sub
24
-
7/28/2019 Data Type, Variables
25/59
VB Code (Sum Button)
Private Sub cmdSum_Click()Declare variables
Dim intFirst as Integer, intSecond as Integer
Dim intSum as IntegerAssign values to variables as a number
intFirst = Val(txtFirstNum.Text)intSecond = Val(txtSecondNum.Text)intSum = intFirst + intSecondCalculate sum
display sum in sumtext boxtxtSum.Text = Str(intSum)
End Sub
25
-
7/28/2019 Data Type, Variables
26/59
26
Break Time!!!!
-
7/28/2019 Data Type, Variables
27/59
Uji Minda!!27
Soalan Pertama:
Anda menyertai perlumbaan. Anda mengejar danmemotong orang yang kedua. Sekarang Andaditempat yang ke berapa?
Jawapan: Jika jawapan anda tempat yang pertama,sudah tentu jawapan anda salah! Jika anda
memotong orang kedua sudah tentu andamengambil tempatnya, tempat kedua!
-
7/28/2019 Data Type, Variables
28/59
28Soalan Kedua :
Bapa Mary ada seramai lima orang anak gadis: 1.Nana, 2. Nene, 3. Nini, 4. Nono. Apakah nama anakgadisnya yang terakhir?
Namanya Mary
-
7/28/2019 Data Type, Variables
29/59
Properties Versus Methods
Dot notation is the way properties are set at run time. Syntax: object.property= value
txtSum.Text=Str(intSum)
The same notation is used to invoke a method for a control.
Methods define the actions a control can carry out.
Methods cant be used in assignment statements.
Syntax: object.method
txtFirstNum.SetFocus
The SetFocus method shifts the cursor to the named text box.
29
-
7/28/2019 Data Type, Variables
30/59
VB Code (Clear Button)
Private Sub cmdClear_Click()Clear text boxes with empty stringtxtFirstNum.Text = ""
txtSecondNum.Text = ""txtSum.Text = ""
Set focus back to first text boxtxtFirstNum.Setfocus
End Sub
30
-
7/28/2019 Data Type, Variables
31/59
Using Assignment Statements for Calculations
An expression is a combination of one or morevariables and/or constants with operators.
Aconstantis a quantity that does not change.
Operators are symbols used for carrying outprocessing :
Arithmetic, Comparison, Logical
31
-
7/28/2019 Data Type, Variables
32/59
Arithmetic Operators
() for grouping (A+B)
^ for exponentiation
Radius ^2 - for negation (subtraction) -Amount
* for multiplication
3 * price / for division PayRaise/Months
32
-
7/28/2019 Data Type, Variables
33/59
Arithmetic Operators
\ for integer division Divisor, dividend, and quotient are rounded to integers
7.1111\1.95 = 7\2 = 3
modfor modulus Integer remainder of an integer division
7.1111\1.95 = 7\2 = 3 with 1 remainder
+ for addition Price + Taxes
- for subtraction Salary - Deductions
33
-
7/28/2019 Data Type, Variables
34/59
Examples of valid Expressions
curInterest = curPrincipal * sngIntRate
sngArea = 3.14157 * sngRadius ^2
curUnitCost = curTotalCost / intUnit
intCounter = 0
intCounter = intCounter + 1
34
-
7/28/2019 Data Type, Variables
35/59
Hierarchy of Operations
1. Operations within parentheses ( )
2. Exponentiation (^)
3. Negation (-)4. Multiplication and division (*,/)
5. Integer division (\)
6. Modulo arithmetic (Mod)
7. Addition and subtraction (+,-)
8. String concatenation (&)
35
-
7/28/2019 Data Type, Variables
36/59
Arithmetic Example
3 * (Salary - Taxes)^2 + Bonus/Months
Order1 Subtract Taxes from Salary
2 Square the result
3 Multiply this result by 3
4 Divide Bonus by Months
5 Subtract result from first expression
36
-
7/28/2019 Data Type, Variables
37/59
Arithmetic Examples
Y = 3^2*41*2+3 Y = 37
X = [
X = 6556 sngAverage = ((70 + 80)/2 + 65)/2
sngAverage = 70
37
-
7/28/2019 Data Type, Variables
38/59
String Operators
For String Variables the only valid operation is thatof combining two strings into one
Use + or & to combine them
strBigday = Christmas + Day strBigday = Christmas & Day
Result of above is Christmas Day
38
-
7/28/2019 Data Type, Variables
39/59
Symbolic Constants
We can assign a name to a constantwith the Const statement
Examples Const Pi As Single = 3.14157
Const sngIntRate As Single = 0.07
Const intNumYears As Integer = 12
39
-
7/28/2019 Data Type, Variables
40/59
Vintage Videos40
-
7/28/2019 Data Type, Variables
41/59
Vintage Input-Process-Output
INPUT customer name
video name
video price
PROCESSING taxes = price x tax rate
amount due = price + taxes
OUTPUT taxes amount due
41
-
7/28/2019 Data Type, Variables
42/59
Pseudocode
Begin Procedure CalculateInput customer nameInput video name
Input video priceTaxes = video price times tax rateAmount due = video price + taxesOutput taxesOutput amount due
End procedure
42
-
7/28/2019 Data Type, Variables
43/59
Code for Calculate Button
Private Sub cmdCalc_Click()' declaring variables
Const sngTaxRate As Single = 0.07Dim curPrice As Currency, curAmountDue As CurrencyDim curTaxes As Currency
' changing format into currencycurPrice = CCur(txtVideoPrice.Text)curTaxes = curPrice * sngTaxRatecurAmountDue = curPrice + curTaxes
' changing format into text
txtTaxes.Text = Str(curTaxes)txtAmountDue.Text = Str(curAmountDue)
End Sub
43
-
7/28/2019 Data Type, Variables
44/59
Conversion Functions
ConversionFunction
Purpose
CBool Convert argument to BooleanCCur Convert argument to Currency
CDate Convert argument to Date
CInt Convert argument to Integer
CSng Convert argument to Single
CDbl Convert argument toDouble
44
-
7/28/2019 Data Type, Variables
45/59
Formatting Data
To display information in a pleasing format, we can use theFormat function:
General form :
variable or control = Format(variable,format expression)
Where the format expressions are in quotes and include;
Currency
Fixed
Standard
Percent
Scientific
E.g :
txtTaxes.Text = Format(curTaxes, currency)
45
-
7/28/2019 Data Type, Variables
46/59
Calculate button (Revised)
Private Sub cmdCalc_Click()Const sngTaxRate As Single = 0.07Dim curPrice As CurrencyDim curAmountDue As Currency
Dim curTaxes As CurrencycurPrice = CCur(txtVideoPrice.Text)curTaxes = curPrice * sngTaxRatecurAmountDue = curPrice + curTaxestxtTaxes.Text = Format(curTaxes, "Currency")
txtAmountDue.Text = Format(curAmountDue, "Currency")txtVideoPrice.Text = Format(curPrice, "Currency")
End Sub
46
-
7/28/2019 Data Type, Variables
47/59
Format Commands
Function Description
FormatCurrency Expression formatted as currencyalong with currency symbol
FormatDateTime Expression formatted as a date ortime
FormatNumber Expression formatted as a number
FormatPercent Expression formatted as apercentage with a trailing %
Round Rounds a number a specifiednumber of decimal places
47
-
7/28/2019 Data Type, Variables
48/59
Code to Clear Entries
Private Sub cmdClear_Click()clear all text boxes
txtCustName.Text = ""
txtVideoName.Text = ""txtVideoPrice.Text = ""txtTaxes.Text = ""txtAmountDue.Text = ""
set focus to this text box
txtCustName.SetFocusEnd Sub
48
-
7/28/2019 Data Type, Variables
49/59
Some Visual Basic Functions
Abs absolute value
Sqr square root
FV future value of an annuity
PV present value of an annuity
IRR internal rate of return
49
-
7/28/2019 Data Type, Variables
50/59
Some Visual Basic Functions
Pmt payment to pay off a loan
UCase/Lcase to convert to upper/lower case
Len length of a string
Date
system date DateValue date corresponding to string argument
50
-
7/28/2019 Data Type, Variables
51/59
Some Examples
txtAnswer.Text = Abs(-3) 3
txtAnswer.Text = Sqr(25)
5
txtAnswer.Text = UCase("VB is fun")VB IS FUN
txtAnswer.Text = Len("VB is fun")
9
txtAnswer.Text = Sqr(Len("four")) 2
51
-
7/28/2019 Data Type, Variables
52/59
Monthly Payment Calculator
Assume you wanted to determine the monthly paymentnecessary to pay off a loan at a given interest rate insome number of months Use PMT function
PMT(rate, nper, pv) where:
rate = monthly interest rate
nper = number of months
pv = negativevalue of loan amount
52
Th M thl P t F
-
7/28/2019 Data Type, Variables
53/59
The Monthly Payment Form
53
C t M thl P t
-
7/28/2019 Data Type, Variables
54/59
Compute Monthly Payment
54
Private Sub cmdCompute_Click()Declare variables
Dim curAmount As Currency, intMonths As Integer
Dim sngRate As Single
Dim curPayment As Currency
Convert variables in text boxes
curAmount = CCur(txtAmount.Text)
intMonths = CInt(txtMonths.Text)
Calculate monthly interest rate
sngRate = (CSng(txtRate.Text) / 100) / 12
Calculate payment
curPayment = Pmt(sngRate, intMonths, -curAmount)txtPayment.Text = Format(curPayment, "Currency")
txtAmount.Text = Format(curAmount, "Currency")
End Sub
-
7/28/2019 Data Type, Variables
55/59
EXERCISE
Create and complete the followingcalculation
-
7/28/2019 Data Type, Variables
56/59
Exercise 1 Simple Calculator
-
7/28/2019 Data Type, Variables
57/59
Exercise 2 - Vintage Video57
-
7/28/2019 Data Type, Variables
58/59
Exercise 3 Monthly Payment Calculator
-
7/28/2019 Data Type, Variables
59/59
THaNK YoU