Data Typing

advertisement
Computer Applications
____________________________________________________________________
Web Address: http://gmitweb.gmit.ie/computing/staff/lkissane/
Data Typing
Computer programs are designed to manipulate different kinds of DATA.
VisualBASIC for example handles 10 different data types.










BOOLEAN Handles TRUE or FALSE values
BYTE
A single ANSI character (Code 0 to 255)
CURRENCY Decimal fractions, such as Euros and cents
DATE
An 8-character date
DOUBLE Double-precision floating point numbers with 14 decimal places
INTEGER Whole numbers from –32,768 to 32,767
LONG
Whole numbers approximately +/- 2 billion
SINGLE
Single precision floating point numbers in range +/-1E-45 to 3E38
STRING
A sequence of zero or more characters from the keyboard enclosed in apostrophes
VARIANT Automatically converts from one type to another, as needed
The arithmetic operations you can perform in VisualBasic are:
Operator
Operation
+
*
/
^
Addition
Subtraction
Multiplication
Division
Exponentiation e.g. 2^3 = 8
INTEGERS
A whole number represented by a sequence of digits optionally prefixed with a plus sign (+) or
minus (-) sign. An unsigned integer is considered the same as that integer with a leading plus i.e.
325 & +325 are identical. Every negative integer MUST begin with a minus sign. Leading zeros are
insignificant –0026 same as –26. No commas or non-digits characters allowed.
L.Kissane
Page 1
06/02/2016
Computer Applications
INTEGER CONSTANTS
Values that do not change during program execution.
VALID
0
137
-2516
+17745
INVALID
5,280
16.0
--5
7-
Floating Point data
The above rules for integers also apply to floating point numeric data values except real values
also carry a decimal point.
Data Typing in VisualBasic
The most common types of variables and constants in VisualBASIC are string, integer and currency.
If the data is to be used in a calculation then it MUST be numeric (usually integer or currency); if
it is not used in a calculation, it will be string. Use currency as the data type for any decimal
fractions in business applications.
Examples:
Contents
Data Type
Reason
RSI number
Pay Rate
String
Currency
Not used in calculation
Used in calculation. Contains a decimal point
Hours worked
Phone No
Quantity
Currency
String
Integer
Used in calculation
Not used in calculation
Used in calculations, contains a whole number
Naming Rules





Programmer’s responsibility to identify (name) every variable, named constant, module, form
etc.
Names must be from 1 to 255 characters long
Consist of letters, digits or underscores – no spaces or keywords e.g. PRINT, NAME, VALUE
etc.
Identifiers must be meaningful - do not use X,Y,Z or A,B,C
Precede each identifier with a lowercase prefix specifying type followed by a capitalized word
of the name e.g. curPayRate, strRSIno, strPhoneNo, intQuantity
L.Kissane
Page 2
06/02/2016
Computer Applications
L.Kissane
Page 3
06/02/2016
Computer Applications
Constant Identifiers
The purpose here is to establish a constant (i.e. unchanging value) to a data constant. Takes the
form
Const Identifier [Identifier as Datatype] = constant
Where identifier is a valid user-defined identifier and constant is a valid data type from the above
list E.g.
Const Speedlimit as Integer =55
Here 55 is the value of the integer constant identifier speedlimit and will always be 55.
PRINT (speedlimit) would cause integer 55 to be displayed.
You declare named constants using the keyword Const in VisualBASIC. You give the constant a
name, a data type and a value. Once this is declared its value cannot be changed during program
execution.
Advantages:
 Code is easier to read e.g. programmers should NOT use ‘magic numbers’ that suddenly
appear without explanation e.g. popchange = (0.1758 – 0.1257) * population
 If these numbers need to be changed, someone must search through the program to
determine what they represent and locate all places where they appear. Using constants this
only has to be done once!
Examples
Const sngBirthRate as Single = 0.1758
Const strCompanyname as String = “R ‘n R – for Reading ‘n Refreshment”
Const curSalesTax = 0.08
Assigning values




Strings must be in double quotation marks
Numeric constants may contain only (0-9), a decimal point and/or a sign (+ or - )
No commas, currency symbols or suffix
String literals may contain letters, digits and any special characters including quotation
marks for preservation e.g. “He said, “”I like it!”” produces the string he said, “I like it!”
L.Kissane
Page 4
06/02/2016
Computer Applications
Intrinsic Constants
These are system defined constants. These are stored in library and available for use in VB
programs e.g. 8 VB colour constants
VbBlack
VbRed
VbGreen
VbYellow
VbBlue
VbMagenta
VbCyan
VbWhite
Declaring Variables in VB
Use Dim statement (which is short for Dimension a store space in memory) e.g.
Dim Identifier [ As DataType] e.g.
Dim strCustomer as String
Dim intTotalSold as String
Dim sngTemperature as Single etc.
When you declare a variable the amount of memory reserved depends on its data type
e.g.
Type
Boolean
Byte
Currency
Date
Double
Integer
Long
Single
String
Variant
L.Kissane
Memory Allocated in Bytes
2
1
8
8
8
2
4
4
10 + 1 byte for each character in string
For numbers 16 bytes, for characters 22 bytes +1 per character
Page 5
06/02/2016
Computer Applications
Variables in VisualBasic
A variable is a symbolic name(identifier) for a memory location whose contents may be established
or changed during program execution.
Differences between constant identifiers and variables



Values of all constant identifiers have been defined by the time program execution begins but
none of the variables have values
Value of a constant identifier cannot be changed during program execution
Variables can have any number of values
Suppose length is a constant identifier that has an integer value and distance is an integer variable
then distance = length is OK but length = distance is not!
Arithmetic in Visual BASIC
Arithmetic is evaluated in Visual Basic using simple arithmetic expressions e.g. 3+4*2. What is the
result? If the addition is done first, the result is 14. However, if the multiplication is done first, the
result is 11. The order of precedence in arithmetic solves the problem.
Evaluation
1.
2.
3.
4.
Negation
Exponentiation
Multiplication & Division
Addition & Subtraction
Parentheses should be used where necessary to clarify the meaning of an expression. When there are
no parentheses, the arithmetic operations are performed in the following order:
In the
()
^
*/
+-
event of ties the leftmost operation is carried out first e.g.
Inner to outer, left to right
Left to right in expression
Left to right in expression
Left to right in expression
Arithmetic expressions can appear in PRINT statements within a picture box control or assignment
statements, e.g.
(a) Picture1.Print (arithmetic expression)
(b) variable := arithmetic expression
Picture1.print (25+132)
X=25 +132
L.Kissane
or
(157 will be displayed)or
(x will hold 157 from now on assuming X is an integer)
Page 6
06/02/2016
Computer Applications
Arithmetic Rules:
 Integer expression is only valid within a given range( shown earlier)
 Symbols used for addition/subtraction are same symbols used as signs on numbers
 Minus sign in front symbolises negation which requires only 1 operand e.g. –5 means ‘the
negative of 5’
 Must use ‘*’ to symbolise multiplication and it cannot be implied as in arithmetic e.g. 6(-25) or
(-25)6 must be show as Picture1.print 6 * (-25)
 Zero divided by any non-zero integer produces integer zero.
 An attempt to divide any integer by zero results in a fatal error!
In programming you can perform calculations with variables, with constants and with the
properties of certain objects e.g. the Text property of a text box which in Visual Basic actually hold
strings of text. These MUST be converted using the VAL function e.g.
IntQuantity = Val(txtQuantity.Text)
CurPrice = Val(txtPrice.Text)
Formatting Data using Pre-Defined Functions
When you want to format data for display, either on the printer or screen use the formatting
functions:-
FormatCurrency
FormatNumber
FormatPercent
FormatDateTime
Examples
Variable
Value
Function
Output
CurBalance
sngAmount
mcurTotal
curBalance
curCorrect
curCorrect
1275.675
.9
1125.67
1234.567
.75
.75
FormatCurrency(curBalance)
FormatCurrency(sngAmount)
FormatNumber(mcurTotal,0)
FormatNumber(ccurBalance,2)
FormatPercent(curCorrect)
FormatPercent(curCorrect,1)
€1,275.68
€0.90
1,1126
1,234.57
75%
75.0%
L.Kissane
Page 7
06/02/2016
Computer Applications
You can format an expression as a date or a time. The expression may be a string that holds a
date or a time value, a date variable, or a function that returns a date. The named formats use
Windows regional settings.
Examples:
LblstartDate.Caption=FormatdateTime(sample,vbShortDate)
LblStartTime.Caption=FormatDateTime(“28/02/99”,vbLongdate)
Named Format
VbShortDate
VbLongdate
L.Kissane
Returns
dd/mm/yy
Day of Week, Month, Day, Year
Page 8
Example
28/02/99
Sunday, February 28,1999
06/02/2016
Computer Applications
L.Kissane
Page 9
06/02/2016
Download