COSC226 Module3

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 74

Visual Basic.

NET

COSC 226
TOPIC: VB.Net Basic Syntax
Outline:

 Identifiers, Keywords, Operators, comments,


 Data types
 VB Type Conversion
 Variables and Constants
Introduction:

 VB.Net is an object-oriented programming language.


 Apart from objects, classes and methods, VB.Net programs consist
of important ingredients such as:
 Identifiers,
 Keywords,
 Operators,
 Comments,
 Data types,
 Variables, and
 Constants
Identifiers:
 An identifier is a name used to identify a class, Some valid identifiers are:
variable, function, or any other user-defined • Value, a, rec1, my_data, Marks, num, etc.
elements in the program.
 The basic rules for naming classes in VB.Net are as Some invalid identifiers are:
follows:
• 5be: First character should be alphabets
 The first character of an identifier must start with an alphabet or or underscore (_)
underscore, that could be followed by any sequence of digits (0-9), • Class, Shared: Keyword are not allowed
letter or underscore. as identifier name.
 An identifier should not contain any reserved keyword. • A#: Identifier does not contain any
 It should not start with any digit. special symbol.
 It should not be more than 51 characters. • Avg marks: It should not contain any
blank space.
 It must not contain any embedded space or symbol like ? - +! @ # % ^
& * ( ) [ ] { } . ; : " ' / and \. However, an underscore ( _ ) can be used.
 An identifier can contain two underscores, but should not be
consecutive.
• Identifiers must begin with either an alphabetic or
underscore character, may be of any length and after
the first character must consist of only alphanumeric
and underscore characters.
• Identifiers are names given to namespaces, types
(structures, standard modules, classes), type
members(methods, events).
• Valid Identifiers: x, names, y12, area, sum_1, tax_rate,
table, MaximumCheck, CompanyName, value1,
xy_coordinate, __total and cmdExit. intFeb_Income,
dec Sales2014, dblEastRegion, StrName
• Invalid identifiers: 4th, “x”, order-no, error flag, i
Number Sold, Number.Sold, sng$Amount, sub,
caption, 7Welcome, input field.4thQuarter (The name
must begin with a letter or underscore), dblWest
Region(The name cannot contain a space),
StrFirst.Name (The name cannot contain
punctuation), decSales$East (The name cannot
contain a special character)
Visual Basic Code Statement
The first project requires two visual basic statements: the
Remark and the Assignment statement.
The Remark Statements sometimes called comments are used
for project documentation only. The purpose of remarks is to
make the project more readable and understandable by the
people who read it. VB remarks begin with an apostrophe e.g
` this project was written by Adeola.
`Exit the project
lblMessage.Text= “Hello world” `assign the message to the
text property.
Comment statement begin with the keyword Rem
e.g Rem This is a Remark
` This is a remark
Assignment Statement
• It consists of a variable name followed by the
assignment operator (=) followed by some sort of
expression.
• It assigns a value to a property or variable. It operates
from right to left i.e the value appearing on the right
side of the equal sign is assigned to the property
named on the left of the equal sign.e.g
• StartTime= Now
• BitCount=ByteCount*8
• Energy= Mass*lightspeed^2
• Networth = Assets- Liabilities
• lblTitle. Text = “A Snazzy Program”
• lblAddress.Text = “1234 South North Street”
• lblMessage. AutoSize = True
• intNumber = 12
Data Types and Variable
Datatype indicates what type of information will be
stored in the allocated memory space.
It is a set of values together with a set of operations on
those values.
Note: the default datatype is variant. If you do not
specify a datatype your variables and constants will be
variants.
The advantage of using variant datatype is that it’s easy
and constants change their appearance as needed for
each situation while the disadvantages is that variants
are less efficient than the other data types that is
variants require more memory and operate less quickly
than other datatype.
Data Types Required Space Value Range

Data types: Boolean


Byte
Char
Based on the platform
1 byte
2 bytes
True or False
Byte Range start from 0 to 255 (unsigned)
Char Range start from 0 to 65535 (unsigned)
Date 8 bytes Date range can be 0:00:0 (midnight) January 1, 0001 to 11:5959 PM of December
• A Data Type refers to which 31, 9999.

type of data or value is Decimal 16 bytes Range from 0 to +/-79,228,162,514,264,337,593,543,950,335 (+/-7.9…E+28) without
any decimal point; And 0 to +/-7.92281625142264337593543950335 with 28
assigning to a variable or position to the right of the decimal
function. Double 8 bytes -1.79769313486231570E+308 to -4.94-65645841246544E-324 for negative values;
4.94065645841246544E-324 to 1.79769313486231570E+308, for positive values
• The type of a variable
Integer 4 bytes -2,147,483,648 to 2,147,483,647 (signed)
determines how much space
Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (9.2…E + 18) (signed)
it occupies in storage and
how the bit pattern stored is Object 4 bytes in 32-bit and 8 bytes in It can store any type of data defined in a variable of type Object
64-bit platform
interpreted.
SByte 1 byte -128 to 127 (signed)
• VB.Net provides a wide range Short 2 bytes -32,768 to 32,767 (signed)

of data types as shown in the Single 4 bytes -3.4028235E + 38 to -1.401298E-45 for negative values;
And for positive value: 1.401298E-45 to 3.4028235E + 38.
table below:
String String Datatype depend on the It accepts Unicode character from 0 to approximately 2 billion characters.
implementing platform
UInteger 4 bytes The range start from 0 to 4,294,967,295 (unsigned)
ULong 8 bytes The range of ULong start from 0 to 18,446,744,073,709,551,615 (1.8…E + 19)
(unsigned)
User-Defined A user-defined data type Each member of the structure has its own data type and limits independent of the
(structure) depends on the implementing other members' ranges.
platform
UShort 2 bytes Range from 0 to 65,535 (unsigned)
The data manipulated by a VB.NET program fall into two categories.
Numeric and String.
Numeric Data must contain only numbers e.g 9,35, 85783,109,95
whereas String Data can contain any symbol. e.g Jane Arbor, 321 Lekki
Road.
Numeric values can be used in arithmetic calculations but string values
cannot be used.
Note: VB uses the term string to represent a string of characters.
Example of datatypes are Boolean (T/F), Byte(1 byte), Currency(8
bytes), Date (8 bytes), Double(8 bytes), Integer(2 bytes), Long(4 bytes),
String(16 bytes), Char, Decimal (12 bytes), Single(4 bytes),object (4
bytes), variant (16 bytes: any value as large as double).
• Variables are the memory locations that hold data
that can be changed during project execution.
• Variables are used in a program to store data items
and to retrieve the data during processing. It may
contain letters, digits or the underscore character. The
first character must be a letter.
• FleetSize, WageRate, AverageAge, MaximumCapacity,
ExtendedPrice, EmployeeNum, EmployeeName,
NumberOfSeminarParticipants.
Rules for naming variables
• All variables must be declared.
• Variable names must begin with an alphabet.
• Variable names should be meaningful and descriptive.
• It must consist of letters, digits and underscores.
• Do not use keywords as a variable name.
• They cannot contain any spaces.
• Variable is an identifier that is declared in a method and stands for a
value within that method.it is used to represent some specified type
of information within a designated portion of the program.
VB.NET Variable and Constant:
• A variable is a simple name used to store the value of a specific data
type in computer memory
• It is a memory location whose contents may changed during program
execution.
• The basic value types provided in VB.Net can be categorized as:
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and
Char
Floating point types Single and Double
Decimal types Decimal
Boolean types True or False values, as assigned
Date types Date
VB.NET Variable and Constant:
Variable Names
• The following are the rules when • Example of Valid names:
naming the variables in Visual Basic
• intFeb_Income
• It must be less than 255 characters
• decSales2014
• No spacing is allowed
It must not begin with a number • dblEastRegion

Period is not permitted • StrName

• Not case sensitive • Example of invalid names:
• It should not be a Reserved keyword( e.g. • 4thQuarter- The name must begin
Sub, End, for, Case, While, etc.) with a letter or underscore
• No special character is allow (e.g. ? - +! @ • dblWest Region -The name cannot
# % ^ & * ( ) [ ] { } . ; : " ' / \) contain a space
• Begin each variable and constant name • StrFirst.Name - The name cannot
with a letter or underscore. This is a contain punctuation
Visual Basic requirement. Variable and • decSales$East - The name cannot
constant names can contain only letters, contain a special character
underscores, and numbers.
Variable Declaration
• In Visual Basic, one needs to declare the variables before using them
by assigning names and data types.
• The declaration of a variable is simple that requires a variable name
and data type followed by a Dim.
• A Dim is used in Class, Module, structure, Sub, procedure.
Syntax:
Dim [Variable_Name] As [Data Type]
Variable Declaration cont.
• Examples:
• Dim password As String
• Dim yourName As String
• Dim firstnum As Integer
• Dim secondnum As Integer
• Dim total As Integer
• Dim doDate As Date
Variable Declaration cont.
• You may also combine them in one line , separating each variable
with a comma, as follows:

Dim password As String, yourName As String, firstnum As Integer,.............

• You can omit the Dim keyword if you specify Public, Protected,
Friend, Protected Friend, Private, Static, or Read Only.
• If you do not specify otherwise, variables you declare using a Dim
statement are Private. The following two statements are equivalent:

Dim num_ people As Integer


Private num_people As Integer
Variable Declaration cont.
• Variable Initialization in VB.Net
• Variables are initialized (assigned a value) with an equal sign followed by a
constant expression.
• The general form of initialization is:
variable_name = value;
• for example,
• Dim pi As Double
• pi = 3.14159
• You can initialize a variable at the time of declaration as follows:
• Dim pi As Double = 3.14159
• Dim StudentID As Integer = 100
• Dim StudentName As String = “Tosin Smith"
Variable Declaration cont.

• If no value is given to variable at declaration, each type assign default


value as follows:
• Numeric variables are set to 0
• Boolean variables are set to False
• Object and String variables are set to Nothing
• Date variables are set to 1/1/0001 12:00:00AM
Variable Behaviour
• Factors that determines variable behaviour:
• Data type
• Kind of data it can hold e.g.: integer, string, character etc.
• Scope
• Code that can access the variable
• Accessibility
• Code in other module that can access the variable
• Lifetime
• How long the variable value is valid
• Visibility of a variable is determine by the above factors(scope,
accessibility and lifetime)
Declaration Statement
• Declaration statements establish your project’s variables
and constants, give them names and specify the type of
data they will hold. i.e
Dim variableName As DataType
• Dim strName As String `Declare a string variable
• Dim intCounter As Integer `Declare an integer variable
• Const curDiscountRate As Currency = .15 `Declare a named constant
• Const decDiscount_Rate As Decimal `Declare a constant
• Dim password As String
• Dim yourName As String
• Dim firstnum As Integer
• Dim secondnum As Integer
• Dim total As Integer
• Dim doDate As Date
• You may also combine them in one line , separating each variable with
a comma, as follows:
Dim password As String, yourName As String, firstnum As Integer,.............

• You can initialize a variable at the time of declaration as follows:


• Dim pi As Double = 3.14159
• Dim StudentID As Integer = 100
• Dim StudentName As String = “Tosin Smith"
• Factors that determines variable behaviour:
• Data type
• Kind of data it can hold e.g.: integer, string, character etc.
• Scope
• Code that can access the variable
• Accessibility
• Code in other module that can access the variable
• Lifetime
• How long the variable value is valid
• Visibility of a variable is determine by the above factors(scope,
accessibility and lifetime)
Performing INPUT and OUTPUT in VB.NET
• Accepting Values from User:
• The Console class in the System namespace provides two input
functions
• Read()
• Reads the next character from the standard input stream
• Readline()
• Reads a line of characters from the standard input stream
• For example:
Dim message As String
message = Console.ReadLine()
surname = Console.Read()
Performing INPUT and OUTPUT in VB.NET cont.
• Displaying output to the user:
• The Console class in the System namespace also provides two functions for
displaying output:
• write()
• Writes the specified data to the standard output stream
• WriteLine()
• Writes the specified data followed by a new line to the standard output stream
• Examples:
• writeLine(“COSC 202 CLASS”)
• Writeline(surName)
• Write(amount)
• Displaying output to the user:
• The Console class in the System namespace also provides two functions for
displaying output:
• write()
• Writes the specified data to the standard output stream
• WriteLine()
• Writes the specified data followed by a new line to the standard output stream
• Example:
• writeLine(“COSC 202 CLASS”)
• Writeline(“surname”)
• Write(amount)
Declaring Constants:

• In VB.Net, constants are declared using the Const statement. The


Const statement is used at module, class, structure, procedure, or
block level for use in place of literal values.
• The syntax for the Const statement is:
Const constantName [As datatype] = initializer
• Examples:
• ' The following statements declare constants.
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415
• Special Character Constants:
• Character Meaning in Life
• Back (VbBack) Represents a backspace character.
• Cr(VbCr) Represents a carriage return character.
• CrLf(VbCrLf) Represents a carriage return/line feed character
combination.
• Lf(VbLf) Represents a line feed character.
• NewLine(VbNewLine) Represents a new line character.
• Tab(vbTab) Represents a tab character.
• For example, to print a string that contains a tab between each word
and then enters a new line
• before the last character, you can make use of the vbTab and VbCrLf
constant characters.
• Consider the following:
• Sub ConstantChars()
• Console.WriteLine("=> Constant characters: ")
• Console.WriteLine("Model" + VbTab + "Color"+ VbTab + "Speed" + VbCrLf +
"Pet Name")
CONSTANT

• Constants are the memory location that hold data that cannot be
change during execution.
• The format for defining a constant named PI with a value 3.14159
• Const PI= 3.14159
• Constant is a data item whose value is specified at design time
and cannot change at the run time.
• There are 2 literal constant
• Numeric Literal constant e.g 123, 1.23, +123, .1, -6, 8.9E+3, 8.9E-
6
• String Literal constant e.g “John Doe”
• Note: A numeric literal constant can be used in arithmetic
calculations but can contain only certain symbols (digits, decimal
point) while a string literal constant cannot be used in arithmetic.
Keywords

• Keywords are words with special meaning in a


programming language. Keywords are reserved e.g As,
Do, Double, Case, For, Else, If, Imports, Select etc.
• Keywords are not allowed nor are spaces, commas or
punctuation marks.
• Declare a variable of myMonth of datatype char and
initialize it to X.
• Dim myMonth As Character = ‘X’c
• Dim myMonth As Character
• myMonth = ‘X’c
• Write a double line statement to display
‘ Have a good day’ to the output screen.
Console.WriteLine (“’ Have a”)
Console.WriteLine (“good day’”)
• Give an example of string literal.
• “my name is wumi”
• Give 2 examples of variable with their datatype.(Note : Give different datatype)
Exercise
• Write declarations for each variable
• i.Lenght and momentOfIntertia of type double.
• ii. population and year of type integer.
• iii. mileage of type double, cost and distance of type decimal.
• iv. alpha and beta of type byte, code of type string and root of type
single.
• Write declarations to declare each variable to have the specified type
and initial value. numberOfDeposits and numberOfChecks to be type
integer, each with an initial value of 0; totalDeposits and totalChecks
to be of type double, each with an initial value of 0.0 and
serviceCharge to be of type single with an initial value of 0.2.
Types of Literal

• Literal are representations of values within the text of a


program.
• X = y *10 , 10 is a literal of type integer
• Integer Literal is within the range of the integer type. It
ranges from -2147483648 -2147483647.
• Numeric Literal can also be of one of the floating point types.
• Z = y*3.14 3.14 is a literal of type double. It ranges from -
1.7976931348623157E308-1.7976931348623157E308
• String Literal: Literal of type string consist of characters
enclosed within quotation mark characters.
• Console.WriteLine (“hello world”)
• Console.WriteLine(“ So then Dave said, “hello world””)
• Character Literals: literals of type char consist of a
single character enclosed within quotation mark
characters, followed by the character C.
• Dim MyChar As Char
• MyChar = ‘A’c
• Boolean Literals: the keywords True and False are the
only boolean literals. They represent the true and
false boolean states.
• Dim MyBoolean As Boolean
• MyBoolean = True.
Literal Formats
Data type LIteral Examples
Boolean True/false Dim bFlag As Boolean = False
Char C Dim chVal As Char = ‘x’c
Date ## Dim datMillen As Date = #01/01/2001#
Decimal D Dim decValue As Decimal = 6.14D
Double R Dim dblValue As Double = 6.142R
Integer I Dim iValue As integer = 362I
Long L Dim LValue As integer = 362L
Short S Dim shValue As short = 362S
single F Dim sngValue As Single = 6.142F
String “ ” Dim strValue As String = “This is a string”
Ex
• Declaring an integer i to give an initial value of 10.
• Dim i As integer = 10
or
Dim i As Integer
i = 10
Keywords: AddHandler

Boolean
AddressOf

ByRef
Alias

Byte
And

ByVal
AndAlso

Call
As

Case

Catch CBool CByte CChar CDate CDbl


 A keyword is a reserved word CDec Char Cint Class CLng CObj

with special meanings in the Const

CType
Continue

CUnit
CSByte

CULng
CShort

CUShort
CSng

Date
CStr

Decimal
compiler, whose meaning Declare Default Delegate Dim DirectCast Do

cannot be changed. Double Each Else Elseif End End if

Enum Erase Error Event Exit False


 Therefore, these keywords Finally For Friend Function Get GetType

cannot be used as an GetXML


Namespace
Global GoTO Handles If Implements

identifier in VB.NET Imports In Inherits Integer Interface Is

programming such as class isNot

Me
Let

Mod
Lib

Module
Like

MustInherit
Long

MustOverride
Loop

MyBase
name, variable, function, MyClass Namespace Narrowing New Next Not

module, etc. Nothing Not Inheritable Not Overridable Object Of On

 The following table lists the Operator Option Optional Or OrElse Overloads

Overridable Overrides ParamArray Partial Private Property


VB.Net reserved keywords: Protected Public RaiseEvent ReadOnly ReDim REM

Remove Resume Return SByte Select Set


Handler

Shadows Shared Short Single Static Step

Stop String Structure Sub SyncLock Then

Throw To True Try TryCast TypeOf


Operators:
 In VB.NET, operator is a special symbol that tells the compiler to perform the
specific logical or mathematical operation on the data values in order to
produce result(s).
 The data value itself (which can be either a variable or a constant) is called an
operand.
 Following are the different types of Operators available in VB.NET:
 Arithmetic Operators
 Comparison/Relational Operators
 Logical and Bitwise Operators
 Assignment Operators
 Concatenation Operators
Operators:

Arithmetic operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Floating Division
\ Integer (whole number) division
Mod Remainder division
^ Exponentiation (raising to a power)
& String concatenation (combination)
Operators:
Relational operators
• Combine value(s) to returns Boolean value(true or false)
operator meaning
> Greater than
< Less than
= Equal to
<> Not equal to
>= Greater than or equal to
<= Less than or equal to
• All relational operator are binary
Operators:
Logical operators
• combine multiple Boolean expressions into a compound Boolean expression
operator description
And combine two expression into one. Returns true if both expression are true
Or combine two expression into one. if both expression evaluate to false, Or returns
false, otherwise it returns true
Not negates an expression
Xor logically joins two expressions. If both expression evaluate to true or both
expression evaluate to false, Xor returns false; otherwise it returns true
IsFalse is used to determine whether an expression is False.
IsTrue is used to determine whether an expression is True.
Operators:
Assignment operators
• The Assignment Operators are used to assign the value to variables in VB.NET.

= assigns a right-side operand or value to a left side operand.


+= adds the value of the right operand to the left operand. And the result is assigned to the left
operand.
-= subtracts the right operand or value from the left operand. And then, the result will be assigned to
the left operand.
*= multiplies the right operand or value with the left operand. And then, the result will be assigned to
the left operand.
/= divides the left operand or value with the right operand. And then, the result will be assigned to
the left operand (in floating-point).
\= divides the left operand or value with the right operand. And then, the result will be assigned to
the left operand (in integer-point division).
^= raises the left operand or value to the right operand's power. And then, the result will be assigned
to the left operand.
&= binds the right-hand string or variable with the left-hand string or variable. And then, the result
will be assigned to the left operand.
Operators:
Concatenation Operators
• In VB.NET, there are two concatenation Operators to bind the operands:

& It is an ampersand symbol that is used to bind two or more operand together.

+ It is also used to add or concatenate two number or string.

• Other operators are Bit Shift Operators and Miscellaneous Operators

Assignment: Write short note on VB.Net Bit Shift Operators and Miscellaneous
Operators.
Comments:
• A comment is used to explain the various steps that we have taken in
our programming.
• The compiler ignores these comment statements because the compiler
is not executed or processed in VB.NET.

• In VB.NET, we use ( ' ) symbol to start a comment statement.


1. Sub main()
2. 'Here Console.WriteLine() is used to print a statement.
3. Console.WriteLine(" Welcome to COSC 226 Class")
4. 'Above statement displays Welcome to JavaTpoint
5. End Sub
Class Exercises:
Let us attempt the following programming exercises to illustrate VB.Net programing
basic above.

1. Write a VB.NET console application that allow users to enter the Length and Breadth
of a rectangle, and then computes and display the Area on the screen
2. A Power company wants a program that inputs the voltage and three resistances and
then calculates and displays the current. For three resistors connected in series,
the total resistance is the sum of the individual resistances and by Ohm’s law, the
current in the circuit is given by
amps = voltage / total resistance.
Write a VB console application to computes the current(amps)

Assignment: Develop window applications to solve the programing


problem above. To be checked during the next class.
Type Conversion Functions in VB.NET:
VB.Net provides the following in-line type conversion functions:
1. CBool(expression): It is used to convert an expression into a Boolean data type.
2. CByte(expression): It is used to convert an expression to a Byte data type.
3. CChar(expression): It is used to convert an expression to a Char data type.
4. CDate(expression): It is used to convert an expression to a Date data type.
5. CDbl(expression): It is used to convert an expression into a Double data type.
6. CDec(expression): It is used to convert an expression into a Decimal data type.
7. CInt(expression): It is used to convert an expression to an Integer data type.
8. CLng(expression): It is used to convert an expression to a Long data type.
9. CObj(expression): It is used to convert an expression to an Object data type.
10. CSByte(expression): It is used to convert an expression to an SByte data type.
11. CShort(expression): It is used to convert an expression to a Short data type.
12. CSng(expression): It is used to convert an expression into a Single data type.
13. CStr(expression): It is used to convert an expression into a String data type.
14. CUInt(expression): It is used to convert an expression to a UInt data type.
15. CULng(expression): It is used to convert an expression to a ULng data type.
16. CUShort(expression): It is used to convert an expression into a UShort data type.
Class Exercises
• One way to determine how healthy a person is by measuring the body fat of the person. The formulas to determine
the body fat for female and male are as follows:
Body fat formula for women:
A1 = (body weight*0.732) + 8.987
A2 = wrist measurement / 3.140
A3 = waist measurement*0.157
A4 = hip measurement *0.249
A5 = forearm measurement*0.434
B= A1+A2-A3-A4+A5
Body fat = body weight - B
Body fat percentage = body fat*100 / body weight
Body fat formula for men:
A1 = (body weight 1.082) + 94.42
A2 = wrist measurement*4.15
B = A1-A2
Body fat = body weight - B
Body fat percentage = body fat*100 / body weight
• Write a VB program to computes and display the person gender, body fat and body fat percentage from the problem
specification above.

Assignment: Develop window applications to solve the programing


problem above. To be checked during the next class.
CONSTANT

• Constants are the memory location that hold data that cannot be
change during execution.
• The format for defining a constant named PI with a value 3.14159
• Const PI= 3.14159
• Constant is a data item whose value is specified at design time
and cannot change at the run time.
• There are 2 literal constant
• Numeric Literal constant e.g 123, 1.23, +123, .1, -6, 8.9E+3, 8.9E-
6
• String Literal constant e.g “John Doe”
• Note: A numeric literal constant can be used in arithmetic
calculations but can contain only certain symbols (digits, decimal
point) while a string literal constant cannot be used in arithmetic.
Keywords

• Keywords are words with special meaning in a


programming language. Keywords are reserved e.g As,
Do, Double, Case, For, Else, If, Imports, Select etc.

• Declare a variable of myMonth of datatype char and


initialize it to X.
• Dim myMonth As Character = ‘X’c
• Dim myMonth As Character
• myMonth = ‘X’c
• Write a double line statement to display
‘ Have a good day’ to the output screen.
Console.WriteLine (“’ Have a”)
Console.WriteLine (“good day’”)
• Give an example of string literal.
• “my name is wumi”
• Give 2 examples of variable with their datatype.(Note : Give different datatype)
Exercise
• Write declarations for each variable
• i.Lenght and momentOfIntertia of type double.
• ii. population and year of type integer.
• iii. mileage of type double, cost and distance of type decimal.
• iv. alpha and beta of type byte, code of type string and root of type
single.
• Write declarations to declare each variable to have the specified type
and initial value. numberOfDeposits and numberOfChecks to be type
integer, each with an initial value of 0; totalDeposits and totalChecks
to be of type double, each with an initial value of 0.0 and
serviceCharge to be of type single with an initial value of 0.2.
Types of Literal

• Literal are representations of values within the text of a


program.
• X = y *10 , 10 is a literal of type integer
• Integer Literal is within the range of the integer type. It
ranges from -2147483648 -2147483647.
• Numeric Literal can also be of one of the floating point types.
• Z = y*3.14 3.14 is a literal of type double. It ranges from -
1.7976931348623157E308-1.7976931348623157E308
• String Literal: Literal of type string consist of characters
enclosed within quotation mark characters.
• Console.WriteLine (“hello world”)
• Console.WriteLine(“ So then Dave said, “hello world””)
• Character Literals: literals of type char consist of a
single character enclosed within quotation mark
characters, followed by the character C.
• Dim MyChar As Char
• MyChar = ‘A’c
• Boolean Literals: the keywords True and False are the
only boolean literals. They represent the true and
false boolean states.
• Dim MyBoolean As Boolean
• MyBoolean = True.
Ex
• Declaring an integer i to give an initial value of 10.
• Dim i As integer = 10
or
Dim i As Integer
i = 10
Using Functions
• Functions are used to convert the property of a control
to its numeric from before you use the value in a
calculation. The function depends on the datatype of
the variable to which you are assigning the value e.g
• To convert text to an integer use the
Cint function e.g intQuantity = Cint (txtQuantity. Text)
• To convert text to a decimal value use the
CDec function e.g decPrice = Cdec (txtPrice.Text)
• To convert decimal value to a string use the
CStr function e.g strValue= CStr (decValue)
• Use Str to return a string of a number.
• Use val to convert to a number.
List of conversion Functions
Cbool Convert to Bool data type
Cbyte Convert to Byte data type
Cchar Convert to char data type
Cdate Convert to date data type
Cdbl Convert to double data type
Cint Convert to int data type
Clng Convert to Long data type
Cobj Convert to object data type
Cshort Convert to short data type
Csng Convert to single data type
Cstr Convert to string data type
Visual Data Conversion Functions
String to number val
Time to serial number TimeSerial, TimeValue
Character code to character chr

String to lowercase or Format, Lcase, Ucase,


uppercase String.ToUpper,
String.ToLower, String.Format
Date to a number DateSerial, DateValue

Decimal number to other Hex, Oct


bases

Number to string Format, Str

Character to character code Asc


Converting between characters and character code

• For example the character code 65 stands for A.


• You can use the Asc and Chr functions
• Asc takes a character and returns its character code.
E.g Asc (“A”) return 65
• Chr takes a character code and returns the
corresponding character e.g chr(65) return “A”
Ex
(a)Write two statements to add decSales to decTotalSales using
• (i)the standard, long version
• (ii) the assignment statement
Answer
(i) decTotalSales= decTotalSales + decSales
(ii) decTotalSales += decSales
(b) Write two statements to add 5 to intCount using (i)the
standard, long version (ii) the assignment statement.
(c) Write a comment of these:
decTotalSales += decSales `Accumulate a total
intCountDown = intCountDown -1 `substract 1 from variable.
• Add 5 to the value in y and assigns the result to y.
The Option and Imports statement
• When constructing programs, two statements are important
– Option and Imports statement.
• The option statement sets a number of options for the rest
of your code.
• Imports statement import namespaces into your code,
making them more readily available.
• Option statement is used to set the ground rules for your
code, helping prevent syntax and logic errors.
• Option Explicit set to on and off. On is the default requires
declaration of all variables before they are used.(this is the
default)
• Option Compare: set to binary or text. This specifies if
strings are compared using binary or text comparison
operations.
• Option Strict set to on or off. Off is the default. When
you assign a value of one type to a variable of another
type visual basic will consider that an error if this
option is on and there is any possibility of data, as
when you’re trying to assign the value in a variable to
a variable of less precise data storage capacity.
• You use Option statements first thing in code, like this
one in which I’m turning Option Strict Off.
• Option Strict Off
• Module Module1
• Sub Main ()
• System.Console.WriteLine (“Hello from
• Visual Basic”)
• End Sub
• End Module.
• Option Strict: is to prevent VB programs from automatic variable
conversions, that is implicit data type conversions. By default, Option
Strict is Off. It is always put at the top of the code to your form. E.g
Option Strict On/Off
• CDbl(parameter) – ‘typecasts to double
• CInt(parameter) – ‘typecasts to integer
• CStr(parameter) – ‘typecasts to string
• 
• (aii) Option Explicit statement ensures whether the compiler requires
all variables to be explicitly declared or not before it use in the
program. If the Option Explicit mode is OFF , Vb.Net automatically
create a variable whenever it sees a variable without proper
declaration. By default the Option Explicit is On.

• Implicit Example: Explicit Example
• x=5 Dim x As Integer = 5
• y = “Hello” Dim y As String = (“Hello” )
• The basic form of setting a control property is
• controlName.property = setting
• Type Inference is used to determine the data types of local variables
declared without an ‘As’
• .vbproj and .vb are the file extensions for visual basic project files and
form files respectively?
• CLR stands for Common Language Runtime
• Sub Procedure is a procedure that does not return a
value.
• Function is a procedure that returns a value.
• Method is a procedure that is built into a class.
• To place two or more statements on a single line, use
the colon between the statements e.g i=5: j=10.
• List 10 VB Application Development Steps
• Clearly define what the program is to do
• Visualize the application running on the computer and design its user interface
• Make a list of the controls needed
• Define values for each control's relevant properties
• List the methods needed for each control
• Create pseudocode or a flowchart of each method
• Check the code for errors
• Use Visual Basic IDE to create the forms and other controls identified in step 3
• Use Visual Basic IDE to write the code for the event procedures and other
methods created in step 6
• Attempt to run the application - find syntax errors

• 

You might also like