Unit 2x - TJVisualBasic
Download
Report
Transcript Unit 2x - TJVisualBasic
Unit 2
Lesson 8
Data Types, Arrays, Constants and
Arithmetic
Data Types
• We deal with many kinds of data in our daily
life.
• For example, we need to handle data like
names, phone number, addresses, money, date,
stock quotes, statistics and more every day.
• In Visual Basic, data can be stored as variables,
constants or arrays.
Data Types
• Visual Basic classifies information into two
major data types,
numeric data type
non-numeric data type
Numeric Data Types
• Numeric data types comprises numbers that
can be calculated arithmetically using
standard operators such as addition,
subtraction, multiplication, division and
more.
•
Examples of numeric data types are
examination marks, height, body weight,
number of customers, stock price, price of
goods, bills, bus fares and more.
Numeric Data Types
TYPE
STORAGE
RANGE
Byte
1 byte
0 to 255
Integer
2 bytes
-32,768 to 32,767
Long
4 bytes
-2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values
Single
4 bytes
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for negative values
Double
8 bytes
4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency
8 bytes
-922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use
Decimal
12 bytes
+/- 7.9228162514264337593543950335 (28 decimal places).
Non-numeric Data Types
• Non-numeric data types are data that cannot
be manipulated using standard arithmetic
operators.
• They comprises the string data types, the
Date data types, the Boolean data types that
store only two values (true or false), Object
data type and Variant data type .
Non-Numeric Data
TYPE
STORAGE
RANGE
String(fixed length)
Length of string
1 to 65,400 characters
String(variable length)
Length + 10 bytes
0 to 2 billion characters
Date
8 bytes
January 1, 100 to December 31, 9999
Boolean
2 bytes
True or False
Object
4 bytes
Any embedded object
Variant(numeric)
16 bytes
Any value as large as Double
Variant(text)
Length+22 bytes
Same as variable-length string
Suffixes for Literals
• Literals are values that you assign to data.
• In some cases, we need to add a suffix behind a
literal so that VB can handle the calculation more
accurately. For example, we can use num =
DATA TYPE
1.3089# for a Double type data. SUFFIX
&
Long
!
Single
#
Double
@
Currency
String Literal
• In addition, we need to enclose string literals
within two quotations and date and time literals
within two # sign.
• Strings can contain any characters, including
numbers.
• The following are few examples:
memberName = “Turban, John.”
TelNumber = “1800-900-888-777″
LastDay = #31-Dec-00#
ExpTime = #12:00 am#
UNIT 2
Lesson 9
Variables and Constants
Variables and Constants
• Data are stored either as variable or
as constant.
• Variables are similar to mail boxes in a post
office. The contents of the variables change
from time to time, just like the mail boxes.
• In VB2013, variables are areas allocated by
the computer memory to store data.
Using Variables
• Variables – named memory location that stores a value.
• Variables allows the use of meaningful names which makes the
code easier to read.
• Data Type of the variable – indicates what kind of value it will
store.
• All variables SHOULD be declared with a Dim statement that
includes an identifier and data type
– Example: Dim dblRadius As Double
• Variable Declarations – reserves a space in memory for a
value.
Declaring Variables
•
We declare a variable by assigning name and data type.
•
Variables are usually declared in the general section of
the code windows using the Dim statement.
The syntax is as follows:
Dim VariableName As Data Type.
•
If you intend to declare more variables, you can declare
them in separate lines or you can combine them in one
line, separating each variable with a comma, as follows:
Dim VariableName1 As DataType1, VariableName2 As
DataType2, VariableName3 As DataType3
Variable Declaration
• A single Dim statement can be used to declare
multiple variables using commas.
– Example: Dim strName As String, intAge As Integer,
dblHeight As Double
– Good to put all integers together, strings, etc.
• Visual Basic initializes variables when they are
declared by default. Double, Single, Integer, Long,
& Currency are initialized to 0. String is set to an
empty string (“”) and Boolean is set to False.
If you don’t set a value they will be set
to the default values
Declaring Variables
• Visual Basic does not require variables to be
declared before they are used.
• This may lead to an error in your output.
– Example: Dim dblRadius As Double
–
dblRadis = 10 ‘dblRadius is misspelled
–
dblCircleArea = dblPi * dblRadius^2
– Answer will be 0
– dblRadius is 0 by default and never assigned to 10
Even though the program works your end result may be
incorrect
Dim
• Dim - is a keyword that stands for
dimension. A declared variable has
“dimension” because it has been assigned
space in memory.
• Identifier – is the name of the variable.
• Data type – indicates what kind of value it
will store.
Built-In Data Types
• Built-In Data Types
–
–
–
–
–
–
–
Single – numbers possibly containing a decimal
Double – numbers possibly containing a decimal
Integer integers only (no decimals)
Long – integers (no decimals)
Currency – numbers representing dollar amounts
String – set of characters
Boolean – True or False
Data Type Memory
• Each data type has their own memory
requirements for storing values.
• Single uses 4 bytes
• Double uses 8 bytes
• Integer uses 2 bytes
• Long uses 4 bytes
• Currency uses 8 bytes
• Boolean uses 2 bytes
• String uses 1 byte for each character in the string
Naming Conventions
• Identifiers should be descriptive and begin with an
appropriate prefix.
• sgl – Single
• dbl – Double
• int – Integer
• lng – Long
• cur –Currency
• str – String
• bln – Boolean
Single & Double
• Represents positive and negative real
numbers (floating point) decimals
• Single – can store numbers up to 3.4e38
• Double - can store numbers up to 1.8e308
Integer and Long
• Represents positive and negative integers.
• Integer can go up to 32,767 (a number)
• Long is used for numbers greater than 32,767.
• Trying to store a decimal in an integer
location will round up the decimal if it is
greater than 5.
– 4.7 = 5.0
Boolean
• Represents True or False
• Yes/No or on/off or open/closed
Currency
• Represents real numbers that are money
values.
• Currency can store values with up to four
digits to the right of the decimal place and
15 digits to the left of the decimal place.
String
• Represents a set of characters called string.
Can include just about everything, numbers,
letters, symbols, spaces etc…, just along as it
is in double quotes.
– Example:
Dim strLastName as String
strLastName = “Grassman”
Variable Names
• We have to assign name to every variable.
• To name a variable, you have to follow a set
of rules. The following are the rules when
naming the variables.
It must be less than 255 characters
No spacing is allowed
It should not begin with a number
Period is not allowed.
Examples
VALID NAMES
INVALID NAME
My_Mobilephone
My.Mobilephone
Apple123
123Apple
Long_Name_Can_beUSE
LongName&Canbe&Use
*& is not acceptable
Example
Private Sub Form1_Load(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles MyBase.Load
Dim strPassword As String
Dim strYourName As String
Dim intFirstnum As Integer
Dim intSecondnum As Integer
Dim intTotal As Integer
Dim dtedoDate As Date
End Sub
You may also combine the above statements in one line, separating
each variable with a comma, as follows:
Dim strPassword As String, strYourName As String, intFirstnum
As Integer,………….
Variable Assignment
• Assignment operator – equal symbol (=).
• Variable is given a value through assignment.
• Variables assignment must be written so the
variable is on the left side of the equal sign
and the value on the right.
– Example: dblRadius = 12.3
• If there is an expression on the right side of
the equal symbol, the expression is evaluated
first and the answer is stored in the memory
location
Expressions
• Expression must be used on the right side
of the assignment.
– Example: dblCircleArea = 3.14 * dblRadius ^2
Example
Private Sub Button1_Click(sender As Object, e As
EventArgs) Handles Button1.Click
Dim YourMessage As String
YourMessage = “Happy Birthday!”
MsgBox(YourMessage)
End Sub
When you run the program, a message box that shows the
text “Happy Birthday!”
Assigning Values to Variables
•
•
After declaring variables using the Dim statements, we
can then assign values to these variables. The syntax of is
Variable = Expression
The variable can be a declared variable or a control
property value. The expressions include a mathematical
expression, a number, a string, a Boolean value (true or
false) and more, as illustrated in the following examples:
intFirstNumber =100
intSecondNumber = firstNumber - 99
strUserName = ”John Lyan”
intThirdNumber = Val(usernum1.Text)
inttotal = intFirstNumber + intSecondNumber +
intThirdNumber
intX=sqr(16)
intNum = int(Rnd * 6) + 1
Errors
•
•
An error occurs when you try to assign a value to a variable of
incompatible data type. For example, if you have declared a variable as
an integer but you assigned a string value to it, an error occurred.
Example
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim YourMessage As Integer
YourMessage = “Happy Birthday!”
MsgBox(YourMessage)
End Sub
•
When you run the program, the following error messages will appear in
a dialog box. You can either break the program or continue to run the
program.
Scope of Declaration
•
Beside using the Dim keyword to declare the data, we may also use
other keywords to declare the data. Three other keywords are private,
static and public. The syntaxes are as shown below:
Private VariableName as Datatype
Static VariableName as Datatype
Public VariableName as Datatype
•
•
•
•
•
The aforementioned keywords indicate the scope of declaration.
Private declares a local variable, or a variable that is local to a
procedure or module.
Static keyword declares a variable that is being used multiple times,
even after a procedure has been terminated. Most variables created
inside a procedure are discarded by Visual Basic when the procedure is
finished.
Static keyword preserve the value of a variable even after the
procedure is terminated.
Public is the keyword that declares a global variable, which means it
can be used by all the procedures and modules of the whole program.
•
Declaring Constants
A Constant’s value does not change during the running of the program. The syntax to declare a
constant is
•
Const Constant Name As Data Type = Value
Example
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Const sglPI As Single = 3.142
Dim sglRadius As Single = 10
Dim sglAreaCircle As Single
AreaCircle = sglPI * sglRadius ^ 2
MsgBox(“Area of circle with ” & “radius” & sglRadius & “=” & sglAreaCircle)
End Sub
•
Press F5 to run the program and clicking the button produces the following message:
Using Named Constants
• Constant is a named memory location
which stores a value that cannot be
changed at run-time from its initial
assignment.
• Const statement is used to declare a
variable.
– Example: Const dblPI As Double = 3.14
• Const should be declare before variable
declarations.
Keywords
• Keywords- has special meaning to the
compiler. Cannot be used as user declared
variables.
– Example: Double, Const
• Case Sensitivity in Identifier
– Visual Basic is not Case Sensitive.
Rounding
• When a decimal number ends with .5. Visual
Basic will round up if the decimal number is
an odd number and round down if the
decimal number is even.
• Example:
Dim intX as Integer
intX = 5.5 ‘intX is assigned 6 because intX is an Integer and 5 is odd
intX = 6.5 ‘intX is assigned 6 because intX is an Integer and 6 is
even
Automatic Type Conversion
• Visual Basic automatically converts data to
match the type of the variable it is being assigned
to.
• (Implicit-computer changes it)
– Example: Dim intSum As Integer
intSum = 6.7 ‘intSum will get 7
• Data typed in a text box is a String
• The String will be converted by Visual Basic to
the appropriate data type when assigning it.
Invalid data type conversion
• Trying to assign a value into an inappropriate
data type causes an error.
– Example: intSum = “abc” ‘Trying to assign a
string to an Integer.
Special Division Operators
• \ - Integer Division – truncates the decimal portion
of the quotient which results in an Integer.
– Example: intSum = 20\7 ‘intSum is assigned 2
• Mod – Modulus Division – returns the remainder
resulting from division.
– Example: intSum = 20 Mod 7 ‘intSum is assigned 6
Syntax Error
• Syntax Error – statements that violates the
rules of Visual Basic
– Example: Dim intX As Integer = 12 ‘Syntax
Error – Can’t assign variables in the
declaration.
– Syntax Error are displayed in Red in the Code
Editor.
Run-time errors
• Errors that occur during the application run.
• Dialog box displays the error
• Clicking the button highlights the statement
causing the runtime error.
UNIT 2
Lesson 10
Creating Arrays
Introduction to Arrays
•
An array is a group of variables belongs to the same data type .
When we deal with a single item, we only need to declare one
variable. However, if we have a list of similar type of data, it is
better to declare an array of variables.
•
For example, if we need to enter one thousand phone numbers, it
would be very tedious if we were to declare one
thousand different phone numbers. Therefore, instead of
declaring one thousand different phone numbers, we need to
declare only one array. We can differentiate each phone number
in an array by using subscript, the index value of each item, for
example phnum(1), phnum(2),phnum(3) …….etc. , this makes
declaring variables more streamline and much more time saving.
The Dimension of an Array
•
•
•
•
•
Arrays can be one dimensional or multidimensional.
A one dimensional array resembles a table that comprises one
row of items or one column of items.
A multi-dimensional array is a table comprises rows and columns
of items.
The way to reference an element in a one dimensional array
is ArrayName(x), where x is the index or position number of the
element.
The way to reference an element in a two dimensional array is
ArrayName(x,y), where (x,y) is the index of the element. Usually
it is sufficient to use one dimensional and two dimensional array,
you only need to use higher dimensional arrays if you need to
deal with more complex problems.
Arrays
One Dimensional Array
Customer Name
Name(0) Name(1)
Name(2)
Name(3)
Name(4)
Name(5)
Two Dimensional Array
Name(0,0)
Name(0,1)
Name(0,2)
Name(0,3)
Name(1,0)
Name(1,1)
Name(1,2)
Name(1,3)
Name(2,0)
Name(2,1)
Name(2,2)
Name(2,3)
Name(3,0)
Name(3,1)
Name(3,2)
Name(3,3)
Name(6)
Declaring an Array
•
•
We use Public or Dim statement to declare an array, similar to the way
we declare a single variable. The Public statement declares an array that
can be used throughout an application while the Dim statement declares
an array that can be used only in a local procedure.
The statement to declare a one dimensional array is as follows:
Dim arrayName(n) as dataType
•
where n indicates the last index in the array. Note that n does not
indicate the total number of elements in the array; it is one less than the
total number of elements (n-1) because the first element is always the
zeroth element. The first element is arrayName(0), the second element is
arrayName(1), the third element is arrayName(2) and so on.
•
The number of elements in an array is also known as length, we can
retrieve the length of an array using the syntax arrayName.length
For example
Dim CusName(10) as String
declares an array that comprises 11 elements starting from
CusName(0) through to CusName(10)
To determine the length of an array, you can write the following
code:
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
Dim CusName(10) As String
MsgBox(CusName.Length)
End Sub
Running the program produces a message box that displays the
length of the array i.e. 11
Results
Starting Indexes
•
We can also declare an array with a non-zero starting index by
initialize an index value other than zero, as follows:
Dim arrayname As DataType()
arrayName = New String(){1,2,3,….,n)
This array will consists of n elements, starting with arrayName(1)
Example
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
Dim CusName As String()
CusName = New String() {1, 2, 3}
MsgBox(CusName.Length)
End Sub
•
The message box displays the length as 3
2D Arrays
•
The statement to declare a two dimensional array is as
follow:
Dim ArrayName(m,n) as dataType
• where m and n indicate the last indices in the array. The
length of the array is (m+1) x (n+1)
Example
Private Sub Form1_Load(sender As Object, e As
EventArgs) Handles MyBase.Load
Dim CusName(5,6) As String
MsgBox(CusName.Length)
End Sub
• Running the program and the message box displays a
length of 42 (6x7)
Result
Example of List Box
Private Sub Form1_Load(sender As Object, e As
EventArgs) Handles MyBase.Load
Dim num As Integer
Dim CusName(5) As String
For num = 0 To 5
CusName(num) = InputBox(“Enter the customer
name”, “Enter Name”)
ListBox1.Items.Add(CusName(num))
Next
End Sub
This program prompts the user to enter names in an input box
for a total of 6 times and the names will be displayed in a list
box
RESULT
UNIT 2
LESSON 11
Mathematics
Operators
• For VB2013 to carry out
mathematical operations, we
need to write code that
uses arithmetic operators.
• Mathematical operators are
very similar to the normal
arithmetic operators, only
with some slight variations.
• The plus and minus operators
are the same while the
multiplication operator use
the * symbol and the division
operator use the / symbol.
MATHEMATICAL
OPERATOR
FUNCTION
EXAMPLE
+
Addition
1+2=3
–
Subtraction
10-4=6
^
Exponential
3^2=9
*
Multiplication
5*6=30
/
Division
21/7=3
Modulus(returns
the remainder of
Mod
an integer division) 15 Mod 4=3
Integer
Division(discards
Example
We insert two text boxes, four labels and a button. Click the button and enter the
code as shown below. When you run the program, it performs four basic arithmetic
operations and displays the results on the four labels.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim dblNum1, dblNum2, dblSum dblDifference, dblProduct, dblQuotient As Double
dblNum1 = TextBox1.Text
dblNum2 = TextBox2.Text
dblSum = dblNum1 + dblNum2
dblDifference = dblNum1 - dblNum2
dblProduct = dblNum1 * dblNum2
dblQuotient = dblNum1 / dblNum2
Label1.Text = dblSum
Label2.Text = dblDifference
Label3.Text = dblProduct
Label4.Text = dblQuotient
End Sub
Program
This program employs the Pythagoras Theorem to calculate the
length of hypotenuse c given the length of the adjacent side a and the
opposite side b. For those of you who have forgotten the formula for
the Pythagoras Theorem, it is written as
c^2 = a^2 + b^2
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim a, b, c As Single
a = TextBox1.Text
b = TextBox2.Text
c = (a^2 + b^2)^(1/2)
Label3.Text=c
End Sub
(Do NOT use SINGLE letters as MEMORY LOCATIONS
NAMES)
BMI Calculator Program
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArsgs)
Handles Button1.Click
Dim dblHeight, dblWeight, dblBmi As
Double
dblHeight = TextBox1.Text
dblWeight = TextBox2.Text
dblBmi = (dblWeight) / (dblHeight ^ 2)
Label4.Text = dblBmi
End Sub
Programming Style
• Variables and constants should be named so that they
are quickly and clearly understandable to the reader.
Visual Basic Programming Guidelines
5*3+2*3
Better written as
(5 * 3) + (2* 3)
• Object names that begin with 3 letters descriptive
of the object.
• Comments that explain and clarify code
• Use parentheses in Expressions if needed to
better understand what is intended.
• Variables and constants with meaningful
identifiers to represent values. Prefix identifies
data type
• Option Explicit statement
• Variables of the appropriate data type
Continued
Variables declared at the beginning of the
procedure that they are used in
Constants to represent unchanging values
Constants declared at the beginning before
variable declarations
Statements in the procedures are indented
with a tab
More arithmetic projects you work on:
Area of a triangle
Area of a rectangle
Area of a circle
Volume of a cylinder
Volume of a cone
Volume of a sphere
Compound interest
Future value
Mean
Variance
Sum of angles in polygons
Conversion of lb to kg
Conversion of Fahrenheit to Celsius