0% found this document useful (0 votes)
22 views45 pages

Slides Variables and Data Types

The document discusses variables and data types in Visual Basic. It covers topics like declaring variables, data types in VB including numeric and non-numeric types, and variable scope and declaration. Examples are provided throughout to explain concepts.

Uploaded by

David Tawiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views45 pages

Slides Variables and Data Types

The document discusses variables and data types in Visual Basic. It covers topics like declaring variables, data types in VB including numeric and non-numeric types, and variable scope and declaration. Examples are provided throughout to explain concepts.

Uploaded by

David Tawiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

CICS 313:

Visual Basic Programming

Variables and Data Types


Ghana Technology University College
Lecturer – Dr. Forgor Lempogo
2021
VB Language Fundamentals

VB Statements

Data Types

Operators in VB

Declaring and Assigning Variables

Declaring Constants

Static Variable Types

2 CICS 313:Visual Basic Programming - GTUC 2021 Delivery


Objectives
After completing this section, you will be able to:

Create an use VB statements

understand the fundamental language features

of VB
Identify supported VB data types

Explain how to create variables and constants

Use built-in functions to convert different data-

types
3 CICS 313:Visual Basic Programming - GTUC 2021 Delivery
What is a Variable?
A variable is a portion of memory to store a
determined value.
Computer memory locations used to store data
while an application is running
Use a meaningful variable name that reflects the
purpose of the variable
Use camel casing for variable identifiers

Variable names should conform to naming rules

9 CICS 313:Visual Basic Programming - GTUC 2021 Delivery


Variables
While executing a program, the computer needs to
hold some information.

This location is associated with a specific address


where a value can be stored and retrieved when
required.

Variables hold the data temporarily.

The value stored in a variable can vary while the


program is running.
10
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Identifiers
An identifier is a sequence of one or more letters,
digits or underscore characters (_) that is used to
distinguish one variable from the others.

Each variable needs an identifier that


distinguishes it from the others.

11 CICS 313:Visual Basic Programming - GTUC 2021 Delivery


Identifier Rules
 Neither spaces nor punctuation marks or symbols can
be part of an identifier.
 Only letters, digits and single underscore characters are
valid.
 variable identifiers always have to begin with a letter.

 They can also begin with an underline (underscore)


character (_ )

 In no case should they begin with a digit.

 Identifiers cannot match any keyword of the Visual Basic


language nor your compiler's specific ones, which are
reserved
12
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
VB Statements
 VB programs are written using statements such as those
shown below:
Dim custCount as Integer = 3
custCount += 1

 Statements represent a single VB operation and can be


composed of several elements including:
 types, VB keywords, etc.

 Statements that span more than one line require the _


continuation character:

Dim custCount as _
Integer = 3
13
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
VB Statements - Commenting

Comments allow documentation to be added into


code and/or statements to be commented out.

VB statements can be commented by using the


apostrophe (‘) character:

‘ Dim custCount as Integer = 3


‘This is my VB comment Statement

14 CICS 313:Visual Basic Programming - GTUC 2021 Delivery


Fundamental data types (1/2)
When programming, variables are stored in the
computer's Memory, the computer has to know
what kind of data we want to store.

The computer will not allocate the same amount of


memory to store a simple number or a single letter or
a large number.

Different data types are not going to be interpreted


the same way.

15 CICS 313:Visual Basic Programming - GTUC 2021 Delivery


Fundamental data types (2/2)
 Below are the basic fundamental data types in VB:
Integer
Long
Short
 single
Double
Decimal
String
Char
Boolean
Object
date
More information on VB data types
16 CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Integer Types
 Used to store only numeric values without any decimal point,
such as natural numbers, whole numbers, etc.

 Integers can be of the Long, Short or Integer types:

Short type
has a size of 2-bytes, so it can store only small values.

Integer
has a size of 4-bytes and it can store the values that
cannot to be stored by the Short integer.

Long type
has a size of 8-bytes, so it can hold large values.

17 CICS 313:Visual Basic Programming - GTUC 2021 Delivery


Double Types (1/2)
 Used to store floating point values with decimal point, such as
fractions.

 Double can be of the Single, Double and Decimal Types:

 Single type
Single has a size of 4-bytes, so it can store values with
only small number of decimal places.

 Double type
has a size of 8-bytes and can store the values that cannot
to be stored by the Single type.

Decimal type
 has a size of 16-bytes, so it can hold large values with
18
large decimal places.
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Double Types (2/2)
 Double type variables are stored internally and have a greater
accuracy and precision as compared to single type variables.

 Consider the following example:


22/7 = 3.14285714...........
 the value after the decimal will be infinite, and will exceed the
range allowed for double type variables.

 The result will be truncated.

 the fractional values cannot always be represented accurately


in the computer memory;

 more precision requires more memory.


19
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Data Types (2/4)
Boolean Type
The Boolean type variable stores true/false values.
The Boolean variables are integers that take 1 for true and
0 for false.
Boolean variables are also combined with the logical
operators
 AND, OR, NOT, and XOR.

String Type
These type of variables can only store text.

Char Type
A character variable stores a single character in two bytes.
20
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Numeric Data Types
Type Storage Range of Values
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.
-922,337,203,685,477.5808 to
Currency 8 bytes
922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no
decimal is use
Decimal 16 bytes
+/- 7.9228162514264337593543950335 (28 decimal
places).
23
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Non-numeric Data Types
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


January 1, 100 to
Date 8 bytes
December 31, 9999
Boolean 2 bytes True or False

Object 4 bytes Any embedded object


Any value as large as
Variant(numeric) 16 bytes
Double
Same as variable-
Variant(text) Length+22 bytes
length string
24
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Declaring a Variable in Code (1/3)
 Declaration statement:
 A statement that helps a language to create a variable in
memory is called a variable declaration statement.

 Declaration statement includes


 Scope keyword: Dim, Private, or Static
 Name of the variable (Identifier)
 Data type
 Initial value (optional)

 Numeric data types are automatically initialized to 0

 String data type is automatically initialized to “”

25
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Declaration of Variables (2/3)
The syntax for declaring a variable is as follows:

Dim VariableName As Data Type


For example:
Dim Area As Integer
Dim stands for dimension and it directs the compiler
that a variable is being declared.
The word Area is the name (identifier) of the
variable.
The term As Integer is used to specify that the
variable will hold an integer value.
26
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Declaration of Variables (3/3)
 You can declare multiple variables in a single statement.
 A comma separates these variables from one another.

Dim VariableName1, VariableName2, VariableNameN As Data Type

For example,
Dim Area, Perimeter As Integer

 You can also declare multiple variables of the same or different types
within a single statement.

Dim VariableName1 As Integer, VariableName2 As String

For example,
Dim Area As Integer, Name As String

27
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Initializing a Variable
 Initializing a variable means assigning an initial value to a
variable while declaring it.
 The syntax of initializing a variable is as follows:

Dim Variable Name As Datatype = initial value

For example,
Dim Area As Integer = 254
 You can also initialize multiple variables of the same or
different types within a single statement.
 The syntax is follows:
Dim Variable Name 1 As Datatype = initial value, Variable name 2 = initial value

For example,
Dim Area As Integer = 254, Name As String = “Smith”
28
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
The Scope and Lifetime of a Variable
Scope:
indicates where the variable can be seen and
used

Lifetime:
indicates how long the variable remains in
memory

Variables can have:


Module scope
Procedure scope
Block scope
29
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Block scope
 Variables are declared within a block of code

 Only the block can see this variable

Private Sub btnSum_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles btnSum.Click

Dim x As Integer
For x = 0 To 50 Step 1
Dim S As Integer
S=S+x
MessageBox.Show(“ The sum is ” & S)
Next

End Sub

30
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Procedure Scope (1/2)
 Procedure-level variable:
Declared within a procedure
Use the Dim keyword in the declaration

 Procedure scope:
only the procedure can use the variable
With procedure-level scope, two procedures can each use
the same variable names

31
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Procedure Scope (2/2)
Private Sub btnTaxCalc_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnTaxCalc.Click
‘Declare Variables
Dim sales As Double
Dim tax1 As Double
‘Calculate and display the sales tax
Double.TryParse(txtSales.Text, sales)
Tax1 = sales * 0.02
lblTax.Text = tax1.ToString
End Sub
Private Sub btnTaxCalc2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnTaxCalc2.Click
‘Declare Variables
Dim sales As Double
Dim tax2 As Double
‘Calculate and display the sales tax
Double.TryParse(txtSales.Text, sales)
Tax2 = sales * 0.05
lblTax.Text = tax2.ToString
32
End Sub
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Procedure Scope (2/2)
Private Sub btnTaxCalc_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnTaxCalc.Click
‘Declare Variables
Dim sales As Double
Dim tax1 As Double
‘Calculate and display the sales tax
Double.TryParse(txtSales.Text, sales)
Tax1 = sales * 0.02
lblTax.Text = tax1.ToString
End Sub
Private Sub btnTaxCalc2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnTaxCalc2.Click
‘Declare Variables
Dim sales As Double
Dim tax2 As Double
‘Calculate and display the sales tax
Double.TryParse(txtSales.Text, sales)
Tax2 = sales * 0.05
lblTax.Text = tax2.ToString
33
End Sub
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Module Scope (1/2)
 Module scope:
 variable can be used by all procedures in the form
variable is declared in the form’s Declarations section
 Module-level variable:
Declared in the form’s Declarations section
Use Private keyword in declaration

 Module-level variables retain their values until the


application ends
Variables declared within a procedure have either
procedure scope or block scope

35
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Module Scope (2/2)
Option Explicit On
Option Strict On
Option Infer Off

Public Class Form1

‘Module level variable used to store the sales amount


Private sales As Double

Private Sub btnTaxCalc_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles btnTaxCalc.Click
‘Declare Variables
Dim tax1 As Double
‘Calculate and display the sales tax
Double.TryParse(txtSales.Text, sales)
Tax1 = sales * 0.02
lblTax.Text = tax1.ToString
End Sub
Private Sub btnTaxCalc2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnTaxCalc2.Click
‘Declare Variables
Dim tax2 As Double
‘Calculate and display the sales tax
Double.TryParse(txtSales.Text, sales)
Tax2 = sales * 0.05
lblTax.Text = tax2.ToString
36 End Sub
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Static Variables (1/2)
 Static variable:
Procedure-level variable that retains its value even
after the procedure ends
Retains its value until the application ends (like a
module-level variable), but can only be used by the
procedure in which it is declared

 A static variable has:


Same lifetime as a module-level variable
Narrower scope than a module-level variable

 Declared using the Static keyword


38
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Static Variables (2/2)
Option Explicit On
Option Strict On
Option Infer Off

Public Class Form1

Private Sub btnTotalSales_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles btnTotalSales.Click

‘Declare Variables
Dim salesAmount As Decimal
Static totalSales as Decimal

‘Calculate and display the total sales


Decimal.TryParse(txtSales.Text, salesAmount)
totalSales = totalSales + salesAmount
lblTotalSales.Text = totalSales.ToString
End Sub
39
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Named Constants (1/3)

Memory location whose value cannot be changed


while the application is running

Declared using the Const keyword

Good programming practice to specify the data


type as well

Many programmers use Pascal case for named


constants
41
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Named Constants (2/3)
 Syntax
Const constantName As DataType = Expression

 Example 1
Const Pi As Double = 3.141593

 example 2
Const MaxHours As Integer = 40

43
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Named Constants (3/3)
Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1

Private Sub btnCalc_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles btnCalc.Click
‘Calculate the area of a circle
‘Declare Variables
Const Pi As Double = 3.141593
Dim radius As Double
Dim Area As Double

‘Calculate and display the area


Double.TryParse(txtRadius.Text, radius)
Area = Pi * radius * radius
lblArea.Text = Area.ToString
End Sub
44
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Data Type Conversion
You can convert the data type of a variable from one
type to another with the help of certain functions
provided by VB.NET. Such as the:
 Type Conversion Functions

CType Function

TryParse Method

Convert Class

etc

46
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Type Conversion Functions
These methods can be Arguments
used to convert data Function converted to
from any data type to any CChar Character
CByte Byte
data type in VB.
CBool Boolean
CDate Date
Care must be taken to CDec Decimal
make sure the converted CInt Integer (4 byte)
data will remain useful CLng Long (8 byte)
CShort Short (2 byte)
Be sure you are not CStr String
converting a string of CDbl Double
ALPHABETS to a numeric CSng Single
data type
47
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Type Conversion - Examples

Convert an Integer type variable x to a Double


type variable y:

Dim x As Integer
Dim y As Double
y = CDbl (x)

48
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
The CType Function
 Returns the result of explicitly converting an expression
to a specified data type.
 Syntax
CType(expression, typename)

 Expression
 Any valid expression.
 If the value of expression is outside the range allowed by
typename, Visual Basic throws an exception.

 Typename
 The name of any data type, object, structure, class, or interface.
 Any expression that is legal within an As clause in a Dim
statement
49
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
CType Function -Examples

The following statement is used to convert the


value of variable x to Double:

Dim x As Integer = 53
Dim y As Double
y = CType(x, Double)

50
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Using the TryParse Method (1/2)
 Method:
 a specific portion of a class’s instructions that performs a
task for the class

 TryParse method:
 Part of every numeric data type’s class
 Used to convert a string to that numeric data type

 Argument:
 a value that is provided to a method

 Basic syntax of TryParse method has two arguments:


 String: string value to be converted
 Variable: location to store the result
51
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Using the TryParse Method (2/2)
If TryParse conversion is successful, the method
stores the value in the variable

If unsuccessful, a 0 is stored in the numeric variable

dataType.TryParse(string, Variable)

Dim sales As Double


Double.TryParse(salesTextBox.Text, sales)

Dim num As Integer


Integer.TryParse(numTextbox.Text, num)
52
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Using the Convert Class
 Convert class:
Contains methods for converting numeric values to
specific data types

 Use the dot member access operator to separate the


class name from the method name

 Commonly used methods of the Convert class include:


ToDouble
Convert.Method(Value)
ToDecimal
ToInt Dim rate As Decimal = Convert.ToDecimal(.05)
ToString
Dim testScore As Integer = 98
totalLabel.Text = Convert.Tostring(testScore)
53
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Option Explicit, Option Infer,
and Option Strict (1/3)
 Undeclared variable:
 a variable that does not appear in a declaration statement
(such as Dim) is assigned a data type of Object
 Misspelling a variable name can result in an undeclared
variable unless Option Explicit is on

 Option Explicit On statement


 Appears in the General Declarations section of the Code
Editor window (above Public Class statement)

 Enforces that all variables must be declared before being


used

54
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Option Explicit, Option Infer,
and Option Strict (2/3)
 Option Infer Off statement:
 ensures that every variable is declared with a data type

 Implicit type conversion:


 occurs when you attempt to assign data of one type to a
variable of another type without explicitly attempting to convert it

 If converted to a data type that can store larger numbers, the


value is said to be promoted

 If converted to a data type that can store only smaller numbers,


the value is said to be demoted
 Can cause truncation and loss of precision

55
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Option Explicit, Option Infer,
and Option Strict (3/3)
 Option Strict On statement:
ensures that values cannot be converted from one data
type to a narrower data type, resulting in lost precision

56
CICS 313:Visual Basic Programming - GTUC 2021 Delivery
Any Questions?

57 CICS 313:Visual Basic Programming - GTUC 2021 Delivery

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy