Objectives
To determine what data types VB supports; how to declare variables, and how to assign data
to variables
To able to use Arithmetic Operators
To use and understand the Val( ), Str( ), and isNumeric Functions
To apply the rule of arithmetic operator precedence
To able to write subroutines that solve mathematical problems
Notes
Programming involves data and ways of manipulating these data. Thus, you should learn how to
represent data in the computer.
IN FOCUS: VARIABLES, TYPES, DECLARATION, AND SCOPE
You often need to store values temporarily when performing calculations with Visual Basic. In VB,
you can store values in containers called variables. Generally, variables have a name (a string
you use to refer to the variable when you want to fetch or store value in the variable) and a data
type (which determines the range of values the variable can store and the operations defined for
that type).
Data types control the internal storage of data in Visual Basic. How do we associate a type to a
variable? VB does this automatically. By default, Visual Basic uses the Variant data type. But
programmers can always associate variables to a type explicitly.
The following table enumerates the common VB data types:
Data Type
Boolean
Byte
Double
Integer
Long
String
Variant
Variable Declaration
Data have different sizes, thus a variable that would contain a String value should have enough
space to accommodate strings. Variable declaration specifies how much space VB should allocate
for a variable.
How do we declare variables? You use the Dim statement through the following syntax:
Dim <var_name> As <data_type>
The following are examples:
Dim strName As String
Dim A As Boolean, B As Integer
Scoping Variables
A variable is scoped as either a procedure-level (local) or module-level variable. This depends on
how it is declared.
Scope
Procedure-level
Private
Variables are private to the
procedure
in
which
they
appear.
Public
Not applicable. You cannot
declare public variables within
a procedure.
End Sub
Note: Variables declared within
a procedure are by default
private the variables can only
be
accessed
within
the
procedures scope.
Module-level
Declaration:
You
create
module-level private variables
by declaring them with the
Private
keyword
in
the
Declarations section at the top
of the module.
Declaration:
You
create
module-level public variables
by declaring them with the
Public
keyword
in
the
Declarations section at the top
of the module.
Note: You can declare 2 different variables with the same name but these variables must be
declared in different scopes. For example, you could have a public variable named Temp and then,
within a procedure, declare a local variable named Temp. If we refer to variable Temp within the
procedure, we would access the local variable. References to Temp outside the procedure would
access the public variable.
IN FOCUS: ASSIGNMENT OPERATOR
We use the assignment operator = to assign data to a variable. Assigning data to a variable is
simply storing a value to the variable. The syntax is as follows:
<var_name> = <expression>
<var_name> is a variable name (which you might have declared using the Dim statement).
<expression> can be a literal, another variable, a mathematical expression, or a function call. Take
the following examples:
Assigning a literal to a variable
age = 18
stude_name = Jay Fernandez
Assigning the value of a variable to another variable
grade = score
Assigning the result of a mathematical expression
grade = score1 + score2
Always bear in mind that the left and right hand side values of the assignment operator should be
of the same data type or at least of compatible type. You cannot assign a String value to a Double
variable.
Operat
or
+
Example
Description
Adds two values
Score1 +
Score2
Price
Discount
Price
*
Discount
Total / 2
Total \ 2
Mod
5 Mod 2
^
-
2^2
-2
You can combine several mathematical expressions in one expression as in the example:
grade = (score1 + score2 + score3) / 3
IN FOCUS: OPERATOR PRECEDENCE
Another matter that you should take note of is operator precedence. Precedence is the order of
computation. ^ is evaluated first, then * and /, then + and -. If there are * and / in an expression,
execution is done from left to right. This holds true to + and -. Let us demonstrate this in the
following examples:
The expression 2 + 3 * 4 is equal to 14. This was computed by doing the multiplication first before
addition (since multiplication has higher precedence over addition).
The expression 4 * 3 / 2 is equal to 6. We evaluate this expression from left to right, which is by
doing the multiplication first before division.
You can override the operator precedence by using parentheses. VB always evaluates expressions
enclosed in parentheses before anything else in the expression. Consider the following expression:
4 * (2 + 3)
This is equal to 20, computed by adding 2 and 3 and multiplying the sum by 4. Without the
parentheses, the value of the entire expression is 11 (multiplying 4 with 2 and adding 3 to the
product).
IN FOCUS: VAL(), STR(), AND ISNUMERIC FUNCTIONS
The Val(), Str(), IsNumeric Functions are useful for data conversion: from numbers to Strings and
from Strings to numbers. Val() converts Strings to numbers. Str() complements Val() it converts
numbers to Strings. IsNumeric() returns True if a String argument can represent a number.
Val() is useful when you want to convert e.g. the Text property of a TextBox to a number. This is
applicable in cases when you require the user to enter a number in the TextBox (e.g. the users
age). The Text property of TextBoxes and the Caption property of Labels are Strings in type, thus
conversion must be done if you need their number value. You use IsNumeric() in cases when you
need to verify if whether a particular value can be represented as a number. For example, if you
require the users age, and the user enters letters, you might want to notify the user of wrong input.
The following are examples of how we use the 3 functions.
strNumber = 122
intNumber = Val(strNumber)
strNum = Str(intNumber)
intAge = Val(txtAge.Text)
y = IsNumeric(intNumber)
Lesson in Action
The application asks for the 2 numbers and outputs The average of the 2 numbers is <average>.
1. Create a new project.
2.
For the Form control, set the following properties:
Name
frmMain
Caption
Arithmetic Application
MaxButton
False
StartUpPosition
Center Screen
Height
3945
Width
5445
BackColor
White
3. Drag 3 Labels to the Form.
Set the following Properties for the first Label:
Name
BackStyle
Caption
Font
Top
Left
Width
Height
Set the following properties for the second Label:
Name
BackStyle
Caption
Font
Top
Left
Width
Height
Set the following properties for the third Label:
Name
BackColor
Caption
Font
Width
Height
Top
Left
lblNum1
Transparent
First Number
Arial, Size 14, Regular
360
240
2175
495
lblLNum2
Transparent
Second Number
Arial, Size 14, Regular
960
240
2175
495
lblResult
Light Blue
None. Erase Default Value
Arial, Size 14, Italic
4815
975
1560
240
Name
txtNum1
Font
Arial, Size 14, Regular
Text
None. Erase Default Value
Width
615
Height
495
Top
240
Left
2520
Set the following properties for the Second TextBox:
Name
txtNum2
Font
Arial, Size 14, Regular
Text
None. Erase Default Value
Width
615
Height
495
Top
840
Left
2520
5. Drag 2 CommandButton controls to the Form.
Set the following properties for the first CommandButton:
Name
cmdAverage
Caption
Average
Width
1695
Height
495
Top
2760
Left
1440
Set the following properties for the second CommandButton:
Name
cmdQuit
Caption
Quit
Width
1695
Height
495
Top
2760
Left
3360
6. Write the following procedures:
Private Sub cmdAverage_Click()
ave = (Val(txtNum1.Text) + Val(txtNum2.Text)) / 2
lblResult.Caption = "Average of the 2 numbers is: " & Str(ave)
End Sub
Private Sub cmdQuit_Click()
End
End Sub
7. Run your application.
8. Save your work as Lesson3.vbp.
On your Own
1. Write a code that declares these variables: your first name, your last name, your age, your
course, and whether you are old or new student.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
2. Write an application that accepts your age in a TextBox and then displays, when you click a
CommandButton, your age in 10 years time.
3. Make an application that asks for an item price, the discount (if any), and the cash given by
the customer. Compute and output the selling price and the change (cash selling price).
Refer to the Form below.