Programming using VB6
VARIABLES
A
variable is a memory
location that stores a value.
Variables must be NAMED in order to have a specific memory location assigned to
them.
Variables allow values to be represented by meaningful names that make program
code easier to read.
Before using a variable it should be declared with a DIM Statement.
DIM means Dimension
The
DIM Statement includes the identifier and data type.
The
name of the variable is known as the Identifier.
The
identifier is
how the value will be referred to within the program.
The
data type of
the
variable indicates what kind of value it will store.
For example, the statement:
DIM
dbllRadius
as
Double
declares a variable
dbllRadius
that stores data of type Double.
A
Double is a
numeric
value that
possibly contains a decimal portion.
The identifier for DOUBLE is
“dbl”
|
A
variable declaration such as the statement above reserves space in the
computer's memory for a value.
Therefore if you write
dblRadius
= 12.3
The
program reserves a value of 12.3 for the variable named dblRadius
DO
NOT reverse the
variable identifier and the value
12.3 =
dblRadius is NOT ACCEPTED (it will give you an error)
YOU
CAN write expressions on the
right hand side of an assignment statement.
VALID Example:
dblCircleArea = 3.14 * dblRadius ^ 2
This expression
calculates the area of a circle.
The program code for the area of the
circle application can be modified to use variables.
|
Look at the code below and rewrite the Area of Circle Program
to include
Variables.
CONSTANTS
A variable is a
memory location whose value can be changed.
A
constant
is a memory location whose value cannot
be changed.
The identifier
for a constant is ===è
CONST
A constant must
be declared using Const
For
example,
The
following statement declares a constant dblPi with a value of 3.14:
Const dblPi as
Double = 3.14
The
cmdCalculate-Click
procedure in the
Circle application can be
modified to include a named constant. Note that as a matter
of good programming style, constants are declared before variable declarations
at the beginning of a procedure:
One
common error is to
include a program statement that tries to
change
the value of a constant, as in the following:
Private Sub
cmdCalculate-Click()
Const dblPi as
Double = 3. 14
Dim
dblRadius as
Double
Dim
dblCircleArea as
Double
dblRadius
= 10
dblCircleArea
= dblPi *
dblRadius
^
2
lblAnswer.Caption = dblCircleArea
End Sub
Const
dblPi as
Double = 3. 14
dblPi = 22/7 ‘This is an Error
Programming Exercises
|